使用ruby和python快速开发metasploit自定义模块

使用ruby和python快速开发metasploit自定义模块

前言

本文的内容主要分为两个部分:

  1. 提供一个基本ruby模块代码框架,并快速开发自定义ruby模块
  2. 提供一个基本python模块代码框架,并快速开发自定义python模块

知识拓展

metsploit中,根据模块的用途对模块进行的分类,在实际开发过程中coder需要将新增的自定义模块放到对应的分类目录中。此外在python开发模块时,需要在在metadata中的type字段(string类型)正确设置其分类。分类如下:

  • encoder,编码器模块
  • exploit,渗透攻击模块
  • nop,空指令模块
  • auxiliary,分析辅助模块
  • payload,攻击载荷模块
  • evasion,从metasploit5.0开始新增加的模块,利用该模块可以轻松的创建反杀毒软件的木马,以及一些病毒代码,听起来很厉害的样子哟。
  • post,后渗透攻击模块

基本ruby模块代码框架

整个开发过程分5步走:

  1. 使用class关键字定义MetasploitModule类(老版本是Metasploit3的类名,如果继续使用老版本类名metasploit在启动加载模块时,会报错的哟。);

  2. 设定模块的Rank等级。有关如何设定Rank等级,请点击查看metasploit wiki

    Rank定义的源码如下:

    #
    # Module rankings
    #
    ManualRanking       = 0
    LowRanking          = 100
    AverageRanking      = 200
    NormalRanking       = 300
    GoodRanking         = 400
    GreatRanking        = 500
    ExcellentRanking    = 600
    RankingName         =
      {
        ManualRanking    => "manual",
        LowRanking       => "low",
        AverageRanking   => "average",
        NormalRanking    => "normal",
        GoodRanking      => "good",
        GreatRanking     => "great",
        ExcellentRanking => "excellent"
      }
    
  3. 设定info信息;

  4. 注册漏洞利用所需要的参数;

  5. 将漏洞利用代码写到MetasploitModule类的exploit方法中;

基本的Exploit模板代码如下:

require 'msf/core'
# Msf::Exploit::Remote类是漏洞利用模块类,专门针对针对本地计算机以外的目标执行的漏洞利用。这通常意味着通过网络连接来利用其他计算机,尽管不限于此范围。
class MetasploitModule < Msf::Exploit::Remote
	Rank = ExcellentRanking # 设定Rank等级

	def initialize(info = {})
        # 设定exploit的info信息
		super(update_info(info,
			'Name'           => 'Fake Test Module',
			'Description'    => %q{
				If this module loads, you know you're doing it right.
			},
			'License'        => MSF_LICENSE,
			'Author'         =>
				[
					'ronnie88597'
				],
			'References'     =>
				[
					[ 'CVE', '1970-0001' ]
				],
			'Platform'          => [ 'win' ],
			'Targets'        =>
				[
					['Universal', {}]
				],
			'DisclosureDate' => 'Jan 01 1970',
			'DefaultTarget'  => 0))
        # 注册漏洞利用所需要的参数
		register_options(
			[
				OptString.new('DATA', [ true, 'The output data', 'Hello, world!'])
			], self.class)
	end
    # 当用户在msfconsole中使用run/exploit命令时,将会初始化该exploit模块,并且调用exploit方法
	def exploit
        # 自定义模块时,主要的逻辑代码放在此处 ---start
		data = datastore['DATA']
		# echo the data
		print_good(data)
        # 自定义模块时,主要的逻辑代码放在此处 ---end
	end
end

基本的Auxiliary模板代码如下:

require 'msf/core'
class MetasploitModule < Msf::Auxiliary
  include Msf::Auxiliary::Scanner
  Rank = ExcellentRanking # 设定Rank等级

  def initialize(info = {})
    # 设定axuiliary的info信息
    super(update_info(info,
                      'Name'           => 'test_auxiliary',
                      'Description'    => %q{
				If this module loads, you know you're doing it right.
			},
                      'License'        => MSF_LICENSE,
                      'Author'         =>
                          [
                              'ronnie88597'
                          ],
                      'References'     =>
                          [
                              [ 'CVE', '1970-0001' ]
                          ],
                      'Platform'          => [ 'win','linux' ],
                      'Targets'        =>
                          [
                              ['Universal', {}]
                          ],
                      'DisclosureDate' => 'Jan 01 1970',
                      'DefaultTarget'  => 0))
    # 注册漏洞利用所需要的参数
    register_options(
        [
            OptString.new('DATA', [ true, 'The output data', 'Hello, world!'])
        ], self.class)
  end

  # 当用户在msfconsole中使用run命令时,将会初始化该auxiliary模块,并且调用run方法
  def run
    # 自定义模块时,主要的逻辑代码放在此处 ---start
    data = datastore['DATA']
    # echo the data
    print_good("good=>#{datastore['DATA']}, #{datastore['RHOSTS']}")
    print_status("status=>#{datastore['DATA']}, #{datastore['RHOSTS']}")
    print_warning("warning=>#{datastore['DATA']}, #{datastore['RHOSTS']}")
    print_error("error=>#{datastore['DATA']}, #{datastore['RHOSTS']}")
    # 自定义模块时,主要的逻辑代码放在此处 ---end
  end
end

整个ruby私有模块的开发过程在metasploit的github-wiki上有,此处不在多余赘述了,点击查看

基本python模块代码框架

相对于ruby写自定义模块,使用python会略微复杂一点点。毕竟ruby是metasploit的亲儿子嘛。

注意使用reload_all命令仅能够加载~/.msf4/modules目录下的ruby模块和ruby测试文件,可加载的文件后缀名为.rb,并且不包括满足正则表达式UNIT_TEST_REGEX = /rb\.(ut|ts)\.rb$/的文件。所以不要将python模块代码放在~/.msf4/modules目录下

在metasploit开发python模块的正确姿势,以我当前开发模块名为例——test_module_py:

  1. metasploit-framework/db/modules_metadata_base.json文件中添加test_module_py模块相关的metadata,如下:

      "auxiliary_scanner/teradata/test_module_py": {
        "name": "test_module_py",
        "fullname": "auxiliary/scanner/teradata/test_module_py",
        "aliases": [
    
        ],
        "rank": 300,
        "disclosure_date": "2018-03-30",
        "type": "auxiliary",
        "author": [
          "Ted Raffle (actuated)"
        ],
        "description": "test_module_py.\ntest_module_py.\ntest_module_py.",
        "references": [
          "URL-https://developer.teradata.com/tools/reference/teradata-python-module",
          "URL-https://downloads.teradata.com/download/connectivity/odbc-driver/linux"
        ],
        "platform": "",
        "arch": "",
        "rport": 1025,
        "autofilter_ports": [
    
        ],
        "autofilter_services": [
    
        ],
        "targets": null,
        "mod_time": "2019-11-01 19:20:22 +0000",
        "path": "/modules/auxiliary/scanner/teradata/test_module_py.py",
        "is_install_path": true,
        "ref_name": "scanner/teradata/test_module_py",
        "check": false,
        "post_auth": true,
        "default_credential": false,
        "notes": {
          "AKA": [
            "test_module_py test_module_py"
          ]
        },
        "needs_cleanup": false
      },
    
  2. 在metadata中指定的path:modules/auxiliary/scanner/teradata/test_module_py.py处,创建模块代码文件test_module_py.py

  3. python模块的模板

    #!/usr/bin/env python3 
    # -*- coding: utf-8 -*- 
    
    # standard modules 
    import logging
    
    # extra modules 
    dependencies_missing = False
    try:
        import requests
    except ImportError:
        dependencies_missing = True
    
    from metasploit import module
    
    metadata = {'name': 'Python Module Example',
                'description': ''' Python communication with msfconsole. ''',
                'authors': ['ronnie88597'],
                'date': '2018-03-22',
                'license': 'MSF_LICENSE',
                'references': [
                    {
                        'type': 'url',
                        'ref': 'Regifting Python in Metasploit'
                    },
                    {
                        'type': 'aka',
                        'ref': 'Coldstone'
                    }
                ],
                'type': 'single_scanner',
                'options': {
                    'DATA': {
                        'type': 'string',
                        'description': 'The output data.',
                        'required': True,
                        'default': 'Hello, world!'
                    }
                }
                }
    
    
    def exploit(args):
        # 自定义模块时,主要的逻辑代码放在此处 ---start
        module.log("%s" %args['DATA']) # 如果要打印信息到msfconsole的话,必须使用module.log函数哟。
        # 自定义模块时,主要的逻辑代码放在此处 ---end
    
    
    if __name__ == '__main__':
        module.run(metadata, exploit)
    
  4. 这步非常关键,需要为文件test_module_py.py增加可执行权限,如下命令:

    chmod 755 test_module_py.py
    

    如果python模块文件没有可执行权限,metasploit将会以为它是ruby文件,在加载模块时会报错的,metasploit会去寻找modules/auxiliary/scanner/teradata/test_module_py.rb而不是modules/auxiliary/scanner/teradata/test_module_py.py

  5. 启动msfconsole,由于没有将python自定义模块放在私有模块目录(~/.msf4/modules)中,所以启动msfconsole,已经将test_module_py模块加载进来了。

  6. 运行模块

    msf6 > search test_module
    
    Matching Modules
    ================
    
       #  Name                                       Disclosure Date  Rank       Check  Description
       -  ----                                       ---------------  ----       -----  -----------
       0  auxiliary/scanner/teradata/test_module_py  2018-03-22       normal     No     Python Module Example
       1  exploit/windows/apache/test_module         1970-01-01       excellent  No     Fake Test Module
    
    
    Interact with a module by name or index, for example use 1 or use exploit/windows/apache/test_module
    
    msf6 > info auxiliary/scanner/teradata/test_module_py
    
           Name: Python Module Example
         Module: auxiliary/scanner/teradata/test_module_py
        License: Metasploit Framework License (BSD)
           Rank: Normal
      Disclosed: 2018-03-22
    
    Provided by:
      ronnie88597
    
    Check supported:
      No
    
    Basic options:
      Name     Current Setting  Required  Description
      ----     ---------------  --------  -----------
      DATA     Hello, world!    yes       The output data.
      RHOSTS                    yes       The target host(s), range CIDR identifier, or hosts file with syntax 'file:<path>'
      THREADS  1                yes       The number of concurrent threads (max one per host)
    
    Description:
      Python communication with msfconsole.
    
    References:
      Regifting Python in Metasploit
      AKA (Coldstone)
    
    msf6 > use auxiliary/scanner/teradata/test_module_py
    msf6 auxiliary(scanner/teradata/test_module_py) > set RHOSTS 127.0.0.1
    RHOSTS => 127.0.0.1
    msf6 auxiliary(scanner/teradata/test_module_py) > run
    
    [*] Running for 127.0.0.1...
    [*] Hello, world!
    [*] Scanned 1 of 1 hosts (100% complete)
    [*] Auxiliary module execution completed
    
  • 9
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值