Fix SSRF (Server Side Request Forgery) in Grape
SSRF in Grape APIs occurs when untrusted user input is passed directly to an HTTP client, allowing attackers to coerce the server into making requests to internal infrastructure, cloud metadata services (169.254.169.254), or local loopback addresses. If you're blindly passing params[:url] to Net::HTTP, you're leaking your internal network architecture.
The Vulnerable Pattern
class VulnerableAPI < Grape::API
format :json
resource :fetcher do
params do
requires :image_url, type: String, desc: 'URL of the image to fetch'
end
get :image do
# VULNERABLE: No validation on the scheme, host, or IP resolution.
# Attackers can hit http://localhost:6379 or http://169.254.169.254/latest/meta-data/
uri = URI.parse(params[:image_url])
Net::HTTP.get(uri)
end
end
end
The Secure Implementation
The fix eliminates SSRF by implementing three critical controls. First, it enforces a protocol allowlist (HTTPS only). Second, it uses the 'ssrf_filter' gem which resolves the hostname and checks the resulting IP against a blacklist of private/reserved ranges (like 10.0.0.0/8 or 127.0.0.1) before the socket is opened. Third, it mitigates DNS rebinding by ensuring the IP validated is the same IP used for the connection, preventing an attacker from switching a safe domain to a local IP between the check and the request.
class SecureAPI < Grape::API
format :json
resource :fetcher do
params do
requires :url, type: String
end
get :image do
# SECURE: Use a hardened client like 'ssrf_filter' to validate the target.
# This prevents DNS rebinding and blocks internal IP ranges (RFC 1918).
begin
response = SsrfFilter.get(params[:url]) do |req|
req.scheme = 'https' # Enforce HTTPS
req.max_redirects = 2
end
response.body
rescue SsrfFilter::UnsafeUrlError => e
error!({ error: 'Prohibited target: Internal or unsafe address' }, 403)
rescue StandardError => e
error!({ error: 'Request failed' }, 400)
end
end
end
end
Your Grape API
might be exposed to SSRF (Server Side Request Forgery)
74% of Grape apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.
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.