Unit 5 - Notes

INT244

Unit 5: Session Hijacking, Web Servers and Applications, SQL Injection

1. Understanding Session Hijacking

Session hijacking refers to the exploitation of a valid computer session—sometimes called a session key—to gain unauthorized access to information or services in a computer system. It generally applies to web developers and system administrators who must ensure that the communication between the client and server remains secure.

The Concept of a Session

  • Definition: A session is a semi-permanent interactive information interchange between two or more communicating devices.
  • The Problem: HTTP is a stateless protocol. The server does not remember the client between requests.
  • The Solution: To maintain state (e.g., keeping a user logged in), servers issue a Session ID (token) after successful authentication.
  • The Vulnerability: If an attacker obtains this Session ID, they can impersonate the victim without needing the username or password.

Methods of Session Hijacking

  1. Session Sniffing: Using packet sniffers (like Wireshark) to intercept unencrypted traffic (HTTP) and capture the Session ID.
  2. Session Prediction: If the algorithm generating Session IDs is weak (e.g., sequential numbers or based on time), an attacker can guess the next valid ID.
  3. Session Fixation: The attacker sets a valid Session ID for the victim (e.g., via a malicious link) and waits for the victim to log in using that ID.
  4. Cross-Site Scripting (XSS): Injecting malicious JavaScript into a viewed page to steal the document.cookie containing the session token.
  5. Man-in-the-Middle (MitM): Intercepting and altering communication between two parties who believe they are communicating directly.

2. Network Session Hijacking

Network-level hijacking involves TCP/IP protocol manipulation. It is distinct from application-level hijacking (which targets HTTP cookies) as it occurs at the transport layer.

TCP/IP Hijacking (IP Spoofing)

This attack targets the TCP 3-Way Handshake.

  1. Normal Flow:
    • Client sends SYN (Sequence X).
    • Server responds with SYN-ACK (Acknowledgment X+1, Sequence Y).
    • Client responds with ACK (Acknowledgment Y+1).
  2. The Attack:
    • The attacker desynchronizes the victim’s connection.
    • The attacker injects packets that look like they came from the victim by spoofing the victim's IP address.
    • Critical Success Factor: The attacker must correctly predict the TCP Sequence Numbers. If the sequence number is incorrect, the server drops the packet.

Types of Network Hijacking

  • Blind Hijacking: The attacker can inject commands (send data) but cannot see the response (because the server sends the response to the actual victim's IP).
  • Active Hijacking: The attacker silences the victim (e.g., via DoS) and takes over the connection completely, acting as the client.

3. Exploring Defensive Strategies

Defense against session hijacking requires a "defense-in-depth" approach, securing both the network layer and the application layer.

Application Level Defenses

  • Regenerate Session IDs: Always issue a new Session ID immediately after a successful login to prevent Session Fixation.
  • Secure Cookies:
    • Secure flag: Ensures cookies are only sent over HTTPS.
    • HttpOnly flag: Prevents JavaScript (XSS) from accessing the cookie.
  • Entropy: Use long, random strings for Session IDs (128-bit minimum recommended) to prevent prediction.
  • Timeouts: Implement absolute timeouts (force re-login after X hours) and idle timeouts (logout after X minutes of inactivity).

Network Level Defenses

  • Encryption (SSL/TLS): The most effective defense. It encrypts the entire communication tunnel, making sniffed Session IDs useless.
  • IPSec: Secures IP communications by authenticating and encrypting each IP packet of a communication session.
  • User Behavior Analysis: Detect anomalies, such as a session suddenly changing IP addresses or User-Agent strings.

4. Exploring the Client-Server Relationship

Understanding the architecture of the web is prerequisite to securing it.

The Client (The Requester)

  • Typically a web browser (Chrome, Firefox) or a mobile application.
  • Responsibilities:
    • Initiating requests (GET, POST, etc.).
    • Rendering HTML/CSS.
    • Executing client-side scripts (JavaScript).
    • Storing local data (Cookies, LocalStorage).

The Server (The Responder)

  • A computer running software like Apache, Nginx, or IIS.
  • Responsibilities:
    • Listening for requests on specific ports (80 for HTTP, 443 for HTTPS).
    • Processing logic (PHP, Python, Java).
    • Interacting with the database.
    • Returning resources (HTML, JSON, Images).

The Interaction

  1. Request: Client sends HTTP packet (Header + Body).
  2. Processing: Server interprets the request.
  3. Response: Server returns HTTP status code (e.g., 200 OK, 404 Not Found) and data.

5. Vulnerabilities of Web Servers and Applications

Web servers and applications present a large attack surface because they must remain open to the public internet.

Web Server Vulnerabilities (Infrastructure)

  • Misconfiguration: Default accounts left enabled, unnecessary services running, directory listing enabled.
  • Patch Management: Running outdated versions of server software (e.g., old IIS or Apache) with known CVEs.
  • Permission Issues: Running the web server service as root or administrator, giving an attacker full system control if compromised.

Web Application Vulnerabilities (Code)

Based on the OWASP Top 10, common flaws include:

  • Injection Flaws: SQLi, Command Injection.
  • Broken Authentication: Weak password policies, session mismanagement.
  • Sensitive Data Exposure: Transmitting data in clear text.
  • Security Misconfiguration: Verbose error messages revealing stack traces.
  • Buffer Overflows: Input data exceeding the reserved memory space, potentially executing malicious code (more common in C/C++ based CGI).

6. Testing Web Applications

Security testing involves assessing the application to find vulnerabilities before attackers do.

Testing Methodologies

  1. Black Box Testing: The tester has no prior knowledge of the system (simulates an external hacker).
  2. White Box Testing: The tester has full access to source code and architecture (simulates a malicious insider or allows for deep code review).
  3. Gray Box Testing: Partial knowledge (e.g., tester has a user account but no source code).

Testing Phases

  1. Reconnaissance: Gathering info (IPs, server versions, technologies used).
  2. Scanning/Enumeration: Using automated tools to find open ports and known vulnerabilities.
  3. Exploitation: Attempting to leverage found vulnerabilities.
  4. Reporting: Documenting findings and remediation steps.

Common Tools

  • Burp Suite: A proxy tool for intercepting and modifying HTTP traffic.
  • OWASP ZAP: Open-source scanner.
  • Nikto: Web server scanner for dangerous files/CGIs.

7. Introducing SQL Injection (SQLi)

SQL Injection is a code injection technique where an attacker executes malicious SQL statements that control a web application's database server.

  • Root Cause: The application trusts user input without sufficient validation or sanitization.
  • Mechanism: The attacker "escapes" the intended data context and enters the command context.
  • Impact:
    • Bypass authentication.
    • Access, modify, or delete data within the database.
    • Execute administrative operations on the database.

8. Databases and Their Vulnerabilities

The database is the "Crown Jewels" of most organizations, holding customer data, financial records, and credentials.

Common Database Systems

  • Relational: MySQL, PostgreSQL, Microsoft SQL Server, Oracle.
  • NoSQL: MongoDB, Redis (susceptible to NoSQL injection).

Vulnerabilities

  • Weak Authentication: Blank or default sa (system admin) passwords.
  • Excessive Privileges: The application connects to the DB using a user with DROP TABLE or GRANT rights.
  • Stored Procedures: Dangerous built-in procedures (e.g., xp_cmdshell in MS SQL) that allow OS-level command execution.
  • Unpatched Software: Known buffer overflows in the database software itself.

9. Anatomy of a SQL Injection Attack

Consider a vulnerable login query in PHP:

PHP
$sql = "SELECT * FROM users WHERE username = '" . $user . "' AND password = '" . $pass . "'";

The Tautology Attack (Authentication Bypass)

The attacker enters ' OR '1'='1 into the username field.

  • Resulting Query:
    SQL
        SELECT * FROM users WHERE username = '' OR '1'='1' AND password = '...'
        
  • Logic: Since 1=1 is always TRUE, the database returns the first record in the table (usually the Administrator), logging the attacker in without a password.

The Union-Based Attack

Using the UNION operator to combine the results of the original query with the results of a specific injected query.

  • Input: ' UNION SELECT username, password FROM users --
  • Goal: To dump the contents of other tables into the visible application interface.

The Comment Attack

Using SQL comment characters to ignore the remainder of the original query (often the password check).

  • MySQL: # or -- (dash-dash-space)
  • MS SQL: --
  • Example Input: admin' --
  • Resulting Query: SELECT * FROM users WHERE username = 'admin' --' AND password = '...' (The password check is commented out).

10. Altering Data with a SQL Injection Attack

SQLi is not limited to reading data (SELECT). If the database user has write permissions, the attacker can alter the state of the system.

Modification Attacks

  1. UPDATE: Changing data.
    • Input: '; UPDATE users SET password='hacked' WHERE username='admin'; --
    • Result: Resets the admin password.
  2. INSERT: Adding data.
    • Input: '; INSERT INTO users (username, password) VALUES ('attacker', '12345'); --
    • Result: Creates a new backdoor account.
  3. DELETE: Removing data.
    • Input: '; DELETE FROM orders; --
    • Result: Wipes transaction history.
  4. DROP: Destructive structure change.
    • Input: '; DROP TABLE users; --
    • Result: Completely deletes the user table.

11. Evading Detection Mechanisms

Security devices (IDS/IPS/WAF) look for specific SQL keywords (like UNION or SELECT). Attackers use evasion techniques to bypass these filters.

Evasion Techniques

  • URL Encoding: Converting characters to %Hex format.
    • SELECT becomes %53%45%4C%45%43%54.
  • Case Variation: SQL is case-insensitive, but some filters are not.
    • SeLeCt * FrOm instead of SELECT * FROM.
  • Whitespace Manipulation: Replacing spaces with tabs or newlines, or removing spaces entirely using comments.
    • SELECT/**/user/**/FROM/**/users (The comments act as separators).
  • SQL Hex Encoding: Passing strings as hex values to avoid quotes.
    • SELECT * FROM users WHERE name = 0x61646D696E (Hex for 'admin').

12. SQL Injection Countermeasures

Preventing SQLi requires a combination of coding best practices and infrastructure hardening.

Primary Defense: Prepared Statements (Parameterized Queries)

This is the only sure way to prevent SQLi. It separates the code (SQL statement) from the data (user input).

  • How it works: The database pre-compiles the SQL statement with placeholders (?). The user input is then treated strictly as data, never as executable code.
  • Example (Java/JDBC):
    JAVA
        String query = "SELECT * FROM users WHERE username = ?";
        PreparedStatement pstmt = connection.prepareStatement(query);
        pstmt.setString(1, inputUser); // Input is treated as a literal string
        ResultSet results = pstmt.executeQuery();
        

Secondary Defenses

  1. Input Validation (Sanitization):
    • Use Allow-lists (White-listing): Only accept input that matches known good patterns (e.g., alphanumeric only for usernames).
    • Type Checking: Ensure input expecting an integer is actually an integer.
  2. Principle of Least Privilege:
    • The web application should connect to the database using an account with the minimum necessary permissions.
    • It should not have DROP or ALTER rights, and definitely not sa or root privileges.
  3. Web Application Firewall (WAF):
    • Filters incoming HTTP traffic looking for SQLi signatures and blocking malicious requests.
  4. Turn off Verbose Errors:
    • Configure the server to display generic error messages ("An error occurred") rather than database syntax errors, which help attackers debug their injection payloads.