GuardAPI Logo
GuardAPI

Fix SSRF (Server Side Request Forgery) in Rails

SSRF occurs when a Rails application fetches a remote resource without validating the user-supplied URL. Attackers use this to scan internal networks, access cloud metadata services (like 169.254.169.254), or bypass firewalls. Simply checking the string for 'localhost' is insufficient due to DNS rebinding and CIDR-based bypasses.

The Vulnerable Pattern

class DownloadsController < ApplicationController
  def preview
    # DANGER: User input is passed directly to Open-URI
    # An attacker can pass 'http://169.254.169.254/latest/meta-data/'
    # or 'file:///etc/passwd'
    image_data = URI.open(params[:url]).read
    send_data image_data, type: 'image/png', disposition: 'inline'
  end
end

The Secure Implementation

The fix involves three layers of defense. First, we restrict schemes to 'http' and 'https' to prevent 'file://' or 'gopher://' attacks. Second, we use the 'ssrf_filter' gem which resolves the hostname and checks the resulting IP address against a blacklist of private, loopback, and reserved ranges (RFC 1918). Third, it prevents DNS rebinding attacks by ensuring the request is made to the specific IP address that was validated, rather than re-resolving the hostname during the actual HTTP fetch.

class DownloadsController < ApplicationController
  def preview
    url = params[:url]
# Use a dedicated gem like 'ssrf_filter' to handle DNS resolution and private IP blocking
begin
  response = SsrfFilter.get(url, schemes: ['http', 'https']) do |req|
    req.read_timeout = 2
  end
  
  send_data response.body, type: response.content_type, disposition: 'inline'
rescue SsrfFilter::UnsafeUrlError => e
  render plain: "Access Denied: Unsafe URL detected", status: :forbidden
rescue StandardError => e
  render plain: "Error fetching resource", status: :bad_request
end

end end

System Alert • ID: 3150
Target: Rails API
Potential Vulnerability

Your Rails API might be exposed to SSRF (Server Side Request Forgery)

74% of Rails apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.

RUN FREE SECURITY DIAGNOSTIC
GuardLabs Engine: ONLINE

Free Tier • No Credit Card • Instant Report

Verified by Ghost Labs Security Team

This content is continuously validated by our automated security engine and reviewed by our research team. Ghost Labs analyzes over 500+ vulnerability patterns across 40+ frameworks to provide up-to-date remediation strategies.