Server Side Vulnerabilities

Server-side vulnerabilities represent some of the most critical security issues in web applications. Unlike client-side attacks that execute in the user's browser, server-side vulnerabilities directly compromise the application server, database, or backend systems. These vulnerabilities can lead to complete system compromise, data breaches, and severe business impact.

This lecture covers the major server-side vulnerability classes that every security professional must understand.


Table of Contents


SQL Injection (SQLi)

SQLi Cover

SQL injection (SQLi) is a critical web security vulnerability that enables attackers to manipulate the database queries made by an application. By injecting malicious SQL code into application inputs, attackers can bypass authentication, extract sensitive data, modify or delete records, and in some cases achieve remote code execution on the database server.

SQLi remains one of the most dangerous and prevalent web vulnerabilities, consistently appearing in the OWASP Top 10.

Why SQL Injection Occurs

SQL injection vulnerabilities arise when:

  1. Dynamic SQL Construction: Application concatenates user input directly into SQL queries

  2. Insufficient Input Validation: User input is not properly sanitized or validated

  3. Lack of Parameterization: Queries don't use prepared statements or parameterized queries

  4. Error Message Disclosure: Detailed database errors are shown to users, aiding exploitation

Impact of SQL Injections

  1. Data Manipulation: Attackers can tamper with existing data, potentially altering, deleting, or inserting new records.

  2. Identity Spoofing: Attackers can gain unauthorized access by pretending to be someone else, potentially leading to unauthorized transactions and actions.

  3. Data Disclosure: Entire databases can be exposed, leading to theft of sensitive information like user details, financial records, personal messages, etc.

  4. Data Destruction: Databases can be destroyed or rendered unavailable, disrupting business operations and causing financial losses.

  5. Admin Rights: Attackers can potentially gain administrative rights to the database server, giving them unrestricted access and control.

  6. Remote Code Execution: In some database configurations (e.g., xp_cmdshell in SQL Server), attackers can execute operating system commands.

  7. Compliance Violations: Data breaches via SQLi can result in GDPR, HIPAA, PCI-DSS violations with severe financial penalties.

Basic SQL Injection Example

Vulnerable Login Code

Attack Example

An attacker enters:

Resulting in the SQL query:

The -- is a SQL comment marker. Everything after it is ignored, so the password check is bypassed!

Result: The attacker logs in as 'admin' without knowing the password.


Types of SQL Injection

1. Union-Based SQLi

Union-based SQLi exploits the SQL UNION operator to combine results from the injected query with the original query, allowing attackers to extract data from other tables.

Requirements:

  • Number of columns must match

  • Data types must be compatible

Example Attack:

Exploitation Steps:

  1. Determine number of columns:

  2. Find which columns accept string data:

  3. Extract data:

2. Boolean-Based Blind SQLi

When the application doesn't display database errors or query results, but behaves differently based on whether the injected condition is true or false.

Example Scenario:

Attack Payloads:

Automation with Python:

3. Time-Based Blind SQLi

When the application shows no visible difference between true and false conditions, attackers can use time delays to infer information.

Example Payloads:

Attack Logic:

  • If the condition is TRUE → Response delayed by 5 seconds

  • If the condition is FALSE → Response is immediate

4. Error-Based SQLi

Exploits verbose database error messages to extract data directly from error output.

Example Attack (MySQL):

Example Attack (PostgreSQL):

5. Out-of-Band SQLi

When in-band techniques don't work, attackers can use out-of-band channels (DNS, HTTP) to exfiltrate data.

DNS Exfiltration (MySQL):

When the database tries to load the file, it makes a DNS request to:

The attacker captures this DNS query on their authoritative DNS server.

HTTP Exfiltration (Microsoft SQL Server):

6. NoSQL Injection

NoSQL databases (MongoDB, CouchDB, etc.) are also vulnerable to injection attacks.

MongoDB Example:

Vulnerable Node.js code:

Attack Payload:

This query becomes:

Result: Authentication bypass

Additional NoSQL Injection Operators:

  • $gt, $gte - Greater than (equal)

  • $lt, $lte - Less than (equal)

  • $ne - Not equal

  • $regex - Regular expression matching

  • $where - JavaScript expression evaluation (dangerous!)

Example with $where:


SQL Injection Prevention

1. Parameterized Queries (Prepared Statements)

The most effective defense against SQL injection.

PHP (PDO):

Python (psycopg2):

Java (JDBC):

Node.js (MySQL):

2. Object-Relational Mapping (ORM)

Using ORM frameworks that abstract SQL queries:

Django (Python):

Sequelize (Node.js):

Entity Framework (C#):

3. Input Validation and Sanitization

Whitelist approach (preferred):

Escaping (less secure than parameterization, but better than nothing):

⚠️ Warning: Escaping is NOT sufficient on its own. Always prefer parameterized queries.

4. Least Privilege Principle

Database user accounts should have minimal necessary permissions:

5. Web Application Firewall (WAF)

Deploy a WAF to detect and block SQL injection attempts:

  • ModSecurity (open-source)

  • Cloudflare WAF

  • AWS WAF

  • Azure WAF

ModSecurity Rule Example:

6. Error Handling

Never expose database errors to users:

7. Security Testing

  • Static Analysis: Use tools like SonarQube, Checkmarx to detect SQLi in code

  • Dynamic Analysis: Use tools like SQLmap, Burp Suite to test running applications

  • Penetration Testing: Regular security assessments

SQLmap Example:


SQL Injection Detection

Indicators of SQL Injection Attempts:

  1. Web Application Firewall Logs:

    • Requests containing SQL keywords: UNION, SELECT, ' OR ', --, ;

    • Encoded SQL: %27 ('), %22 ("), %23 (#)

  2. Database Logs:

    • Unusual query patterns

    • Queries accessing information_schema

    • Multiple failed authentication attempts with SQL syntax

  3. Application Logs:

    • Increased database errors

    • Unexpected query execution times

Log Analysis Example:

For more Examples see: https://portswigger.net/web-security/sql-injection#sql-injection-examples

Server-Side Request Forgery (SSRF)

Server-side request forgery (SSRF) is a web security vulnerability that allows an attacker to induce the server-side application to make HTTP requests to an arbitrary domain of the attacker's choosing. This can include internal services, cloud metadata endpoints, or external systems.

In a typical SSRF attack, the attacker might cause the server to make a connection to internal-only services within the organization's infrastructure. In other cases, they may be able to force the server to connect to arbitrary external systems, potentially leaking sensitive data such as authorization credentials.

Why SSRF Occurs

SSRF vulnerabilities arise when:

  1. Unsanitized URLs: Application accepts user-supplied URLs without validation

  2. File Upload Features: File processing that fetches external resources (e.g., PDF generators)

  3. Webhooks: Applications that fetch data from user-provided webhook URLs

  4. API Integration: Features that proxy requests to third-party APIs

  5. Image/Document Processing: Features that load remote images or documents

Impact of SSRF Attacks

  1. Unauthorized Access: SSRF attacks can bypass access controls, potentially leading to unauthorized actions or data access within internal systems.

  2. Data Exfiltration: Sensitive data from the server or connected backend systems can be accessed, which may include personal, credential, or confidential information.

  3. Cloud Metadata Access: In cloud environments, SSRF can access instance metadata endpoints (AWS, Azure, GCP) to steal credentials and secrets.

  4. Internal Probing: SSRF can be utilized to map internal networks, discover services on other machines, and identify further vulnerabilities within an internal network.

  5. Arbitrary Command Execution: Some SSRF vulnerabilities may lead to remote code execution, allowing attackers to run arbitrary commands on the server or related systems.

  6. Secondary Attacks: The server can be manipulated to make requests to external systems, leading to secondary attacks that appear to come from the organization itself.

  7. Denial of Service: SSRF attacks can result in service overload, potentially leading to denial of service for internal services.


Basic SSRF Example

Vulnerable Code:

Attack Example:

The server makes a request to its own localhost/admin endpoint, which might be:

  • Not accessible from the internet

  • Protected by IP-based access controls

  • Containing sensitive administrative functions

Result: The attacker can access internal services that should not be publicly accessible.


SSRF Attack Scenarios

1. Accessing Internal Services

Target: Internal admin panel at http://192.168.1.10/admin

Why it works: The application server is inside the corporate network and can access internal IPs that are not routable from the internet.

2. Cloud Metadata Endpoints

Cloud providers expose instance metadata at special IP addresses. SSRF can be used to steal cloud credentials.

AWS Metadata Endpoint:

Response:

Azure Metadata Endpoint:

GCP Metadata Endpoint:

3. Port Scanning Internal Network

Attack: Use SSRF to scan internal network ports

4. Bypassing Authentication

Scenario: Admin panel accessible only from localhost

Normal request from internet:

SSRF attack:

5. Reading Local Files (using file:// protocol)

Response:


SSRF Bypass Techniques

Defenders often implement filters to prevent SSRF. Here are common bypass techniques:

1. Alternative IP Encoding

Decimal encoding:

Hexadecimal encoding:

Octal encoding:

Integer encoding:

2. DNS Rebinding

Attack Flow:

  1. Attacker controls evil.com DNS server

  2. First DNS query returns legitimate IP (e.g., 1.2.3.4)

  3. Application validates the IP is not internal

  4. Application makes request to evil.com

  5. Second DNS query (with short TTL) returns internal IP (e.g., 192.168.1.10)

  6. Request goes to internal service

DNS Configuration:

3. URL Parser Confusion

Different URL parsers may interpret URLs differently.

Some parsers interpret @ as authentication credentials, others as part of the hostname.

4. Redirect-Based SSRF

If the application follows redirects:

  1. Attacker provides: https://evil.com/redirect

  2. Application validates: evil.com is allowed

  3. evil.com/redirect returns HTTP 302 to http://169.254.169.254/...

  4. Application follows redirect to metadata endpoint

Evil server code:

5. Protocol Smuggling

Use alternative protocols if not properly filtered:

Gopher Protocol Example (Redis exploitation):

6. IPv6 Localhost

7. CIDR Bypass

If blacklist blocks 127.0.0.0/8:


Blind SSRF

When the application doesn't return the response to the attacker, but still makes the request.

Detection Methods:

1. Out-of-Band (OOB) Interaction

Use external services to detect SSRF:

Monitor for:

  • DNS queries to burpcollaborator.net

  • HTTP requests to your server

2. Time-Based Detection

Internal services respond faster than external:

Measure response time to infer port status.


SSRF Prevention

1. Whitelist Allowed Destinations

2. Disable Unused URL Schemes

3. Block Internal IP Ranges

⚠️ Warning: Checking IPs is complex due to DNS rebinding, TOCTOU (Time-of-Check-Time-of-Use), and encoding bypasses.

4. Use Network Segmentation

  • Place application servers in a DMZ (Demilitarized Zone)

  • Restrict outbound connections from application servers

  • Use firewall rules to block access to metadata endpoints

Firewall Rule (iptables):

5. Disable HTTP Redirects

6. IMDSv2 (AWS)

AWS IMDSv2 requires a session token, making SSRF exploitation harder:

Configure instances to require IMDSv2:

7. Response Validation

Even if request is made, don't return raw response to user:


SSRF Detection and Monitoring

Indicators of SSRF Attacks:

  1. Unusual Outbound Connections:

    • Requests to internal IPs

    • Connections to cloud metadata endpoints

    • Requests to localhost

  2. Access Logs:

    • URL parameters containing IPs or internal hostnames

    • Requests with unusual protocols (gopher, dict, file)

  3. Network Monitoring:

    • Monitor DNS queries for internal domain names from application servers

    • Alert on connections to 169.254.169.254

Log Analysis:


Command Injection

Command injection (also known as OS command injection) is a vulnerability that allows an attacker to execute arbitrary operating system commands on the server running the application. This typically occurs when an application passes unsafe user-supplied data (forms, cookies, HTTP headers) to a system shell.

Why Command Injection Occurs

  1. Unsafe Use of System Commands: Application executes system commands with user input

  2. Insufficient Input Validation: User input not properly sanitized before being passed to shell

  3. Dynamic Command Construction: String concatenation to build shell commands

Impact of Command Injection

  • Complete Server Compromise: Execute arbitrary commands with application privileges

  • Data Exfiltration: Read sensitive files, database credentials

  • Lateral Movement: Use compromised server to attack internal network

  • Backdoor Installation: Install persistent access mechanisms

  • Denial of Service: Crash services or consume resources


Basic Command Injection Example

Vulnerable Code:

Attack Payload:

Executed Command:

Result: The server pings 8.8.8.8 and then executes cat /etc/passwd, leaking system user accounts.


Command Injection Techniques

1. Command Separators

Different separators allow executing multiple commands:

Examples:

2. Blind Command Injection

When the application doesn't return command output, use out-of-band techniques:

Time-Based Detection:

If the response is delayed by 10 seconds, command injection exists.

DNS Exfiltration:

Monitor DNS queries on attacker.com to see the executed command result.

HTTP Exfiltration:

3. Bypassing Filters

Space Filtering Bypass:

Keyword Filtering Bypass:

Blacklist Bypass:


Command Injection Prevention

1. Avoid System Commands Entirely

Use built-in language functions instead of shell commands:

2. Input Validation (Whitelist)

3. Use Parameterized APIs

4. Principle of Least Privilege

Run application with minimal permissions:

5. Disable Dangerous Functions

In php.ini:


Path Traversal and File Inclusion

Path traversal (also known as directory traversal) allows attackers to access files and directories stored outside the web root folder. File inclusion vulnerabilities allow attackers to include files into the application, potentially leading to code execution.

Types of File Inclusion Vulnerabilities

  1. Path Traversal: Reading arbitrary files

  2. Local File Inclusion (LFI): Including local files in execution

  3. Remote File Inclusion (RFI): Including remote files in execution


Path Traversal

Vulnerable Code:

Attack Payload:

Executed Path:

Common Traversal Sequences:

Sensitive Files to Target:

Linux:

  • /etc/passwd - User accounts

  • /etc/shadow - Password hashes (if readable)

  • /home/user/.ssh/id_rsa - SSH private keys

  • /var/log/apache2/access.log - Web server logs

  • /proc/self/environ - Environment variables (may contain secrets)

Windows:

  • C:\windows\system32\config\sam - Windows password hashes

  • C:\windows\system32\drivers\etc\hosts - Hosts file

  • C:\inetpub\logs\LogFiles\W3SVC1\ - IIS logs


Local File Inclusion (LFI)

Allows including and executing local files.

Vulnerable Code:

Attack Payload:

The %00 (null byte) truncates the .php extension in some PHP versions < 5.3.4.

Result: The content of /etc/passwd is included and executed (though it's not PHP code, so it's just displayed).

LFI to RCE (Remote Code Execution)

1. Log Poisoning:

Attack Flow:

  1. Inject PHP code into log file

  2. Include log file via LFI

  3. Injected PHP code executes

Example:

2. PHP Session Files:

3. PHP Wrappers:


Remote File Inclusion (RFI)

Allows including files from external servers.

Vulnerable Code:

Attack:

  1. Create malicious PHP file on attacker server (http://attacker.com/evil.txt):

  2. Include via RFI:

Note: ? in the URL causes .php to be treated as a query parameter.


Path Traversal & File Inclusion Prevention

1. Whitelist Allowed Files

2. Use Basename

3. Validate Input Against Patterns

4. Disable Dangerous PHP Settings

In php.ini:

5. Use Realpath Validation


XML External Entity (XXE)

XML External Entity (XXE) is a vulnerability that allows attackers to interfere with an application's processing of XML data. It occurs when XML input containing a reference to an external entity is processed by a weakly configured XML parser.

Why XXE Occurs

  1. Unsafe XML Parsing: XML parser allows external entity resolution

  2. User-Controlled XML: Application accepts XML input from users

  3. DTD Processing Enabled: Document Type Definition (DTD) processing is enabled

Impact of XXE

  • File Disclosure: Read arbitrary files from the server

  • SSRF: Make requests to internal/external systems

  • Denial of Service: Billion Laughs attack (XML bomb)

  • Remote Code Execution: In rare cases with specific configurations


Basic XXE Example

Vulnerable Code:

Attack Payload:

Result: The content of /etc/passwd is read and displayed.


XXE Attack Techniques

1. File Disclosure

Read PHP source code:

2. SSRF via XXE

Access cloud metadata:

3. Blind XXE (Out-of-Band)

When the application doesn't return the XXE result, exfiltrate data via external requests:

Attack Flow:

  1. Host malicious DTD on attacker server (http://attacker.com/xxe.dtd):

  2. Trigger XXE in application:

  3. Attacker receives HTTP request with file contents:

4. XXE Denial of Service (Billion Laughs)

This expands to billions of "lol" strings, consuming all available memory.


XXE Prevention

1. Disable External Entity Processing

PHP (libxml):

Java (DocumentBuilderFactory):

Python (lxml):

.NET:

2. Use Simple Data Formats

Prefer JSON over XML when possible:

3. Input Validation

Validate XML structure before parsing:


Server-Side Template Injection (SSTI)

Server-Side Template Injection occurs when an attacker can inject template directives into a template, which are then executed server-side. This can lead to remote code execution.

Why SSTI Occurs

  1. User Input in Templates: User data is embedded directly into template syntax

  2. Unsafe Template Rendering: Templates are rendered with user-controlled content

  3. Template Engines: Vulnerability exists in various template engines (Jinja2, Twig, Freemarker, Velocity, etc.)

Impact of SSTI

  • Remote Code Execution: Execute arbitrary code on the server

  • File System Access: Read/write files

  • Information Disclosure: Access server-side objects and variables

  • Complete Server Compromise


SSTI Example (Jinja2 - Python)

Vulnerable Code:

Normal Usage:

Attack Payload:

The expression {{7*7}} is evaluated as template syntax!

Remote Code Execution:

Full Payload:


SSTI Exploitation by Template Engine

1. Jinja2 (Python)

Detection:

RCE Payload:

2. Twig (PHP)

Detection:

RCE Payload:

3. Freemarker (Java)

Detection:

RCE Payload:

4. Velocity (Java)

Detection:

RCE Payload:


SSTI Prevention

1. Never Put User Input Directly in Templates

VULNERABLE:

SECURE:

User input is passed as a variable, not embedded in template syntax.

2. Use Logic-Less Template Engines

Consider template engines with limited functionality:

  • Mustache: No logic, only variable substitution

  • Handlebars (with restricted helpers)

3. Sandbox Template Execution

⚠️ Note: Sandboxes can sometimes be bypassed. Defense in depth is critical.

4. Input Validation

If user input must be in templates, strictly validate it:


Insecure Deserialization

Insecure deserialization occurs when untrusted data is used to reconstruct objects. This can lead to remote code execution, authentication bypass, or other attacks.

Why Insecure Deserialization Occurs

  1. Trusting Serialized Data: Application deserializes data from untrusted sources

  2. Magic Methods: Languages have special methods called during deserialization

  3. Object Injection: Attacker can control object types and properties

Impact

  • Remote Code Execution: Arbitrary code execution via gadget chains

  • Authentication Bypass: Modify serialized session data

  • Data Tampering: Alter object properties

  • Denial of Service: Resource exhaustion


PHP Object Injection

Vulnerable Code:

Normal Cookie:

Attack:

Modify serialized object:

Set as cookie → Become admin!

More Dangerous Example (RCE):

Attack Payload:

When deserialized, __destruct() writes to shell.php, creating a webshell!


Python Pickle Deserialization

Vulnerable Code:

Attack (RCE):

When deserialized, os.system('rm -rf /') is executed!


Java Deserialization

Vulnerable Code:

Attack:

Java deserialization exploits use gadget chains - sequences of existing classes that, when chained together, achieve code execution.

Tools:

  • ysoserial: Generate Java deserialization payloads

  • Gadget chains: Commons-Collections, Spring, etc.

Example:


Insecure Deserialization Prevention

1. Never Deserialize Untrusted Data

2. Use Safe Serialization Formats

  • JSON: No code execution capabilities

  • XML (with XXE protections): Safer than binary formats

  • Protocol Buffers, MessagePack: Type-safe alternatives

3. Implement Integrity Checks

Sign serialized data to detect tampering:

4. Restrict Deserialization Classes

Java:

PHP:


Authentication and Authorization Flaws

Authentication verifies identity (who you are), while authorization determines permissions (what you can do). Flaws in these mechanisms can lead to complete application compromise.

Common Authentication Vulnerabilities

1. Weak Password Policy

Issues:

  • No minimum length requirements

  • No complexity requirements

  • Common passwords allowed

Example:

Prevention:

2. Broken Brute-Force Protection

Vulnerable Code:

Attack:

Prevention:

3. Insecure Session Management

Session Fixation:

Attack:

  1. Attacker gets session ID: PHPSESSID=attacker_session

  2. Attacker sends link to victim: https://bank.com/?PHPSESSID=attacker_session

  3. Victim logs in (session ID unchanged)

  4. Attacker uses same session ID → Logged in as victim!

Prevention:

4. JWT Vulnerabilities

None Algorithm Attack:

Attack:

Prevention:

Common Authorization Vulnerabilities

1. Insecure Direct Object References (IDOR)

Vulnerable Code:

Attack:

Prevention:

2. Horizontal Privilege Escalation

Attack: User A accesses User B's resources

3. Vertical Privilege Escalation

Attack: Regular user accesses admin functions

Vulnerable Code:

Attack:

Prevention:

4. Missing Function-Level Access Control

Example: Admin function accessible to anyone who knows the URL

Prevention:


Defense in Depth

Effective server-side security requires multiple layers of protection:

  1. Secure Coding Practices

    • Input validation (whitelist approach)

    • Output encoding

    • Parameterized queries

    • Principle of least privilege

  2. Framework Security Features

    • Use built-in security functions

    • Enable security headers

    • Configure frameworks securely

  3. Infrastructure Security

    • Network segmentation

    • Firewall rules

    • Security groups (cloud)

  4. Monitoring and Detection

    • Log analysis

    • Intrusion detection systems (IDS)

    • Security Information and Event Management (SIEM)

  5. Regular Security Testing

    • Static Application Security Testing (SAST)

    • Dynamic Application Security Testing (DAST)

    • Penetration testing

    • Bug bounty programs


Key Takeaways

  1. Server-side vulnerabilities directly compromise backend systems and are often more severe than client-side issues

  2. SQL Injection remains prevalent despite being well-known; always use parameterized queries

  3. SSRF is particularly dangerous in cloud environments due to metadata endpoints

  4. Command Injection can lead to complete server compromise; avoid system commands when possible

  5. File Inclusion vulnerabilities can escalate to RCE through log poisoning and wrappers

  6. XXE attacks leverage XML parsing; disable external entity processing

  7. SSTI allows RCE through template engines; never put user input directly in templates

  8. Insecure Deserialization can be exploited for RCE; use safe formats like JSON

  9. Authentication/Authorization flaws are common and critical; implement proper access controls

  10. Defense in Depth is essential; no single control is sufficient


Hands-On Exercises

  1. SQL Injection Practice:

    • Set up a vulnerable web application (e.g., DVWA, bWAPP)

    • Practice Union-based, Blind, and Time-based SQLi

    • Use SQLmap to automate exploitation

  2. SSRF Exploitation:

    • Deploy a web app with URL fetching feature

    • Access cloud metadata endpoints (in safe environment)

    • Practice bypass techniques

  3. Command Injection:

    • Create a ping utility with unsanitized input

    • Practice command separators and filter bypasses

    • Implement secure version using subprocess with arrays

  4. LFI to RCE:

    • Set up PHP application with LFI vulnerability

    • Practice log poisoning technique

    • Experiment with PHP wrappers

  5. XXE Exploitation:

    • Create XML parsing endpoint

    • Practice file disclosure and SSRF via XXE

    • Implement secure XML parsing

  6. SSTI:

    • Deploy Flask/Jinja2 application with template injection

    • Craft RCE payloads for different template engines

    • Practice detection and exploitation

  7. Authorization Testing:

    • Test web applications for IDOR vulnerabilities

    • Practice horizontal and vertical privilege escalation

    • Implement proper authorization controls


Resources

Official Documentation

OWASP Resources

Practice Platforms

  • PortSwigger Web Security Academy: Free interactive labs

  • HackTheBox: Realistic vulnerable machines

  • TryHackMe: Guided learning paths

  • PentesterLab: Web penetration testing exercises

  • DVWA (Damn Vulnerable Web Application): Practice environment

  • bWAPP: Buggy web application for testing

Tools

  • SQLmap: Automated SQL injection tool

  • Burp Suite: Web application security testing

  • ysoserial: Java deserialization exploit tool

  • tplmap: Server-side template injection detection

  • XXEinjector: XXE exploitation tool

  • Commix: Command injection exploitation tool

Books

  • "The Web Application Hacker's Handbook" by Dafydd Stuttard and Marcus Pinto

  • "Web Security Testing Cookbook" by Paco Hope and Ben Walther

  • "SQL Injection Attacks and Defense" by Justin Clarke

Last updated