Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
rapid7
GitHub Repository: rapid7/metasploit-framework
Path: blob/master/lib/metasploit/framework/key_collection.rb
27899 views
1
module Metasploit::Framework
2
class KeyCollection < Metasploit::Framework::CredentialCollection
3
attr_accessor :key_data
4
attr_accessor :key_path
5
attr_accessor :private_key
6
attr_accessor :error_list
7
attr_accessor :ssh_keyfile_b64
8
9
# Override CredentialCollection#has_privates?
10
def has_privates?
11
@key_data.present?
12
end
13
14
def realm
15
nil
16
end
17
18
def valid?
19
@error_list = []
20
@key_data = Set.new
21
22
if @private_key.present?
23
results = validate_private_key(@private_key)
24
elsif @key_path.present?
25
results = validate_key_path(@key_path)
26
else
27
@error_list << 'No key path or key provided'
28
raise RuntimeError, 'No key path or key provided'
29
end
30
31
if results[:key_data].present?
32
@key_data.merge(results[:key_data])
33
else
34
@error_list.concat(results[:error_list]) if results[:error_list].present?
35
end
36
37
@key_data.present?
38
end
39
40
def validate_private_key(private_key)
41
key_data = Set.new
42
error_list = []
43
begin
44
if Net::SSH::KeyFactory.load_data_private_key(private_key, @password, false).present?
45
key_data << private_key
46
end
47
rescue StandardError => e
48
error_list << "Error validating private key: #{e}"
49
end
50
{key_data: key_data, error_list: error_list}
51
end
52
53
def validate_key_path(key_path)
54
key_data = Set.new
55
error_list = []
56
57
if File.file?(key_path)
58
key_files = [key_path]
59
elsif File.directory?(key_path)
60
key_files = Dir.entries(key_path).reject { |f| f =~ /^\x2e|\x2epub$/ }.map { |f| File.join(key_path, f) }
61
else
62
return {key_data: nil, error: "#{key_path} Invalid key path"}
63
end
64
65
key_files.each do |f|
66
begin
67
if read_key(f).present?
68
key_data << File.read(f)
69
end
70
rescue StandardError => e
71
error_list << "#{f}: #{e}"
72
end
73
end
74
{key_data: key_data, error_list: error_list}
75
end
76
77
78
def each
79
prepended_creds.each { |c| yield c }
80
81
if @user_file.present?
82
File.open(@user_file, 'rb') do |user_fd|
83
user_fd.each_line do |user_from_file|
84
user_from_file.chomp!
85
each_key do |key_data|
86
yield Metasploit::Framework::Credential.new(public: user_from_file, private: key_data, realm: realm, private_type: :ssh_key)
87
end
88
end
89
end
90
end
91
92
if @username.present?
93
each_key do |key_data|
94
yield Metasploit::Framework::Credential.new(public: @username, private: key_data, realm: realm, private_type: :ssh_key)
95
end
96
end
97
end
98
99
def each_key
100
@key_data.each do |data|
101
yield data
102
end
103
end
104
105
def read_key(file_path)
106
@cache ||= {}
107
@cache[file_path] ||= Net::SSH::KeyFactory.load_private_key(file_path, password, false)
108
@cache[file_path]
109
end
110
end
111
end
112
113