การป้องกันการโจมตี SSRF
เรียนรู้การระบุและลดช่องโหว่การปลอมแปลงคำขอฝั่งเซิร์ฟเวอร์ (SSRF) ด้วยการตรวจสอบ URL และจำกัดคำขอเครือข่ายขาออก
การป้องกันการโจมตี SSRF เป็นบทเรียน Secure Coding & OWASP Top 10 for Backend ฟรีบน CoddyKit นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Secure Coding & OWASP Top 10 for Backend และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Secure Coding & OWASP Top 10 for Backend มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
Understanding SSRF Attacks
Server-Side Request Forgery (SSRF) is a critical web security vulnerability. It tricks a server into making requests to an unintended location, often internal resources or other external services.
Imagine your backend application acts as a proxy, fetching data or resources on behalf of a user. If an attacker can control the destination of these requests, you have an SSRF vulnerability.
How SSRF Works
Here's how SSRF typically works:
- Your application accepts a URL from a user.
- The server then makes a request to that URL to fetch data (e.g., an image, a file, a webpage).
- An attacker provides a malicious URL, pointing to an internal IP address or a sensitive service.
- The server, trusting the input, makes the request, potentially exposing internal data or services.
The Dangers of SSRF
The consequences of a successful SSRF attack can be severe:
- Access to internal systems: Attackers can scan internal networks, access databases, or administrative interfaces.
- Cloud metadata exposure: On cloud platforms (AWS, GCP, Azure), SSRF can expose sensitive instance metadata, including temporary credentials.
- Interaction with other services: The server might be forced to interact with other APIs or services it has access to, performing unauthorized actions.
- Port scanning: Attackers can use the server to scan ports on other internal or external machines.
Vulnerable Code in Action
Consider a simple backend service that fetches content from a user-provided URL. This Java example shows a common pattern that can lead to SSRF.
The fetchContent method directly uses a user-supplied URL to make an HTTP request without validation.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
public class Main {
public static void main(String[] args) {
// In a real app, this URL would come from user input (e.g., a web parameter)
String userSuppliedUrl = "http://example.com/data.txt";
// Malicious example: "http://169.254.169.254/latest/meta-data/"
try {
System.out.println("Fetching content from: " + userSuppliedUrl);
String content = fetchContent(userSuppliedUrl);
System.out.println("--- Fetched Content ---");
System.out.println(content.substring(0, Math.min(content.length(), 100)) + "...");
System.out.println("-----------------------");
} catch (Exception e) {
System.err.println("Error fetching content: " + e.getMessage());
}
}
public static String fetchContent(String urlString) throws Exception {
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
BufferedReader in = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuilder content = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();
return content.toString();
}
}The Power of Whitelisting
The most robust defense against SSRF is whitelisting. Instead of trying to block bad inputs, you should only allow known, safe inputs.
For URLs, this means defining a strict list of permitted domains, hostnames, or IP addresses that your application is allowed to connect to. Any request to a destination not on this list should be blocked.
Code for URL Whitelisting
Let's update our previous example to include a whitelist check. We'll define allowed domains and check the input URL against them before making any network requests.
This makes sure the server only connects to trusted external services.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Arrays;
import java.util.List;
public class Main {
private static final List<String> ALLOWED_HOSTS = Arrays.asList(
"example.com", "mytrustedapi.com"
);
public static void main(String[] args) {
String safeUrl = "http://example.com/data.txt";
String maliciousUrl = "http://badsite.com/evil.php";
try {
System.out.println("\nAttempting to fetch from: " + safeUrl);
String content = fetchContentSafely(safeUrl);
System.out.println("Fetched (safe): " + content.substring(0, Math.min(content.length(), 50)) + "...");
} catch (Exception e) {
System.err.println("Error fetching (safe): " + e.getMessage());
}
try {
System.out.println("\nAttempting to fetch from: " + maliciousUrl);
String content = fetchContentSafely(maliciousUrl);
System.out.println("Fetched (malicious): " + content.substring(0, Math.min(content.length(), 50)) + "...");
} catch (Exception e) {
System.err.println("Error fetching (malicious): " + e.getMessage());
}
}
public static String fetchContentSafely(String urlString) throws Exception {
URL url = new URL(urlString);
String host = url.getHost();
if (!ALLOWED_HOSTS.contains(host)) {
throw new IllegalArgumentException("Host not allowed: " + host);
}
URLConnection connection = url.openConnection();
BufferedReader in = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuilder content = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();
return content.toString();
}
}Blacklisting: A Risky Approach
You might think blacklisting known bad IPs or domains is easier. However, blacklisting is inherently weak against SSRF.
Attackers can use various tricks to bypass blacklists:
- IP address encoding: Using decimal, octal, or hexadecimal representations (e.g.,
http://0x7f000001for localhost). - DNS rebinding: Changing DNS records to point a 'safe' domain to an internal IP after the initial check.
- URL shorteners: Masking malicious URLs behind a seemingly benign short URL.
- Special protocols: Using
file://,gopher://, ordata://schemes if not explicitly blocked.
Always prefer whitelisting!
Layered Defense: Network Rules
Beyond application-level URL validation, you should also implement network-level controls:
- Firewall rules: Configure firewalls to block outgoing connections from your application server to internal IP ranges (e.g.,
10.0.0.0/8,172.16.0.0/12,192.168.0.0/16,127.0.0.1/8). - Network segmentation: Isolate the server making external requests into its own network segment, with minimal access to other internal resources.
- Least privilege: Ensure the application's runtime environment has only the necessary network access.
These measures provide a crucial second layer of defense.
Tricky URLs and Redirects
SSRF attacks can also exploit nuances in URL handling:
- Inconsistent URL parsers: Different libraries or systems might interpret a URL differently, potentially bypassing your validation. Always use a consistent, robust parser.
- HTTP Redirects: An attacker might provide a whitelisted URL that then redirects to a blacklisted internal IP. Your application must follow redirects carefully and re-validate the final destination URL.
Always validate the resolved URL after any redirects and before making the final request.
Preventing SSRF Attacks
Which of the following is the most effective strategy to prevent Server-Side Request Forgery (SSRF) vulnerabilities?
Recap: Secure Against SSRF
You've learned how to identify and prevent SSRF attacks!
- SSRF allows a server to make unauthorized requests to internal or external systems.
- The most effective defense is URL whitelisting, allowing connections only to trusted destinations.
- Avoid blacklisting, as it's prone to bypasses.
- Supplement application-level defenses with network firewalls and segmentation.
- Be cautious of URL parsing inconsistencies and always re-validate URLs after redirects.
Keep your backend secure by strictly controlling outgoing connections!
คำถามที่พบบ่อย
บทเรียน “การป้องกันการโจมตี SSRF” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “การป้องกันการโจมตี SSRF” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Secure Coding & OWASP Top 10 for Backend ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Secure Coding & OWASP Top 10 for Backend มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “การป้องกันการโจมตี SSRF”
เรียนรู้การระบุและลดช่องโหว่การปลอมแปลงคำขอฝั่งเซิร์ฟเวอร์ (SSRF) ด้วยการตรวจสอบ URL และจำกัดคำขอเครือข่ายขาออก คุณปฏิบัติ Secure Coding & OWASP Top 10 for Backend ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Secure Coding & OWASP Top 10 for Backend หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน Secure Coding & OWASP Top 10 for Backend บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน
บทเรียน “การป้องกันการโจมตี SSRF” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน Secure Coding & OWASP Top 10 for Backend นี้ได้ไหม
ได้ บทเรียน Secure Coding & OWASP Top 10 for Backend ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- การออกแบบ RESTful API ที่ปลอดภัย
- ความปลอดภัยของ GraphQL API
- การป้องกันการโจมตี SSRF
- การจำกัดและควบคุมอัตราการส่งคำขอของเอพีไอ