Metasploit 模組開發基礎

Metasploit Module Development Fundamentals

模組開發概述

Metasploit Framework 是滲透測試領域中最廣泛使用的開源工具之一。其強大之處在於模組化架構,允許安全研究人員根據需求開發自訂模組。本文將介紹如何開發 Metasploit 模組,從基礎概念到實際撰寫程式碼。

Metasploit 模組使用 Ruby 語言撰寫,利用框架提供的 API 和 Mixin 來簡化開發流程。透過了解模組結構和開發規範,您可以快速建立符合需求的安全測試工具。

模組類型介紹

Metasploit 提供多種模組類型,每種類型有其特定用途:

模組類型說明
Exploits利用漏洞取得目標系統存取權限
Auxiliary輔助功能模組,如掃描、嗅探、模糊測試
Post取得存取權後的後滲透模組
Payloads在目標系統執行的惡意程式碼
Encoders編碼 Payload 以規避偵測
Nops產生 NOP 指令以維持 Payload 穩定性

開發環境設定

開始開發前,需要設定適當的開發環境:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
# 安裝 Metasploit Framework
curl https://raw.githubusercontent.com/rapid7/metasploit-omnibus/master/config/templates/metasploit-framework-wrappers/msfupdate.erb > msfinstall
chmod 755 msfinstall
./msfinstall

# 設定開發目錄
mkdir -p ~/.msf4/modules/exploits
mkdir -p ~/.msf4/modules/auxiliary

# 安裝 Ruby 開發工具
gem install bundler
gem install rubocop

建議使用 IDE 如 VS Code 並安裝 Ruby 擴充套件,以獲得語法高亮和自動完成功能。

模組結構說明

每個 Metasploit 模組都遵循特定的結構。以下是基本的模組架構:

 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
32
33
34
35
36
37
##
# This module requires Metasploit: https://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##

class MetasploitModule < Msf::Auxiliary
  # 引入所需的 Mixin
  include Msf::Exploit::Remote::HttpClient

  def initialize(info = {})
    super(update_info(info,
      'Name'           => '模組名稱',
      'Description'    => %q{
        模組描述
      },
      'Author'         => ['作者名稱'],
      'License'        => MSF_LICENSE,
      'References'     =>
        [
          ['CVE', '2024-XXXX'],
          ['URL', 'https://example.com/vulnerability']
        ],
      'DisclosureDate' => '2024-06-21'
    ))

    # 註冊選項
    register_options(
      [
        OptString.new('TARGETURI', [true, '目標路徑', '/'])
      ]
    )
  end

  def run
    # 模組主要邏輯
  end
end

撰寫 Auxiliary 模組

Auxiliary 模組適合用於掃描和資訊收集。以下是一個 HTTP 版本掃描模組範例:

 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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
##
# HTTP Server Version Scanner
##

class MetasploitModule < Msf::Auxiliary
  include Msf::Exploit::Remote::HttpClient
  include Msf::Auxiliary::Scanner
  include Msf::Auxiliary::Report

  def initialize(info = {})
    super(update_info(info,
      'Name'           => 'HTTP Server Version Scanner',
      'Description'    => %q{
        掃描目標主機的 HTTP 伺服器版本資訊
      },
      'Author'         => ['Security Researcher'],
      'License'        => MSF_LICENSE
    ))

    register_options(
      [
        Opt::RPORT(80),
        OptString.new('TARGETURI', [true, '目標路徑', '/'])
      ]
    )
  end

  def run_host(ip)
    begin
      res = send_request_cgi({
        'method' => 'GET',
        'uri'    => normalize_uri(target_uri.path)
      })

      if res
        server = res.headers['Server'] || 'Unknown'
        print_good("#{ip}:#{rport} - Server: #{server}")

        report_service(
          host: ip,
          port: rport,
          name: 'http',
          info: server
        )
      end
    rescue ::Rex::ConnectionError
      print_error("#{ip}:#{rport} - 連線失敗")
    end
  end
end

撰寫 Exploit 模組基礎

Exploit 模組用於利用漏洞取得系統存取權。以下是基本架構:

 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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
##
# Example Exploit Module
##

class MetasploitModule < Msf::Exploit::Remote
  Rank = NormalRanking

  include Msf::Exploit::Remote::HttpClient

  def initialize(info = {})
    super(update_info(info,
      'Name'           => 'Example Remote Code Execution',
      'Description'    => %q{
        此模組示範遠端程式碼執行漏洞的利用
      },
      'Author'         => ['Researcher'],
      'License'        => MSF_LICENSE,
      'References'     =>
        [
          ['CVE', '2024-12345']
        ],
      'Platform'       => ['unix', 'linux'],
      'Arch'           => ARCH_CMD,
      'Targets'        =>
        [
          ['Automatic', {}],
          ['Linux', { 'Platform' => 'linux' }]
        ],
      'Privileged'     => false,
      'DisclosureDate' => '2024-06-21',
      'DefaultTarget'  => 0
    ))

    register_options(
      [
        Opt::RPORT(8080),
        OptString.new('TARGETURI', [true, '漏洞路徑', '/vulnerable'])
      ]
    )
  end

  def check
    res = send_request_cgi({
      'method' => 'GET',
      'uri'    => normalize_uri(target_uri.path)
    })

    if res && res.body.include?('Vulnerable Version 1.0')
      return Exploit::CheckCode::Vulnerable
    end

    Exploit::CheckCode::Safe
  end

  def exploit
    print_status("正在傳送 Payload...")

    res = send_request_cgi({
      'method'   => 'POST',
      'uri'      => normalize_uri(target_uri.path),
      'vars_post' => {
        'cmd' => payload.encoded
      }
    })

    if res && res.code == 200
      print_good("Payload 傳送成功")
    else
      fail_with(Failure::UnexpectedReply, "伺服器回應異常")
    end
  end
end

Mixin 使用

Mixin 是 Metasploit 提供的可重用程式碼模組。常用的 Mixin 包括:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
# HTTP 客戶端功能
include Msf::Exploit::Remote::HttpClient

# TCP 連線功能
include Msf::Exploit::Remote::Tcp

# SMB 協定支援
include Msf::Exploit::Remote::SMB::Client

# 檔案操作
include Msf::Exploit::FileDropper

# 報告功能
include Msf::Auxiliary::Report

# 掃描功能
include Msf::Auxiliary::Scanner

使用 Mixin 後可呼叫其提供的方法:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
# HttpClient Mixin 提供的方法
res = send_request_cgi({
  'method' => 'GET',
  'uri'    => '/api/data',
  'headers' => {
    'Authorization' => 'Bearer token123'
  }
})

# 檢查回應
if res && res.code == 200
  data = JSON.parse(res.body)
  print_good("取得資料: #{data}")
end

測試與除錯

開發完成後需要進行測試。Metasploit 提供多種除錯方式:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
# 重新載入模組
msf6 > reload_all

# 載入特定模組
msf6 > use auxiliary/scanner/http/my_scanner

# 顯示選項
msf6 auxiliary(scanner/http/my_scanner) > show options

# 設定選項
msf6 auxiliary(scanner/http/my_scanner) > set RHOSTS 192.168.1.100
msf6 auxiliary(scanner/http/my_scanner) > set RPORT 8080

# 執行模組
msf6 auxiliary(scanner/http/my_scanner) > run

在程式碼中使用除錯輸出:

1
2
3
4
5
6
7
def run
  vprint_status("詳細模式輸出")  # 僅在 VERBOSE 啟用時顯示
  print_status("一般狀態訊息")
  print_good("成功訊息")
  print_warning("警告訊息")
  print_error("錯誤訊息")
end

使用 RSpec 進行單元測試:

1
2
3
4
5
6
7
8
9
RSpec.describe MetasploitModule do
  subject(:mod) { described_class.new }

  describe '#check' do
    it 'returns Vulnerable for affected versions' do
      # 測試邏輯
    end
  end
end

模組發布

完成開發後,可以將模組提交至 Metasploit 官方專案:

  1. 程式碼規範檢查:使用 msftidy.rb 檢查程式碼格式
  2. 文件撰寫:建立模組文件說明使用方式
  3. Fork 專案:在 GitHub 上 Fork metasploit-framework
  4. 建立分支:為新模組建立獨立分支
  5. 提交 PR:撰寫詳細的 Pull Request 說明
1
2
3
4
5
6
7
# 執行程式碼規範檢查
./tools/dev/msftidy.rb modules/auxiliary/scanner/http/my_scanner.rb

# 確認無錯誤後提交
git add modules/auxiliary/scanner/http/my_scanner.rb
git commit -m "Add HTTP scanner module for XYZ vulnerability"
git push origin my-new-module

參考資料

comments powered by Disqus
Built with Hugo
Theme Stack designed by Jimmy