Skip to content
This repository was archived by the owner on Feb 19, 2026. It is now read-only.
This repository was archived by the owner on Feb 19, 2026. It is now read-only.

Security Hardening - Enhanced URL Validation to Prevent XSS and Malicious Redirect Attacks #3

@Shengxiang-Lin

Description

@Shengxiang-Lin

The current URL validation mechanism in the code contains security vulnerabilities that could be exploited for XSS attacks, open redirect attacks, and SSRF attacks. Implementing stricter URL validation is necessary to protect user and system security.
Affected Files

  • index.php (URL handling section around lines 20-25)
  • index.php (Redirect section around line 50)

Current Code Issues

Original Code Snippet (Approx. Lines 20-25)

$url = $_POST[‘url’] ?? ‘’;
if (empty($url)) {
    die(‘Please enter a URL’);
}
// Directly uses user-provided URL without proper validation

Security Risks

  1. XSS Attack Risk: Allows execution of malicious scripts via protocols
  2. Open Redirect Vulnerability: Can be exploited for phishing attacks
  3. SSRF Attack: May access internal network resources
  4. Protocol Abuse: Permits dangerous protocols like javascript:, data:, etc.

Attack Scenario Examples

1. XSS Attack

// Malicious user submission:
javascript:alert(‘XSS’)
data:text/html,<script>alert(‘XSS’)</script>

2. Phishing Attack

https://legitimate-site.com/redirect?url=evil-phishing-site.com

3. SSRF Attack

http://192.168.1.1/admin
http://169.254.169.254/latest/meta-data/  # AWS Metadata Service

Solutions

Enhanced URL Validation Function

/**
 * Validate whether a URL is safe
 * @param string $url The URL to validate
 * @return bool Whether it is safe
 */
function isValidUrl($url) {
    // 1. Basic null and format checks
    if (empty($url) || filter_var($url, FILTER_VALIDATE_URL) === false) {
        return false;
    }
    
    // 2. Protocol whitelist
    $allowed_schemes = [‘http’, ‘https’];
    $parsed = parse_url($url);
    
    if (!isset($parsed[‘scheme’]) || !in_array(strtolower($parsed[‘scheme’]), $allowed_schemes)) {
        return false;
    }
    
    // 3. Dangerous Protocol Check
    $dangerous_patterns = [‘javascript:’, ‘data:’, ‘vbscript:’, ‘file:’, ‘ftp:’];
    foreach ($dangerous_patterns as $pattern) {
        if (stripos($url, $pattern) === 0) {
            return false;
        }
}

// 4. Base Domain Validation
if (!isset($parsed[‘host’]) || empty($parsed[‘host’])) {
    return false;
}

return true;
}

Usage in Form Handling (Approx. Lines 20-25)

$url = $_POST[‘url’] ?? ‘’;
if (empty($url)) {
    die(‘Please enter a URL’);
}

if (!isValidUrl($url)) {
    die(‘Invalid URL. Only http and https protocols are allowed.’);
}

Validation during redirection (around line 50)

$stmt = $pdo->prepare(“SELECT original_url FROM short_urls WHERE short_code = ?”);
$stmt->execute([$code]);
$url = $stmt->fetchColumn();

if ($url && isValidUrl($url)) {
    // Log access (security audit)
    header(“Location: ” . $url);
    exit;
} else {
    // Do not expose specific error details
    die(‘Invalid short URL’);
}

Comparison of Improvement Effects

| Security Feature | Before Improvement | After Improvement |
|---------|--------|------- | XSS via javascript: | ❌ Vulnerable | ✅ Blocked |
| Malicious Data Protocols | ❌ Vulnerable | ✅ Blocked |
| Illegal Protocol Redirects | ❌ Vulnerable | ✅ Blocked |
| Basic URL Format Validation | ❌ None | ✅ Strict |
| Protocol Whitelist | ❌ No restrictions | ✅ HTTP/HTTPS only |

Optional Enhancements

For advanced security, consider:

  1. Domain blacklist/whitelist
  2. Internal IP address detection
  3. URL reputation checks
  4. Access frequency limits

Test Cases

// URLs that should be rejected
isValidUrl(“javascript:alert(‘xss’)”); // false
isValidUrl(“data:text/html,<script>alert(‘xss’)</script>”); // false
isValidUrl(“file:///etc/passwd”); // false
isValidUrl(“http://192.168.1.1/admin”); // Can be configured to false as needed

// URLs that should be accepted
isValidUrl(“https://example.com”); // true
isValidUrl(“http://www.google.com”); // true

Related Safety References

Metadata

Metadata

Assignees

Labels

SuspendedThis proposal is temporarily suspended and will be considered as appropriate for follow-up

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions