CEH Hacking methodology and goals

  1. Reconnaissance

    • Goal: Gather information on the target before any direct engagement.
    • Techniques: Passive and active information gathering, including open-source intelligence (OSINT), scanning, and footprinting.
  2. Scanning

    • Goal: Identify live hosts, open ports, services, and potential vulnerabilities.
    • Techniques: Network scanning, vulnerability scanning, and enumeration.
  3. System Hacking

  • Goal: Gain unauthorized access to systems and escalate privileges.
    • Key Actions:
      • Password Cracking: Using tools to guess or decrypt passwords.
      • Vulnerability Exploitation: Leveraging identified vulnerabilities to gain access.
      • Social Engineering: Trick users into revealing sensitive information or taking unsafe actions.
  1. Privilege Escalation

    • Goal:Objective: Gain higher-level access once initial access is achieved.
    • Types:
      • Horizontal Escalation: Accessing accounts with different permissions but at the same level.
      • Vertical Escalation: Moving to higher privilege levels, such as administrative access.
  2. Maintaining Access (Persistence)

    • Goal: Ensure continued access to the compromised system.
    • Techniques:
      • Installing malware for command and control (C2) communication.
      • Creating backdoor accounts.
      • Using persistence mechanisms to reconnect if access is interrupted.
  3. Hiding Files and Data Exfiltration

    • Goal: Objective: Extract data covertly and avoid detection.
    • Methods:
      • Steganography: Hiding sensitive data within image or video files.
      • Covert Channels: Using encrypted communication protocols like HTTPS for data transfer.
  4. Covering Tracks

    • Objective: Conceal evidence of hacking activities.
    • Techniques:
      • Clearing logs and deleting entries to remove traces of unauthorized access.
      • Ensuring minimal detection by system monitors or administrators.

Windows authentication

  • *Windows SAM (Security Accounts Manager) stores passwords in hashed form using either:

    • Security Accounts Manager (SAM) Database
      • A file stored at %SystemRoot%/system32/config/SAM. On registry you can find it on HKEY_LOCAL_MACHINE\SAM.
      • Locked by Windows kernel to prevent copying/moving
      • Usually stolen through bootable CD/USBs.
    • Active Directory Database
      • Stored on a domain controller in a database
      • Located in either %SystemRoot%\NTDS\Ntds.dit or %SystemRoot%\System32\Ntds.dit
  • NTLM (NT LAN Manager): NTLM is an authentication protocol used in Windows environments, though it is gradually being phased out in favor of the more secure Kerberos protocol.

    • Less Secure: NTLM is considered less secure than Kerberos due to vulnerabilities in its hash-based challenge-response mechanism.
    • Usage: Primarily used in older or non-domain Windows environments, or as a fallback when Kerberos is not available.
    • NTLM Authentication Process:
      1. Client Request: The user initiates login by providing a username and password.
      2. Challenge-Response:
        • The client sends a login request to the server with the username.
        • The server responds with a randomly generated challenge.
      3. Hash Calculation: The client computes a cryptographic hash of the user’s password, combines it with the challenge, and hashes this result (known as the NT hash).
      4. Hash Exchange: The client sends the hashed response back to the server.
      5. Server Verification: The server compares the received hash with its stored hash for the user in the Security Accounts Manager (SAM) or Active Directory.
      6. Authentication:
        • If the hashes match, the user is authenticated, and access is granted.
        • If the hashes do not match, authentication fails.
  • Kerberos Authentication Protocol: Kerberos is a secure network authentication protocol commonly used in enterprise networks to authenticate client-server applications. Kerberos is widely implemented in systems like Windows Active Directory and Unix-based environments to enable secure, scalable authentication.

    • Key Components:
      • Key Distribution Center (KDC): The central authority that issues and manages tickets, comprised of:
        • Authentication Server (AS): Handles initial authentication requests.
        • Ticket Granting Server (TGS): Issues service tickets for access to specific resources.
      • *Ticket Granting Ticket (TGT): A temporary credential allowing the user to request service tickets without needing to re-authenticate.
      • Service Ticket: A ticket used to authenticate the user to a specific network service.
    • Kerberos Authentication Steps:
      1. Client Authentication Request: The user initiates a request to access a network service.
      2. TGT Request (AS-REQ): The client sends an authentication request to the AS, asking for a TGT.
      3. TGT Issuance (AS-REP): The AS verifies the user’s credentials and issues a TGT, encrypted with a session key and a KDC secret key.
      4. Service Ticket Request (TGS-REQ): Using the TGT, the client requests a service ticket for the target service from the TGS.
      5. Service Ticket Issuance (TGS-REP): The TGS verifies the TGT and issues a service ticket for the target service, encrypted with the service’s secret key.
      6. Service Authentication: The client presents the service ticket to the target service.
      7. Service Verification: The service decrypts the service ticket, verifies its authenticity, and grants access if valid.
    • Benefits of Kerberos:
      • Mutual Authentication: Both client and server validate each other’s identity.
      • Single Sign-On (SSO): Users authenticate once and gain access to multiple network services without re-authenticating.
      • Ticket-Based Authentication: Reduces the need to transmit passwords over the network by using encrypted tickets.

Password attacks - Basic concepts

Password cracking methods are used to recover plaintext passwords from stored, hashed, or encrypted values. This overview includes common techniques, online vs. offline approaches, and popular tools.

  • Types:

    • Non-technical techniques
      • Shoulder surfing: Observing someone’s screen or keyboard to capture a password.
      • Social engineering: Manipulating individuals to reveal sensitive information.
      • Dumpster diving: Recovering disposed items with potential password clues (e.g., sticky notes, discarded documents).
    • Online Techniques: Online techniques are active attacks on live services requiring network connectivity.
      1. Active online techniques:
      • Dictionary attack: Uses a list of common passwords or words.
      • Brute force attack: Systematically tries all possible character combinations.
      • Rule-based attack: Applies custom rules to guess passwords.
      • Guessing default passwords: Tries default passwords often associated with specific software or services.
      • Malware & spyware: Retrieves passwords directly from a compromised system.
      1. Specialized Active Online Techniques:
      • Pass the hash: Uses intercepted NTLM hash values without decrypting.
      • LLMNR poisoning: Exploits link-local multicast name resolution (LLMNR) vulnerabilities to capture hashes.
      • Internal monologue: Extracts NTLM hashes without network communication, effective when already on a target system.
      1. Passive Online Techniques:
      • Packet aniffing: Captures and analyzes packets for passwords.
      • Man-in-the-Middle (MITM): Intercepts communication to retrieve credentials.
      • Replay attack: Re-sends captured valid data packets.
    • Offline Techniques: Offline attacks involve working on captured password hashes without connecting to the original service.
      • Dictionary and brute force: Similar to online but performed on captured password files.
      • Rainbow Tables: Uses precomputed hash tables to expedite cracking by directly comparing hash values.
  • Tools

    • Online Active: Hydra, Medusa (for brute force attacks over the network)
    • Online Passive: Wireshark, Ettercap (for packet sniffing and MITM attacks)
    • Offline:
      • Kali Hydra:
        1
        2
        3
        4
        5
        6
        7
        8
        9
        hydra -L usernamelist.txt -P passlist.txt -e ns -F -t 1 -w 10 <host-ip-address> http-form-post "/login.php:username=^USER^&password=^PASS^&Login=Login:Login failed" -v
        # -e ns: e additional options
        # n: try null (for empty password)
        # s: try also same password as a user name
        # -t 1: number of tasks (based on threads), default is 16 (don't use many, you'll raise attention)
        # -w 10: waiting time of 10 ms
        # <host-ip-address>: usually people go to the target using proxies and examine results in proxies.
        # http-form-post: Posts data to server as the HTML does
        # Login failed: text to search in result page to determine whether the login has failed
      • Hashcat: High-performance tool for cracking large sets of hashes.
        1
        2
        3
        4
        5
        6
        7
        8
        # cracking Linux OS password
        ./hashcat64.bin -a 3 -m 1800 ?u?l?l?l?d?d?d
        # -m 1800: Hash mode sha512crypt $6$, SHA512 (Unix)
        # -a 3 ?u?l?l?l?d?d?d: Mask attack
        # Brute-force on user specified character sets
        # ?u?l?l?l?d?d?d= uppercase + lowercase + lowercase + lowercase + number + number + number
        # Do certain assumptions or it might take until the next big bang to crack the password.
        # e.g. usually passwords start with capital letter and continues with lowercase letters
      • John the Ripper: Classic password-cracking tool.
        1
        2
        3
        4
        5
        6
        7
           # Copy pass file
        umask 077
        unshadow /etc/passwd /etc/shadow > mypasswd
        # Crack it
        john mypasswd
        # Passwords are saved in $JOHN/john.pot
        john --show mypasswd
      • Ophcrack: Utilizes rainbow tables.
      • L0phtCrack: Windows password auditing with LANMAN and NTLM hashes.
  • Recovery:

  • Reset:

Password extraction and cracking

  • Steps:

    1. Password Hashes and Obfuscation:
      • Linux: Passwords are stored in the etc/shadow file (requires sudo permissions).
      • Windows: Stored in locations such as SAM, Kerberos, and NTLM systems.
    2. Tools for Hash Extraction:
    • Windows:
      • PWDump: Extracts password hashes.
      • MimiKatz: Comprehensive tool, requires deep familiarity.
      • Responder: Intercepts authentication requests on a network for password hashes.
    • Linux: Direct access to shadow file for hash extraction, using tools like cat (with proper permissions).
    1. Hash Cracking Tools:
    • John the Ripper: Popular for dictionary-based attacks.
    • Hashcat: Known for speed and flexibility; supports various hash types and attack modes.
    • Ophcrack: Utilizes rainbow tables for NTLM hashes.
    • Loft Crack: Recently free; useful for different password cracking scenarios.
    1. Attacks Without Cracking:
    • Pass-the-Hash: Authentication bypass using hashed passwords directly for systems that accept them as passwords.
  • Techniques:

    1. Linux:
      • Access the shadow file using sudo cat /etc/shadow.
      • Use a hash-cracking tool (e.g., John the Ripper) with a suitable wordlist.
    2. Windows:
      • Run PWDump for hash extraction.
      • Store extracted hashes securely for offline cracking on a dedicated machine.
      • Use Hashcat with specific hash and attack modes for efficient cracking.
    3. Network Interception:
      • Responder can capture NTLMv2 hashes on the network by acting as a man-in-the-middle.
      • Useful when the direct machine compromise isn’t feasible.
    4. Exfiltration Tactics:
      • Use tools like curl to send captured hashes to an external server, e.g., with Python’s HTTP server.
  • Countermeasures:

    1. Strong Passwords:
      • Ensure length and complexity (avoid dictionary words).
      • Use salting for additional security against hash-based attacks.
    2. Other Security Tips:
      • Avoid weak passwords that could be quickly cracked or guessed.
      • Regularly monitor for unauthorized hardware (e.g., keyloggers).

Password attacks cracking enhancement techniques

  • Key techniques:

    1. Combinator attack:
      • Combines two or more dictionaries to create a more extensive wordlist.
      • Useful for expanding the scope of password guesses.
      • Recommended to use scripts to remove duplicates to avoid redundant checks.
    2. Prince attack:
      • Stands for Probability Infinite Chained Elements.
      • Uses a single dictionary but generates new word combinations based on known criteria (e.g., password length).
    • Ideal when some password characteristics (like minimum or maximum length) are known.
    1. Toggle case:
      • Generates case variations for each word in the dictionary (e.g., “Password,” “pAssword”).
      • Ensures all possible uppercase/lowercase combinations are tried.
      • Helpful when case sensitivity is uncertain.
    2. Markov chain:
      • A statistical analysis-based approach that uses common patterns observed in previously cracked passwords.
      • Builds likely passwords based on frequent character sequences, improving the dictionary’s relevance.
      • Operates as a hybrid of dictionary and brute-force techniques.
  • Tips for efficient cracking:

    • Hardware Optimization: Use multi-GPU setups, water-cooled systems, and multi-threading to increase speed.
    • Avoid Redundancy: Use scripting to combine dictionaries without duplicates.
    • Utilize Known Criteria: Apply filters based on password policies (e.g., length limits) to narrow guesses.

Buffer overflows

If we have a program which has a buffer overflow issue, it means it doesn’t handle the extra data correctly which then can cause it to crash OR we can use the vulnerability as: if we know the data sent overflows in a register for example ESB and I know when it flows (how many bytes) then we can control what is sent which can be a reverse shell code (by msfvenom tool for example).

  • Concepts:

    1. Buffer overflow basics:
    • Definition: Occurs when data overflows its allocated memory space into adjacent areas.
    • Goal: Achieve code execution by controlling where data overflows.
    1. Heap vs. stack overflows:
    • Heap overflow: Involves dynamically allocated memory (e.g., using malloc in C).
    • Stack overflow: Involves static memory allocation, where stack pointers (e.g., EIP, ESP) can be controlled to direct execution.
    1. Registers and pointers:
    • Key registers:
      • EIP (Instruction Pointer): Points to the next instruction.
      • ESP (Stack Pointer) and EBP (Base Pointer): Track data in the stack.
    • Exploit requires control over these pointers to redirect execution.
  • Tools:

    • Debugger (Immunity Debugger): Used to analyze memory and monitor pointers.
    • Mona.py: Immunity Debugger plugin to assist in buffer overflow analysis.
  • Steps for exploiting a buffer overflow:

    1. Fuzzing: Sending incremental data to identify crash points.
      • Wrote a fuzz.py script in Python to send progressively larger payloads, detecting the crash point.
      • Discovered that the server crashes with payloads of 2400 bytes.
    2. Finding the EIP offset:
      • Generated a unique pattern (via pattern_create) to locate where the EIP register is overwritten.
      • Analyzed in Immunity Debugger to determine the exact byte offset for EIP overwrite.
    3. Controlling execution flow
      • Located the Jump ESP command within the loaded modules (using Mona modules) to find the correct memory address for redirection.
      • Used Metasploit’s msfvenom to generate shellcode, ensuring to match the payload size with the required buffer length.
    4. Executing the exploit
      • Created a payload consisting of:
        • NOP Sled: provides padding before shellcode.
        • Shellcode: reverse shell payload created with msfvenom.
        • EIP Redirect: points to Jump ESP to run shellcode in ESP.
      • Confirmed code execution by opening a reverse shell.
  • Defense Mechanisms:

    1. Memory protections
    • ASLR (Address Space Layout Randomization): Randomizes memory addresses, preventing predictable address targeting.
    • DEP (Data Execution Prevention): Blocks code execution in specific memory regions.
    1. Secure coding practices
    • Implement input validation and boundary checks to handle unexpected data sizes gracefully.
    • Use static and dynamic code analysis in the development lifecycle to catch buffer overflows early.

Privilege Escalation

Privilege escalation refers to the process of gaining higher levels of access or privileges on a system or network than what was initially granted to a user or process. It’s a common goal for attackers who have gained initial access to a system with limited privileges.

  • Types:

    1. Horizontal Privilege Escalation:
      • In horizontal privilege escalation, the attacker gains access to another account or process with the same level of privileges as their current account.
      • This typically involves impersonating another user or process that has similar access rights.
    2. Vertical Privilege Escalation:
      • In vertical privilege escalation, the attacker gains access to higher levels of privileges than their current account or process.
      • This can involve escalating privileges from a low-privileged user account to an administrator or root-level account.
  • Techniques for privilege escalation:

    1. OS or software vulnerabilities: unpatched systems may have known exploits available on ExploitDB. Tools like searchsploit (Kali Linux) can find local exploit databases.
    2. Misconfigurations: misconfigured permissions or shared folders can open doors for escalation.Common errors include granting excessive permissions and failing to secure shares.
    3. DLL Hijacking: placing a malicious DLL in a folder where the system expects a legitimate DLL. Tools like ProcMon help identify missing DLLs that can be hijacked.
    4. Unattended installation files: unattend.xml or unattended.xml files often contain sensitive information. These files may store admin credentials, located in folders like C:\Windows\System32\sysprep.
    5. Unquoted service paths: if a service path has spaces and lacks quotes, attackers can place a malicious executable in the expected path. e.g. service path like C:\Program Files\App Name may execute App.exe if found in C:\Program.
    6. Scheduled tasks: Manipulating scheduled tasks (e.g., PowerShell scripts in Windows or cron jobs in Linux) can allow execution of malicious code.
    7. SUID/GUID permissios: in Linux, files with SUID/GUID set can run with elevated privileges. Tools like GTFOBins list exploitable binaries with SUID bits.
    8. Sudo privileges: misconfigured sudo permissions may allow escalation.sudo -l command shows accessible binaries that could be exploited to gain root access.
  • Tools for privilege escalation:

    1. LinPEAS/WinPEAS (PEAS Suite): automates privilege escalation checks and suggests exploitation paths on Linux (LinPEAS) and Windows (WinPEAS).
    2. Windows Exploit Suggester: analyzes Windows configurations to identify potential privilege escalation points.
    3. Linux Privilege Checker: Runs privilege checks on Linux systems, identifying areas to escalate privileges.
  • Defense against privilege escalation:

    • System patching: apply patches for known vulnerabilities.
    • Principle of least privilege: grant only necessary permissions to users.
    • System hardening: follow hardening guides and secure configurations.
    • Multifactor authentication: adds an extra layer of protection against unauthorized access.
    • Secure application development: use SAST and DAST to test application security.

Maintaining Access

  1. Backdoors: Attackers may install backdoor programs or modify existing system components to create secret entry points into the compromised system. These backdoors can provide remote access to the system, allowing attackers to return and regain control even if their initial access is discovered and removed.
  2. Rootkits: Rootkits are malicious software designed to hide the presence of other malicious programs or activities on a system. They operate at a deep level within the operating system, making them difficult to detect and remove. Rootkits can be used to maintain access by ensuring that the attacker’s tools and processes remain hidden from system administrators and security software. There are several types:
    • Kernel-Level Rootkits: Operate at the OS kernel level, replacing or modifying core OS functions.
    • User-Level Rootkits: Exploit vulnerabilities in user-space applications to gain elevated privileges.
    • Bootkits: Infect the boot process (e.g., MBR), controlling the system from startup.
    • Hardware/Firmware Rootkits: Infect system hardware or firmware, controlling the system at a fundamental level.
    • Memory Rootkits: Reside entirely in system memory, injecting malicious code into processes.
  3. Scheduled tasks and cron jobs: Attackers may create scheduled tasks or cron jobs to execute their malicious code at predefined intervals. By scheduling tasks to run periodically, attackers can maintain access to the compromised system without needing to maintain a constant presence.
  4. Persistence mechanisms: Attackers can leverage various persistence mechanisms built into operating systems to ensure their malicious code runs automatically every time the system boots or a user logs in. Examples include modifying startup scripts, registry keys, or system services.

Steganography

  • Steganography is the practice of hiding data within other files, known as the cover medium. This allows data to be concealed within images, audio, or video files without altering their appearance. It’s commonly used to exfiltrate sensitive information, like personal data or intellectual property, without detection (e.g. Snowden reportedly used steganography to exfiltrate data).

    • Methods:
      • Slack Space: Hiding data in unused portions of a file, making it less noticeable.
    • Tools
      • StegSnow: Embeds hidden text into file slack space with optional compression and password protection.
      • StegHide: A versatile tool used for embedding various data types in images and other file types.
  • Steganalysis: process of detecting and analyzing hidden data within files, often used in threat hunting and cybersecurity defense.

    • Detection methods:
      • Visual Analysis: Observing abnormalities in files, such as odd pixelation in images or inaudible frequencies in audio files.
      • File Metadata: Examining metadata fields for hidden information.
      • Strings Command: Searching for readable text in files to identify embedded data.
  • Tools:

    • Zsteg: Analyzes files for hidden data, providing insight into embedded messages and metadata.

Covering Tracks

In cybersecurity, attackers, red team members, or penetration testers may attempt to hide their activity on a system. Covering tracks is essential for maintaining access and avoiding detection.

  • Techniques:

    • Disabling security and logging systems:
      • Disabling auditing: Stops logging specific actions, like login events, by modifying audit policies.
      • Disabling IDS/IPS: Although risky (it may trigger alerts), it can prevent detection if attackers remain unnoticed.
      • Disabling tripwires: Prevents alerts when accessing sensitive files.
    • Manipulating logs:
      • Clearing logs:
        • Windows: PowerShell Clear-EventLog, wevtutil for event logs, and Event Viewer GUI.
        • Linux: history -c, echo > .bash_history, and shred to overwrite log files.
      • Selective deletion: Removing specific log entries instead of clearing all logs avoids suspicion, as completely empty logs can trigger alerts.
    • Modifying timestamps:
      • FSUtil in Windows: Disables last access timestamps, hiding file access history.
      • Linux touch Command: Updates file timestamps to avoid showing recent access.
    • Disabling restore Points and Virtual Memory
      • System restore points: Disabling them in Windows removes evidence of activity saved in system snapshots.
      • Page and hibernation files: Virtual memory files can contain remnants of attacker activity; deleting or overwriting these files removes evidence.
  • Defensive Measures against track-covering:

    1. Centralized logging (Syslog): Transmit logs to a remote Syslog server to maintain copies outside of the compromised system.
    2. Event viewer subscriptions: In Windows, create a central server to subscribe to and collect logs from other machines, preserving evidence even if logs on a local machine are tampered with.
    3. SIEM (Security Information and Event Management):
      • Log normalization: SIEM tools normalize logs, making them easier to analyze and review.
      • Alerting and dashboarding: Provides a centralized view of logs and alerts, highlighting missing or disabled logs.
      • Syslog integration: Often integrates with Syslog to ensure all logs are captured and normalized.

AD enumeration

Active Directory (AD) enumeration is essential in understanding and exploiting a Windows domain. By gathering information on users, computers, groups, and domain structure, security professionals can identify potential lateral movement paths within the network. Its scripts can be run directly from a local attack machine (e.g., a Kali box) using PowerShell’s Invoke-Expression to pull the script via HTTP.

  • Techniques and tools
    1. PowerView: CLI tool, part of the PowerSploit toolkit and is widely used in AD enumeration for gathering detailed information on domain structure and assets. It provides PowerShell commands to enumerate AD objects and relationships.
      • Key PowerView Commands
        • Get-NetDomain: Lists details about the current domain, including the domain controller, domain mode, and domain owner roles.
        • Get-NetForest: Provides information about the forest, including root domain, global catalog, and site details.
        • Invoke-ShareFinder: Searches for shared drives within the domain to identify accessible resources.
    2. BloodHound: visual tool that maps and analyzes AD relationships, making it easier to spot vulnerabilities and privilege escalation paths. It uses SharpHound (available as an .exe or .ps1 script) to collect AD data and generates JSON files that BloodHound converts into an interactive graph.
      • Key BloodHound Features
        • Graphical Representation: displays relationships between domain objects, like user and group memberships, making it easy to identify paths for privilege escalation.
        • Query Options: built-in queries allow users to find key information such as:
          • Domain admins and computers with unsupported OS.
          • Users with DC Sync rights and Kerberostable accounts.
          • Computers where domain users are local admins.
      • Setup:
      1. SharpHound Data Collection: Run SharpHound (sharphound.exe or sharphound.ps1) on a compromised AD-connected system, which outputs JSON data in a zip file.
      2. Neo4j Database: BloodHound relies on a Neo4j database for storing and querying data. Start Neo4j, log in, and connect BloodHound to the database.
      3. Upload JSON: Import the SharpHound JSON files to BloodHound to create a visual map of AD relationships.

Mimikatz

Powerful post-exploitation tool primarily used on Windows systems to extract and manipulate credentials, aiding in privilege escalation and persistence.

  • Key features and attacks:

    1. Abusing Data Protection API (DPAPI):
    • DPAPI: a Windows feature that securely stores sensitive data (e.g., Wi-Fi, browser passwords).
    • Mimikatz commands:
      • sekurlsa::dpapi: extracts master keys from DPAPI, allowing access to encrypted data.
      • lsa::backupkeys /system: exports DPAPI master keys, enabling decryption of sensitive information on other systems.
    1. Malicious replication (DC Sync Attack):
    • DC Sync Attack: Mimikatz impersonates a domain controller to request password data for domain users.
    • Mimikatz command* lsa::dcsync /domain:<domain> /user:<username>: Requests password hash data for a specified user, enabling pass-the-hash attacks or offline password cracking.
    1. Skeleton key attack:
    • Skeleton key attack: creates a “skeleton key” that allows any AD user to log in with a universal password (e.g. “Mimikatz”).
    • Mimikatz command: misc::skeleton: activates the skeleton key, enabling login across accounts without modifying individual user passwords.
    1. Golden ticket attack:
    • Purpose: Grants broad access to Active Directory (AD) by creating a forged Kerberos Ticket Granting Ticket (TGT) for a specific user with administrative privileges.
    • Requirements: krbtgt Hash (to create the TGT), domain SID and FQDN.
    • Mimikatz command: kerberos::golden /domain:<FQDN> /sid:<SID> /rc4:<krbtgt hash> /user:<username>: It creates a ticket.kirbi file, enabling persistent, stealthy access across AD.
    1. Silver ticket attack
    • Purpose: provides access to a single service within AD, rather than full domain access.
    • Requirements:
      • Service Account Hash: used to create a service-specific TGT.
      • Note: common service accounts often have weak passwords, making them easier to compromise.
    • Use Case: limited access, targeting a specific service without full domain privileges.
  • Pass-the-ticket

    • Purpose: uses a previously obtained Kerberos TGT to access resources without needing a password.
    • Mimikatz command: kerberos::ptt: loads the TGT (ticket.kirbi) into the session, enabling access to AD resources as the specified user.
  • Hash-based attacks: Pass-the-Hash (PTH):

    • Purpose: Aalows the use of an NTLM hash to authenticate without knowing the plaintext password.
    • Requirements: NTLM hash of the target account.
    • Mimikatz Command: sekurlsa::pth /user:<username> /domain:<domain> /ntlm:<hash>, it opens a new session with privileges of the specified user.

Pivoting

  • Pivoting: it involves using a compromised system, often referred to as a “pivot point” or “pivot host,” to gain access to other systems or networks that are not directly accessible from the attacker’s initial entry point. The pivot host serves as a bridge or intermediary for the attacker to launch further attacks against additional targets within the network.

    • Common techniques:
      • Port Forwarding: setting up port forwarding or port redirection on the pivot host to relay traffic between the attacker and other systems within the network.
      • Proxying: configuring the pivot host to act as a proxy server, allowing the attacker to route traffic through it to reach other systems or services within the network.
      • Tunneling: establishing encrypted tunnels, such as SSH tunnels or VPN connections, from the pivot host to other systems or networks, providing a secure communication channel for the attacker.
  • Relaying: it involves intercepting authentication requests between two systems and relaying them to gain unauthorized access to resources or escalate privileges. Relaying attacks exploit weaknesses in authentication protocols and trust relationships between systems to gain unauthorized access or escalate privileges within a network.

    • Common techniques:
    • NTLM Relay: intercepting NTLM (NT LAN Manager) authentication requests between a client and a server and relaying them to gain access to resources on behalf of the client. This is commonly used in attacks such as SMB relay attacks.
    • Kerberos Relay: intercepting Kerberos authentication tickets and relaying them to gain access to systems or services that trust the compromised authentication.
    • HTTP/HTTPS Relay: intercepting HTTP or HTTPS traffic and relaying it to exploit vulnerabilities or gain access to sensitive information.
  • proxychains: tool used to force any TCP connection to follow through proxy servers or chains of proxies. It’s typically used for anonymizing the origin of network traffic and bypassing network restrictions.

    • How to: ProxyChains intercepts network connections initiated by applications and redirects them through a series of proxy servers defined in its configuration file. Each proxy server in the chain relays the connection to the next until it reaches the final destination.
    • Configuration: ProxyChains is configured through its configuration file (/etc/proxychains.conf on Linux). Users specify proxy servers, their ports, and optionally, the proxy type (e.g., SOCKS4, SOCKS5, HTTP). Additionally, users can specify rules for handling DNS requests.
    • Usage: once configured, users simply prepend proxychains to their command-line applications to force them to use the configured proxy servers. For example: proxychains curl example.com.

Vulnerability assessment concepts and resources

Vulnerability research helps identify vulnerabilities which could compromise the system.

  • Scanning types:

    • Active scanning: interacting directly with the target network to discover vulnerabilities.
    • Passive scanning: discovering vulnerabilities without a direct interaction with the target network.
  • Solution types:

    • Product-based solutions: installed in the internal network.
    • Service-based solutions: offered by third parties.
    • Tree-based assessment: different strategies are selected for each machine.
    • Inference-based assessment:
      1. Find the protocols to scan.
      2. Scan and find the found protocols and their services.
      3. Select the vulnerabilities and begins with executing relevant tests.

Vulnerability scoring systems

Vulnerabilities that are identified are stored into databases, scored according to their severity and risk:

  • CVSS - Common Vulnerability Scoring System: (how to rate them)

    • A free and open industry standard for assessing the severity of computer system security vulnerabilities.
    • Helps to assess and prioritize vulnerability management processes.
    • Assigns severity scores to vulnerabilities.
    • Score calculator depends on metrics that include ease and impact of exploit.
  • CVE - Common Vulnerabilities and Exposures: (identification for common vulnerabilities)

    • Mitre.org: eg. CVE-2020-0023.
    • List of common identifiers for publicly known cybersecurity vulnerabilities.
  • NVD - National Vulnerability Database: (database with CVEs)

    • U.S. government repository of standards based vulnerability management data.
    • nvd.nist.gov.
    • Includes databases of security checklist references, security-related software flaws, misconfigurations, product names, and impact metrics.

Vulnerability management life-Cycle

Evaluation and control of the risks and vulnerabilities in the system.

  • Phases:
    • Pre-assessment phase: creating baseline: Identifying critical assets and prioritizing them.
    • Assessment phase: vulnerability assessment: identifying known vulnerabilities.
    • Post-assessment phase:
      • Risk assessment: assessing the vulnerability and risk levels for the identified assets.
      • Remediation: mitigating and reducing the severity of the identified vulnerabilities.
      • Verification: ensuring that all phases have been successfully completed.
      • Monitoring: identifying new threats and vulnerabilities.
1
2
3
4
5
# check connetions on ports
netstat -antup
# check open services
sudo nmap -T5 -n -Pn -p- 8.8.8.8
# some port may be overflowed, close them uf not needed

Vulnerability classification

  • Misconfiguration.
  • Default installations.
  • Buffer overflows.
  • Unpatched servers.
  • Design flaws.
  • Operating system flaws.
  • Application flaws.
  • Open services.
  • Default passwords.

Vulnerability assessment types

  • Active assessment: through network scanners.
  • Passive assessment: by sniffing the traffic.
  • External assessment: vulnerabilities & threats that are accessible outside of the organization.
  • Internal assessment: vulnerabilities & threats that are present internally.
  • Host-Based assessment: vulnerabilities & threats on a specific server by examining the configuration.
  • Network assessment: identifies potential attacks on the network.
  • Application assessment: examines the configuration of the web infrastructure.
  • Wireless network assessment: vulnerabilities & threats in the organization’s wireless network.

Vulnerability assessment models and tools

Also known as vulnerability scanners

  • Scanning solutions perform vulnerability penetration tests in three steps:

    1. locate the live hosts in the network.
    2. enumerate open ports and services.
    3. test the found services for known vulnerabilities by analyzing responses.
  • Tool types:

    • Host-based vulnerability assessment tools.
    • Depth assessment tools.
    • Application-layer vulnerability assessment tools.
    • Scope assessment tools.
    • Active/Passive tools.
    • Location/Data examined tools.
  • Tools

    • Openvas software framework of several services and tools offering vulnerability scanning and vulnerability management.
    • Nmap: you can scan multiple servers for multiple ports for multiple vulnerabilities: -A: enables OS detection, version detection, script scanning and traceroute.
    • Nessus: proprietary port and vulnerability scanner, which includes: misconfigurations, default passwords and DoS vulnerabilities. It can be used to perform compliance auditing, like internal and external PCI DSS audit scans.
    • Burp Suite: proxy tool to scan web vulnerabilities. It allows manual testers to intercept all requests and responses between the browser and the target application. It visualices, edit or drops individual messages to manipulate the server-side or client-side components of the application.
    • Nikto is an open source Nikto web server vulnerability scanner. Looks for outdated software, dangerous files/CGI etc.

Vulnerability assessment reports

  • Written after an assessment is performed.
  • Classified into security vulnerability report and security vulnerability summary.
  • Details of what has been done and what has been discovered during the assessment
  • Created to help organizations resolve security issues if they exist
  • Typically contain information about the scan, target, and results.

Actively engage a system and query it for information, in order to discover vulnerabilities and then exploit them. Information collected include routing tables, users and groups, machine names, network resources.

NetBIOS and SMB enumeration

NetBIOS (Network Basic Input/Output System) is a unique name of a Windows machine. Easily exploitable, often used as one of the first scans.

  • Uses:
    • Allows computers to communicate with others at the same time, or share files and printers
    • Network file sharing protocol uses SMB (service message block) protocol (it was targeted by WannaCry ransomware who traversed the network and injected hosts).
  • Information retrieved:
    • System name.
    • Username.
    • Domain.
    • Printers.
    • Available shares.

Tools:

  • Nmap: sudo nmap -A -T5 -n -Pn -p 445 8.8.8.8
  • nbtstat: proprietary Windows diagnostic tool for NetBIOS over TCP/IP.
    • nbtstat -a <IP or hostname>: shows NetBIOS names
    • net view <IP or hostname>: prints available shares such as printers.
  • smb-nat: NetBIOS Auditing Tool.
    • nat -o <output file> -u <user-list> -p <password-list> <ip/range> allows you to brute force different usernames and passwords for administrative shares.
  • WinFingerPrint: Windows enumeration tool. Scan machines in LAN and returns shares, disk information, services, users (SID), groups.

SNMP enumeration

SNMP stands for Simple Network Management Protocol. It was developed for routers and switches (1988), and later was extended for linux/windows machines, printers, sensors, power supplies and more…

  • Uses:

    • monitoring networking equipment
    • remotely modifying settings and configs on the equipment
  • Community strings types: (SNMPv3 encrypts the community strings)

    • Read community string: read-only: you can collect information such as System name, system uptime, network settings, CPU usage level, etc (estimated time of completion).
    • Read/write community string: read-write (private) to edit configurations
  • Components:

    • Agents are embedded into network devices:
      • Agents send their information to manager using port 162.
      • Data messages are called traps.
    • Manager is installed on a computer:
      • Needs two passwords to access and configure the agents:
        • read community string
        • read/write community string
  • Object identifier (OID): any device that can be monitored has an OID (e.g. 1.3.6.1.2.1.2.2.1.8).

  • Management Information Base (MIB): text-file that translates numerical OIDs to word-based OIDs (e.g. SYNOLOGY-SYSTEM-MIB::temperature.0).

    • You can collect information CPU usage level, disk usage level, network settings using vendor-specific OIDs.
  • Versions:

    • Version 1, 2: (insecure!) No encryption, only “community string” and no encryption
    • Version 3: Username + password and encryption
  • Tools:

    • onesixtyone: onesixtyone 8.8.8.8
    • snmpcheck: snmpcheck 8.8.8.8 -c public.
    • nmap: sudo nmap -sU -p 161 --script snmp-win32-users.nse 8.8.8.8
    • snmpwalk: enumerates ports in SNMP agent and finds out UDP port sending traffic to manager (snmpwalk -c public -v1 <agent IP address>).
    • **snmp-check: you can find out the version using snmp-check <IP address> -v <version 1 or 2c>. Gives much more information like routing tables, storage information, users etc.
    • snmp-get:
      • Retrieve specific OID information from target using -o (e.g. snmpget -v 1 -c public system.sysName.0).
      • SNMP community string for SNMP v1/v2c (e.g. sysName.0 for system name).

LDAP enumeration

LDAP stands for Lightweight Directory Access Protocol, used by on-premises Active Directory (Microsoft). It can be utilized in a brute force or social engineering attacks.

  • Structure: hierarchical (e.g. domain > child-domains > organizational units > users / groups / computers).

  • Retrieved information: usernames, addresses, servers, and other sensitive information.

  • Tools:

  • Countermeasures:

    • Use over encrypted and secure protocols e.g. by e.g.
      • LDAP over SSL/TLS
        • Also known as LDAPS
        • SSL/TLS is negotiated before LDAP protocol begins.
      • LDAP over StartTLS
        • STARTTLS is a way to take an existing insecure connection and upgrade it to a secure connection using TLS.
        • Communication is only encrypted after the connection is established.
    • Use NTLM or Basic authentication
    • Select a username different from your email address

NTP enumeration

NTP (Network Time Protocol) is to synchronize computer clocks (e.g. machines in same domain in Active Directory must have same GMT clocks). It uses UDP 123. Usually companies have authority of time-source on their on-premises, it synchronizes to internet and everything else synchronizes to it. It is important for routers / switches to have logs with right timestamps.

  • Target accuracy:

    • 10 ms over the public internet
    • 200 ms or better on a local area network
  • Information retrieved:

    • List of hosts connected to NTP server.
    • Clients IP addresses, system names and operating systems..
    • Internal IP addresses can be acquired if the NTP server is on the DMZ.
  • Tools:

    • ntpdate: synchronize date, use debug flag to gte more info (ntpdate -d 8.8.8.8).
    • ntptrace: traces NTP servers back to the primary source, you may indicate a single remote host with the flag (nttrace -r 8.8.8.8).
    • ntpq: monitors NTP daemon ntpd operations and determines performance. It is interative a provides lots of information.
    • ntpdc: monitors operation of the NTP daemon, ntpd.
    • Other tools include: NTP Time Server Monitor, NTP server Scanner, Nmap • Wireshark, AtomSync, NTPQuery, PresenTense NTP Auditor, PresenTense Time Server, PresenTense Time Client, Lan Time Analyser…

NFS enumeration

Network File System, similar to mounting a hard drive for centralizing data (UDP port 2049).

  • Tools:
    • nmap: explore the port (sudo nmap -A -T5 -n -Pn -p 2049 8.8.8.8).
    • rpcinfo: rpcinfo 8.8.8-8
    • showmount: showmount -e 8.8.8.8 (/ * means you can mount the root directory).
    • rpcscan: python tool (rpcscan --nfs 8.8.8.8).
1
2
3
4
5
6
7
# example mpunt nfs drive
mkdir /tmp/hacked
sudo mount.nfs metasploitable-drive:/ /tmp/hacked
# we get a symlink here
cd /tmp/hacked
ls
# and so on...

SMTP enumeration

SMTP = Simple Mail Transfer Protocol (port: 25) is the protocol used for sending/receiving e-mails. It is used by clients talk to SMTP server, and SMTP servers to talk to other servers.

  • Components:

    • SMTPS is SMTP over TLS (port: 587), like HTTPS is HTTP over TLS.
    • SMTP can also run with STARTTLS (port: 467):
      • Compared to running over TLS, it encrypts communication AFTER the communication is established.
      • STARTTLS is also known as opportunistic TLS as it would fall back to unencrypted communication if server does not support it.
  • MX records (Mail eXchange records are used to direct emails sent to domain) on DNS may help find SMTP servers.

  • Information retreived: it allows to validate e-mail addresses to ensure they exist:

    • One another: Go to provider → try creating account with that e-mail.
    • Large collection of e-mails can be sold or used for phishing.
    • Many e-mail senders (e.g. AWS Simple Email Service) blocks you if you send e-mails that will not reach the targets (idea: create fake accounts in cloud providers → ask to increase soft limits → enumerate per accounts).
  • Commands:

    • VRFY: validates e-mail address that actually exists
    • EXPN: tells the actual delivery address of aliases and mailing lists
    • RCPT TO: Defines recipients of the messages
    • Some admins may turn off VRFY and EXPN, but not RCPT TO (or no one can receive e-mail)
  • Tools:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
npm -T5 -n -Pn -p 25 bee-box metasploitable
# connect
ncat -v 192.168.255.266 25
# do something, it will kick you out due to inactivity
helo bob
# start playing around
ls
# look for some names
vrfy bee-box
# use automation againts target
stmpy-user-enum -m VRFY -U /usr/share/seclists/usernames/names/names.txt -t 192.168.255.266 25

# load metasploit to find scanners on aux
search smtp aux
# choose one form the list, e.g. number 8
use 8
# look for options with it
options
# verify target is rhosts
set rhosts 192.168.255.266
run
# see the banner wait for it

# meanwhile, we can get busy with nmap where it is enum-users (plural)
sudo nmap -n -Pn -T5 -p 25 --script smtp-enum-users.nse 192.168.255.266 25

Network scanning types

Process of obtaining additional information about hosts, ports and services in network for more detailed reconnaissance in order to identify vulnerabilities in communication channels and then create an attack plan.

  • Host discovery: to list IP addresses. Discover live hosts and operating systems.
  • Port scanning: to list open ports and services. Discover open ports, and verify which services (version) run on them.
  • Vulnerability scanning: to discover the presence of known vulnerabilities. Use previosuly obtained information to narrow down againts a database.

Network scanning tools

Tools for techniques are used to identify hosts, ports, and services in the target network

  • namp is the most popular:
    • Includes:
      • Ncat: reads and writes data across networks from the command
      • ndiff: compares scan results
      • nping: generates packets and analyzes responses
    • Phases:
      1. Script pre-scanning: Runs NSE scripts that are run once per execution for each targets, e.g. dhcp-discover.
      2. Target enumeration: Resolves DNS names, CIDR network notations etc. to list of IPv4 or IPv6 addresses
      3. Host discovery (ping scanning): Checking if a host (or which hosts are) is alive before deeper investigation
      4. Reverse-DNS resolution: Provides IP numbers for hosts that are alive
      5. Port scanning: Probes are sent and remote port states are classified as open, closed, filtered
      6. Version detection: Determines what server software is running on remote system
      7. OS detection: Determines OS that’s running on the port
      8. Traceroute: Usually involves another round of reverse-DNS resolution for intermediate hosts.
      9. Script scanning: Runs most of the scripts rather than pre-scan and post-scan phases.
      10. Output: Prints results using different options e.g. XML
      11. Script post-scanning: Runs scripts that process results and deliver final reports and statistics
  • Metasploit
  • Hping port scanner
  • Colasoft Packet Builder
  • NetScanTools Pro
  • Packeth
  • Fing

Host discovery

  • Types:
    • Internal: inside the network.
    • External: starting from the exterior.

Techniches:

  • Scanning ICMP or ping scan (echo).
  • ARP for TCP.
  • UDP (usually forgotten).

Tools:

  • ip: retrieve network information: ip -br -c a
  • ping: test if device is alive: ping 8.8.8.8.
  • nmap: discovery: nmap -sn 8.8.8.8
    • usually “echo” (-PE) is blocked on firewall, others like ICMP, ARP, UDP are not (-PE, -PR, -PU).
  • traceroute: gets you the external network information: traceroute 8.8.8.8
  • angry ip scanner built upon ping.

Corporations use a perimeter or DMZ to pretect themselves against these technicques.

Port and service scanning

List of TCP and UDP port numbers

Port Protocol Default service
21 TCP FTP (File Transfer Protocol)
22 TCP SSH (Secure Shell)
23 TCP Telnet
25 TCP SMTP (Simple Mail Transfer Protocol)
53 TCP/UDP DNS (Domain Name Server)
80 TCP TTP (Hypertext Transfer Protocol). HTTP/3 will run over UDP
123 TCP NTP (Network Time Protocol)
443 TCP/UDP TTPS
500 TCP/UDP IKE/IPSec (Internet Key Exchange / IPSec)
631 TCP/UDP IPP (Internet Printing Protocol)
3389 TCP/UDP RDP (Remote Desktop Protocol)
9100 TCP/UDP AppSocket/JetDirect (HP JetDirect, Printer PDL Data Stream)

Example on map:

1
2
3
4
# port, state and service
nmap -T5 -n -Pn -p- 8.8.8.8 -o nmapscan.txt
# port, state, service and version from the service
nmap -T5 -n -Pn -p- -sV 8.8.8.8 -o nmapVersionScan.txt

TCP connect scan

“Full open scan” used for detecting open ports upon the completion of the three-way handshake. Works by establishing a full connection and then dropping it by sending a RST packet.

  • Tools:

    • Wireshark: capture traffic from other tools and “paints it”.

    • Nmap: nmap -sT <ip-or-host>.

      1
      2
      # port, state and service
      nmap -sT 8.8.8.8
  • Three-way handshake: Establishes a TCP connection with synchorinzation and acknowledge.

    • Sender: SYN → Receiver: SYN ACK → Sender: ACK.
    • ACK is then set in every packet sent after the handshake.
    • Sender: FIN → Receiver: ACK FIN → Sender: ACK.
sequenceDiagram
    Attacker->>Target: (1) SYN
    Target->>Attacker: (2) SYN/ACK
    Attacker->>Target: (3) ACK

Stealth scan

Also known as TCP SYN ping, SYN stealth, stealth scan, half-open scan or TCP ping scan, is the default and most popular scan. It works by resetting the TCP connection before the three-way handshake is completed, which in turn makes the connection half open.

  • Pros and cons:

    • Pro: Stealthy because it never completes TCP connections (can bypass firewalls and logging).
    • Con: Require root privileges.
    • Con: Rulesets block many SYN scan attempts.
  • Types:

    • Open: only uses the first part of the conversation.
sequenceDiagram
    Attacker->>Target: (1) SYN + Port
    Target->>Attacker: (2) SYN/ACK
    Attacker->>Target: (3) RST
  • Closed: reset after finish.
sequenceDiagram
    Attacker->>Target: (1) SYN + Port
    Target->>Attacker: (2) RST
  • Filtered: Retry if not recovered.
sequenceDiagram
    Attacker->>Target: (1) SYN + Port
    Attacker->>Target: (2) SYN + Port retry
  • Tools
    • Nmap: -PS (host discovery, default behaviour) or -sS (port scan): sudo nmap -sS -PS 8.8.8.8.
    • Hping: hping3 -8 <port-list e.g. 50-60> –S <ip-address> –V

Inverse TCP XMAS and Maimon scans

Works by sending a TCP frame with FIN, URG, and PUSH flags set.

  • Christmas tree packet (-sX): packet with every option set, like bulbs on a Christmas tree.
  • TCP Maimon Scan (-sM): This technique is exactly the same as NULL, FIN, and Xmas scan, except that the probe is FIN/ACK.
Probe Response Assigned State
No response received (even after retransmissions) open or filtered
TCP RST packet closed
ICMP unreachable error (type 3, code 1, 2, 3, 9, 10, or 13) filtered
  • Closed: reset after finish.
graph LR;
    A[Attacker];
    B[Target];
    A -- 1: URG, FIN, PUSH --> B;
    B -- 2: RST --> A;
  • Open or filtered: no response.
graph LR;
    A[Attacker];
    B[Target];
    A -- 1: URG, FIN, PUSH --> B;
  • Filtered: Retry if not recovered.
graph LR;
    A[Attacker];
    B[Target];
    A -- 1: URG, FIN, PUSH --> B;
    B -- 2: ICMP unreachable error --> A;
  • Tools
    • Hping: hping3 -F -P -U <ip-address> -p <port-number>
      • -F for FIN, -P for PUSH), -U for URG
      • 0% packet loss is closed, 100% packet loss is open.
    • Nmap: -sX‘.
      1
      2
      sudo nmap --scanflags URGACKPSHRSTFIN 8.8.8.8
      # flags go together: URG ACK PSH RST FIN

ACK scan

Also known as ACK flag scanning, ACK flag probe scanning or TCP ACK scan. Used to detect existence of firewalls, cannot detect open ports.
Works by sending TCP packet with ACK flag set, where ACK (acknowledgment) is used to acknowledge the successful receipt of a packet

  • Unfiltered:
graph LR;
    A[Attacker];
    B[Target];
    A -- 1: ACK --> B;
    B -- 2: RST --> A;
  • Filtered, unresponsive:
graph LR;
    A[Attacker];
    B[Target];
    A -- 1: ACK --> B;
  • Filtered: errored.
graph LR;
    A[Attacker];
    B[Target];
    A -- 1: SYN + port --> B;
    B -- 2: ICMP unreachable error --> A;
  • Pros and cons:
    • Pro: Difficult to log, avoids IDS detection, helps detecting existence of stateful firewalls.
    • Con: Relies on BSD network code bug in older versions and is slow.
  • Tools
    • Nmap: -PA (host discovery) or -sA (port scan): sudo nmap -sA -PA 8.8.8.8.
    • Hping: hping3 –A <ip-address> –p <port>

IDLE IPID scan

  • Allows for blind port scanning (without sending any packet with own IP).
  • Utilizes IP address of a zombie machine through spoofed packets.
  • Flow:
    1. Probe the zombie’s IP ID and record it.
      • IP ID:
        • Every IP packet on the Internet has a fragment identification number
        • Incremented by OSes for each packet sent
      • Zombie should be:
        • idle as no other traffic would increase the traffic
        • assigning IP ID packets incrementally on global level instead of per-host basis.
    2. Forge a SYN packet from the zombie and send it to the desired port on the target.
    3. Probe the zombie’s IP ID again.
      • If it’s increased compared to one in step 1, port is open (it has received)
  • *Pros and cons:
    • Pro: Ultimate stealth scan as attackers IP would not be revealed, can be used for framing as IDS will report zombie as the attacker.
    • Con: It takes far longer, and many ISPs implement egress filtering to prevent the packet spoofing.
  • Tools:
    • Nmap: nmap -Pn -sI <zombie-ip/domain> <target-ip/domain>
      • -sI: Idle scan
      • -Pn: no ping to be stealthy

UDP scan

UDP is the connectionless stream protocol, so no handshakes. UDP is used by e.g. DNS (port 53), SNMP (port 161/162), and DHCP (port 67/68). It is also known as UDP ping, UDP/ICMP error scan, UDP port scan or UDP ICMP_PORT_UNREACHABLE scan. It exploits UDP behavior where the receiver sends an ICMP packet with error code when a port is unreachable. No response is interpreted as “open” or “filtered” behind firewall.

  • Pros and cons:
    • Pro: Avoids TCP IDS, and scans non-TCP ports that are quite common.
    • Cons:
      • Provides port information only, ICMP is rate-limited by Linux kernel however not by Windows.
      • Require root privileges and slower.
  • Tools
    • Hping: hping3 -2 <ip-address> –p <port>
    • Nmap: -PU (host discovery) or -sU (port scan)

SCTP INIT and COOKIE ECHO scans

SCTP: most reliable protocol for transport layer.

sequenceDiagram
    Client->>Server: INT
    Server->>Client: INT + ACK
    Client->>Server: Cookie+ Echo
    Server->>Client: Cookie + ACK
  • Tools
    • Nmap: -sY (SCTP init and cookie echo scan): sudo nmap -sY -n -Pn 8.8.8.8 --packet-trace

Scan optimizations

  • Increase focus: start from wider net, then reduce targets.
  • Remove unnecessary scanner.
  • Templates: -T4 is faster than -T3.
    • -T0: paranoid.
    • -T1: sneaky.
    • -T2: polite.
    • -T3: normal.
    • -T4: aggresive.
    • -T5: insane.
1
2
3
4
5
# -n: skip name resolution
# -Pn: skip ping, since Windows blocks it
# -F top 100 ports
# --disable-arp-ping end IP traffic
sudo nmap -n -Pn -F -T2 --disable-arp-ping scanme.nmap.org

Target OS identification techniques

  • Time To Live (ttl) may give up the OS:

    1
    2
    3
    ping -c 4 8.8.8.8
    # Windows ttl is 128
    # Linux ttl is 64
  • nmap may try to guess the OS:

    1
    2
    3
    4
    # educated guess
    sudo nmap -O 8.8.8.8
    # SMB 1.0 is out of support, but on packages you may find things like "WIN" and "10PRO"
    sudo nmap --script smb-os-discovery.nse 8.8.8.8 --package-trace
  • IPv6: it is usually not firewalled

    1
    2
    # -6 goes for IPv6
    sudo nmap -O -6 8.8.8.8
  • Countermeassures:

    • Dissinformation.
    • Turn off unused protocols.
    • Turn off banners (“Hi, I am this service running on this version”).
    • Don’t show file extensions.

IDS and firewall evasion

Avoiding meassures like Intrussion Detection System and firewalls.

  • Packet fragmentation: splitting up TCP header to several smaller (fragmented) packets on send, and the server reasembles them once all packets are received.

    • Usually ignored by IDSes as processing them requires a lot of computer resources
    • Any IP datagram can be fragmented: including UDP, TCP, ICMP, etc.
    • Tools:
      • Nmap: -f flag e.g. nmap -f <ip-or-host>
        • splits the packets into 8 bytes or less after the IP header
        • Alternatively can use --mtu option allows to set bytes e.g. --mtu 16
      • fragroute
        • Usage: fragroute <domain-name>
          *Intercept, modify, and rewrite egress traffic to use fragments
  • IP address decoy: all packets originate from the scanning machine, but some have spoofed source addresses.

    • It elps to confuse port scan detection, but it does not offer any information beyond a regular scan.
    • Tools:
      • Nmap:
        • nmap -D decoy1,decoy2,ME,decoy3... <target>: Manual list with custom positioned ME
        • nmap -D RND:10 <target> to randomize 10 decoy IP addresses
  • IP address spoofing: used to make packet appear to come from someone else, done by changing address information in IP packet header field.

    • Replies go back to the spoofed address not to the attacker.
    • Mostly used for DoS attacks.
    • If it does not get a response, the firewalll did not block it (no drop, no rejection), so there may be something here.
    • Tools:
      • hping: hping3 <target> -a <spoofed-ip>
      • Nmap: nmap <target> -S <spoofed-ip> -e -Pn
  • Source routing: specifying which path the malformed packet will take to get to the target host, but it is usually blocked.

    • Used to skip routes (routers/gateways) where firewalls exist, disregarding what route tables say.
    • Done by modifying IP address field in IP Options field
    • Using Nmap:
      • Loose routing:
        • Specifying packet to be loose source routed through given IP way points
        • E.g. --ip-options "L 192.168.0.7 192.168.30.9"
      • Strict routing:
        • You will have to specify every single hop along the path.
        • E.g. --ip-options "S 192.168.0.7 192.168.0.9 .. 192.168.30.9"
  • Source port modification: Firewalls filter port (ingress and egress), e.g. usually port 53 is open so DNS can work, so piggyback your request over there.

    • Tools:
      • Nmap: nmap -g 53 <target>
  • SSRF (Server Side Request Forgeries): a server makes the request on our behalf. BurpSuite, Zap

  • Randomize host: hides by avoiding sequences, using randimizers.

    • Tools:
      • Mmap: nmap --randomize-hosts <target>
  • Proxies: use middleman (nmap --proxies).

  • Anonymiser: avoid blacklists Proxyswitcher, FoxyProxy, VPNs, TOR browse, or OS level like Tails or Whonix.

Footprinting concepts

  • Gathering information about a target system. Also known as fingerprinting or reconnaissance.
  • End goal is to find a way to break into the system.
  • Often offered as separate service bought by companies to check against leaks and to see what data is there.

Classification

  • Passive footprinting: no direct contact with target, relying on information that is publicly available.
  • Active footprinting: direct contact with target including, possible for target to be aware (e.g. through tasks that may be logged or recorded)

How to:

  1. Start with passive footprinting by gathering all publicly available data. Organiuze data obtained.
  2. Use active footprinting: starting probing for ports, networks, possible vulnerabilities etc. It¡’s good to learn more about stuff (employees) of a company: through them you can learn a lot more and gain a lot more access (e.g. contact them through social media and start a conversation, join a conference that you see the person is attending on LinkedIn and meet him).

Information types

  • System information:
    • Web server operating systems.
    • Server locations.
    • Active Directory or LDAP.
    • Users.
    • Passwords.
  • Network information:
    • Domains, subdomains.
    • IP addresses.
    • Whois and DNS records.
    • VPN firewalls using ike-scan.
  • Organization information:
    • Employee information.
    • Organization’s background
    • Phone numbers.
    • Locations.

Footprinting objectives

  • Learn security posture: analyze security, find loopholes, create an attack plan.
  • Identify focus area: narrow down the range of IP addresses.
  • Find vulnerabilities: identify weaknesses in the target’s security.
  • Map the network: graphical representation of target’s network a guide during the attack.

Footprinting reports

  • Main items:
    • Details about the performed tests.
    • Used techniques.
    • Test results.
  • Other information:
    • List of vulnerabilities and how they can be fixed.
    • List sources of information e.g. DNS, social medial, social engineering.
    • List what information you gathered from each source.
  • Should be kept highly confidential.

Google dorks

Use advanced search features of Google in order to do granular searching.

  • Look for vulnerabilties on software (eg. msexchange).

    • Look for tools on a site * site:reddit.com osint tools.
    • Look for user and password files inurl:/wp-content/uploads/ ext:txt "username" | "user name" | "uname" | "user" | "userid" | "user id" AND "password" | "pass word" | "pwd" | "pw".
  • Look for id= on a URL, and test SQL injections.

  • Operators:

    • site:: changes scope to an specific website.
    • inurl:: look for webpages which contain an sepecific character string.
    • intitle:: look for webpages which contain an sepecific character string on its title.
    • filetype:: look for files from a certaion type, like a PDF.
    • cache: find a storaged copy of a website.
    • related:: fin websites related to the site cite on the command.
    • link:: find websites linking to certain websites.
    • info:: find information on a certain website.

Shodan and Censys

  • Shodan: search devices connected to the Internet. It has lot of filters.

    Filter Description
    city Name of the city
    country 1 character country code
    http.title Title of the website
    net Network range ot IP on a CIDR
    org Name of the organization unit that owns the IP
    port Port number of the running service
    product Name of the software powering the device
    screenshot label Label thar describes the content
    state US state
  • Censys: search devices connected to the Internet.

    • Hosts and certificates database.
    • Explore tab: map the domain.

Sub-Domain enumeration

  • Domain: presence of the Internet.

  • Subdomains: smaller area on a domain. Enumeration widens the scope for finding targets.

  • Techniques:

    • Check all NS Records for zone transfers.
    • Enumerate general DNS records for a given domain.
    • Perform common SRV Record Enumeration: service records contain the hostname, port and priority of servers for a given service.
    • Brute force subdomain and host A and AAAA records discovery with given top domain and wordlist.
    • DNS PTR lookup given a IP range CIDR range
      • Querying dns for PTR record of each IP in subnet
  • How to:

    • Google dork: site:my-target-webiste.org.

    • Go to website, look for “page source code”, look for matches with Ctrl + F for my-target-webiste.org, look at cookies.

    • Netcraft: on Resoures - Tools - Search DNS, use “site contains…”.

    • Sublist3r: python tool

    • ExifTool: extract metadata.

      Short Form Long Form Description
      -d –domain Domain name to enumerate subdomains of
      -b –bruteforce Enable the subbrute bruteforce module
      -p –ports Scan the found subdomains against specific tcp ports
      -v –verbose Enable the verbose mode and display results in realtime
      -t –threads Number of threads to use for subbrute bruteforce
      -e –engines Specify a comma-separated list of search engines
      -o –output Save the results to text file
      -h –help show the help message and exit

Social networking recon

People don’t think on what they put out on social media.

  • Use advance search parameters.

  • Look for usernames, they are usually similar to email addresses.

  • How to:

    • Social searcher: website.
    • Sherlock: python tool to find usernames across Social Network.
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      sherlock [-h] [--version] [--verbose] [--folderoutput FOLDEROUTPUT]
      [--output OUTPUT] [--tor] [--unique-tor] [--csv] [--xlsx]
      [--site SITE_NAME] [--proxy PROXY_URL] [--json JSON_FILE]
      [--timeout TIMEOUT] [--print-all] [--print-found] [--no-color]
      [--browse] [--local] [--nsfw]
      USERNAMES [USERNAMES ...]

      positional arguments:
      USERNAMES One or more usernames to check with social networks.
      Check similar usernames using {?} (replace to '_', '-', '.').

Job board recon

  • Easy way to gte contact information, org charts.
  • Learn stack they use from job posts ads.

Deep-dark web recon

  • Dark web are unindexed websites that exist in the Dark net. Browse them with censorship-resistant and privacy-respecting specialized browser like:
  • Freenet
  • TOR.

Email tracking

Monitoring the email delivery and inspecting the e-mail headers may reveal:

  • IP address of the recipient.
  • Geolocation of the recipient.
  • Delivery information.
  • Visited links.
  • Browser and OS information.
  • Reading time.

There are email tracking tools, used marketers with JavaScript, tracking links, link shorteners or tracking pixels.

Headers

  • Email header analysis:

    • Sender’s name
    • IP/Email address of the sender
    • Mail server
    • Mail server authentication system
    • Send and delivery stamps
    • Unique number of the message
  • Authentication protocol headers: allows you to detect forged sender addresses. They should include information about their pass status

    • SPF: Sender Policy Framework (e.g. 'PASS' with IP 209.85.220.69 or 'NEUTRAL' ...), ased on e-mail servers who publish records and says “here’s the IP addresses we’ll send e-mails”:
      • Verifies if the domain of the e-mail owned by the sending server.
      • If not passed, many e-mail providers just block it.
    • DKIM: DomainKeys Identified Mail (e.g. 'PASS' with domain accounts.google.com): allows the receiver to verify that an email claimed to have come from a specific domain was authorized by the owner of that domain using a digital signature on the domain.
    • DMARC: Domain-based Message Authentication, Reporting and Conformance (e.g. PASS or FAIL): Combination of two protocols SPF + DKIM, which build on them and adds more policy
  • Verifying email legitimacy

    • Double check FROM.
    • Check the spelling in domain name so it’s coming from the domain of the company. If it’s random e-mail check if it’s from one of the biggest domain providers or if something legit.
    • Check IP of the domain.
    • It can be someones computer (home router IP) or a private server.
    • Major mail service providers checks to determine if domain of the e-mail is tied to the source IP of the e-mail (e.g. have a record, you may tie a public WiFi like coffee shop IP to domain and send the e-mails from there).
  • e-mail policies:

    • Different e-mail service provider have different policies regarding to their SMTP.
    • Once hacker recognizes e-mail servers then then he/she can create accounts there, send e-mails back and further to figure out what the rules are.
    • Each have own ruling list.

WHOIS and DNS recon

WHOIS

Query and response protocol (port 43), pulic records, completely legal. It is used for retrieving registry information about assigned Internet resources.

  • Access:
    • Use different websites such as whois.net
    • Use CLI: whois cloudarchitecture.io
  • Models:
    • Thick WHOIS: information from all registrars for the specified set of data.
    • Thin WHOIS: limited information about the specified set of data.
  • Results:
    • Domain details.
    • Domain owner details (contact information). Can be hidden by a WHOIS guard (proxy between the owner of the domain and who’s accessing), but emails are usually still redirected to the owner (phishing target).
    • Domain server (site owner might have account in the server, and you can test passwords there).
    • Net range.
    • Domain expiration: If auto-renewal fails, can be transfered or bought.
    • Creation and last update dates.
  • Regional internet registries: WHOIS databases are maintained by the Regional Internet Registries (RIRs). Every ISP, hosting company etc. must be member of one of the registries to get IP addresses:
    • ARIN: American Registry for Internet Numbers
    • AFRINIC: African Network Information Center
    • APNIC: Asia Pacific Network Information Center
    • RIPE: Réseaux IP Européens Network Coordination Centre
    • LACNIC: Latin American and Caribbean Network Information Center

DNS recon

Domain Name Service, which collects information about DNS zone data, retrieveing key hosts in the network.

  • How to: host -t a cloudarchitecture.com (-t: type of domain record, a trrieve A type of domain records).
  • Reverse DNS lookup: use one of IP addresses that’s listed as an A,m to retrieve multiple IP addresses tied to same domain:
    1
    2
    host 13.33.17.159`
    159.17.33.13.in-addr.arpa domain name pointer server-13-33-17-159.arn53.r.cloudfront.net.
  • Zone transfers (ZANG), dig command (dig axfr @nsztml.digi.ninja zonetransfer.me), nslookup. Resources can be found in digi.ninja.

Social Engineering Recon

  • Eavesdropping: hear conversations, people like to yell on their phones, or read emails load.
  • Shoulder-surfing: look over their shoulder as you pass by.
  • Dumpster diving: documents, notes with passwords. Documents may need to be shredded.
  • Impersonating: as default, people will belive you if you pose as service desk.

Other footprinting tools

Collect and visualizes information (e.g. IP location, routing, business, address, phone number, social security number, source of an email and a file, DNS, domain).

  • Maltego, proprietary software for OSINT, provides graphical link for investigative tasks.
  • OSINT framework: provides graphical link for investigative tasks.
  • Recon-ng (The Recon-ng Framework): open source CLI tools for open source web-based reconnaissance.
  • Recon-dog:
    • Open-source CLI tool self-claimed as Reconnaissance Swiss Army Knife.
    • Can extracts targets from STDIN (piped input) and act upon them.
    • Passive reconnaissance tool extracting all information with APIs without any contact with target.
  • FOCA: Fingerprinting Organizations with Collected Archives: open-source tool to find metadata and hidden information in the documents:
    1. Finds documents (e.g. PDF, SVG) through search engines or manual upload.
    2. Analyze them and identify which documents are created by same team, using which servers/clients.
  • Dmitry (DeepMagic Information Gathering Tool): CLI tool to analyze a website e.g. dmitry https://cloudarchitecture.io:
    1. Performs WHOIS lookup on IP and domain.
    2. Retrieves Netcraft information.
    3. Search for subdomains/email addresses.
    4. Performs TCP scanning.
    5. Grabs banner for each port.

Footprinting and recon countermeasures

  • Enforcing security policies.
  • Educating employees about security threats: raising awareness reduces risks dramatically.
  • Encrypting sensitive information: use proper encryption everywhere. Many companies uses VPN/proxy with encryption for outside communication, but service communicate with each other without any encryption.
  • Access control: authentication, use of MFA.
  • Disabling protocols that are not required.
  • Proper service configuration:
    • Double check all services that application depends.
    • Do not disable/enable configuration without knowing consequences.
  • Scrutinize information released to the public domain: e.g. you post on social media which routers the company has just bought, it allows hacker to know default router configurations and get image of OS in the router and conduct tests in a VM.
  • Limit site caching: inform search engines what they’re supposed to index through (e.g. robots.txt):
    • User-agent: * Disallow: / prevents indexing any page (Disallow: /) for any crawler (User-agent: *).
  • Use Whois Guard.
  • Restricting access to social media: extra risk as you click on many links and giving away companies IP address,
0%