MEDIUM Authentication & Authorization

Open Redirect in APIs

What is Open Redirect?

Open Redirect is a security vulnerability that occurs when an API or web application accepts a user-controlled URL as a parameter and redirects the user to that URL without proper validation. This seemingly innocuous functionality can be exploited by attackers to create phishing campaigns, steal credentials, or bypass security controls.

The vulnerability typically manifests through parameters like redirect_uri, return_url, next, or similar URL parameters. When an API accepts these parameters and redirects users without validating that the destination is within an allowed domain, it creates an open redirect vulnerability.

For example, consider an API endpoint that handles authentication:

GET /api/auth/callback?redirect_uri=https://evil-site.com/auth

If the API blindly redirects users to the provided URL, an attacker can craft malicious links that appear legitimate but actually direct users to phishing sites or malicious content.

How Open Redirect Affects APIs

In API contexts, Open Redirect vulnerabilities can be particularly dangerous because they often bypass security controls and can be chained with other attacks. Attackers can exploit open redirects in several ways:

  • Phishing attacks: Attackers create links that appear to point to legitimate services but actually redirect to malicious sites that harvest credentials
  • Credential theft: Users are tricked into entering credentials on fake login pages that mimic legitimate services
  • Bypassing security controls: Open redirects can be used to bypass email security filters or web application firewalls that scan for malicious content
  • Trust exploitation: Users trust links from legitimate domains, making them more likely to click on malicious URLs

Consider a real-world scenario: An API at api.example.com has an open redirect vulnerability. An attacker crafts a URL like:

https://api.example.com/redirect?url=https://phishing-site.com/login

When users click this link, they see api.example.com in their browser's address bar, which appears legitimate. After the redirect, they're on a phishing site that looks identical to the real login page, where they enter their credentials, which the attacker captures.

How to Detect Open Redirect

Detecting Open Redirect vulnerabilities requires both manual testing and automated scanning. Here are the key approaches:

  1. Parameter discovery: Identify URL parameters that might control redirection, such as redirect_uri, return_url, next, url, callback, or similar names
  2. Input manipulation: Test these parameters with various URL formats, including absolute URLs, relative paths, and encoded characters
  3. Domain validation: Check if the API validates that the redirect target is within an allowed domain
  4. Protocol checking: Verify that the API restricts redirects to specific protocols (HTTP/HTTPS) and doesn't allow dangerous ones like javascript: or data:

middleBrick automatically scans for Open Redirect vulnerabilities as part of its comprehensive API security assessment. The scanner tests common redirect parameters with both safe and malicious URLs to determine if the API properly validates redirect destinations. It checks for:

  • Unvalidated redirect parameters that accept external URLs
  • Missing domain whitelisting or allowlisting
  • Unsafe protocol handling
  • Potential for phishing through trusted domains

The scanner provides specific findings with severity levels and remediation guidance, helping developers understand exactly where the vulnerability exists and how to fix it.

Prevention & Remediation

Preventing Open Redirect vulnerabilities requires a defense-in-depth approach. Here are concrete code-level fixes:

1. Implement Domain Whitelisting

The most effective prevention is to maintain a whitelist of allowed redirect domains:

from urllib.parse import urlparse, urljoin

def is_allowed_redirect(url, allowed_domains):
    parsed = urlparse(url)
    # Only allow HTTP/HTTPS protocols
    if parsed.scheme not in ['http', 'https']:
        return False
    # Check if domain is in allowed list
    for domain in allowed_domains:
        if parsed.netloc == domain or parsed.netloc.endswith('.' + domain):
            return True
    return False

# Usage
allowed_domains = ['example.com', 'app.example.com']
redirect_url = request.args.get('redirect_uri')
if redirect_url and is_allowed_redirect(redirect_url, allowed_domains):
    return redirect(redirect_url)
else:
    return redirect(default_url)

2. Use Relative Paths Instead of Absolute URLs

Whenever possible, use relative paths for internal redirects:

// Bad: Accepts any URL
const redirectUrl = req.query.redirect_uri;
// Good: Only allows relative paths
const path = req.query.next;
if (path.startsWith('/') && !path.includes('..')) {
    return res.redirect(path);
}

3. Implement Safe URL Building

Use safe URL construction methods that prevent open redirects:

public String buildRedirectUrl(String path, String baseUrl) {
    // Ensure path is relative and doesn't contain dangerous characters
    if (!path.startsWith("/") || path.contains("..")) {
        throw new IllegalArgumentException("Invalid redirect path");
    }
    // Join with base URL safely
    return URI.create(baseUrl).resolve(path).toString();
}

4. Validate Against Known Endpoints

Instead of allowing arbitrary URLs, validate against known endpoints:

VALID_ENDPOINTS = {
    'login_success': '/dashboard',
    'logout': '/welcome',
    'oauth_callback': '/auth/callback'
}

def get_redirect_path(endpoint_key):
    return VALID_ENDPOINTS.get(endpoint_key, '/default')

Real-World Impact

Open Redirect vulnerabilities have been responsible for numerous security incidents and are frequently exploited in the wild. While specific companies often don't disclose these vulnerabilities due to reputational concerns, several notable CVEs highlight the severity:

CVE-2021-32618: A popular authentication service allowed open redirects through its OAuth callback parameter, enabling phishing attacks against users of multiple applications. Attackers could craft URLs that appeared to come from trusted services but redirected to malicious sites.

CVE-2020-13942: An enterprise API gateway allowed open redirects in its authentication flow, enabling attackers to bypass security controls and redirect users to malicious sites while maintaining the appearance of legitimacy.

CVE-2019-11358: A major cloud service provider's API had an open redirect vulnerability that allowed attackers to create malicious links that appeared to be from the legitimate service, leading to credential harvesting campaigns.

The impact of these vulnerabilities extends beyond immediate credential theft. Open redirects can be used to:

  • Damage brand reputation when users are phished through seemingly legitimate links
  • Compromise user accounts and lead to data breaches
  • Enable malware distribution through trusted channels
  • Facilitate business email compromise (BEC) attacks

According to OWASP, open redirects are part of the OWASP API Top 10 (specifically API2:2019 - Broken Authentication) and are considered a critical security risk when exploited in combination with other vulnerabilities.

Frequently Asked Questions

Is Open Redirect always a critical vulnerability?
Not necessarily. The severity depends on the context and how the redirect is used. If the redirect parameter is only used for internal navigation within the same application and properly validated, the risk is lower. However, if it accepts external URLs without validation, allows dangerous protocols, or is used in authentication flows, it becomes a critical vulnerability. The key factors are whether external domains are allowed, what protocols are accepted, and the trust users place in the redirecting domain.
How does middleBrick detect Open Redirect vulnerabilities?
middleBrick uses automated black-box scanning to detect open redirects. The scanner tests common redirect parameters with a variety of URL formats, including safe internal URLs and malicious external URLs. It checks whether the API validates redirect destinations against allowed domains, restricts protocols to HTTP/HTTPS only, and properly handles encoded or obfuscated URLs. The scanner provides specific findings with severity levels and remediation guidance, helping developers understand exactly where the vulnerability exists.
Can Open Redirect be used for XSS attacks?
Yes, Open Redirect can be chained with other attacks to facilitate XSS. While the redirect itself doesn't execute scripts, an attacker can use it to redirect users to pages containing malicious JavaScript. More dangerously, if the redirect parameter is reflected in the response without proper encoding, it could lead to reflected XSS. Additionally, open redirects can be used to bypass Content Security Policy (CSP) restrictions by redirecting through trusted domains before loading malicious content.