Last active
January 15, 2020 16:36
-
-
Save voidfyoo/6774c4e32f79dde9a0ad1376d5740013 to your computer and use it in GitHub Desktop.
An example of SSRF defence in Java.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.BufferedInputStream; | |
import java.io.ByteArrayOutputStream; | |
import java.io.InputStream; | |
import java.net.*; | |
import java.nio.ByteBuffer; | |
public class Request { | |
public static void main(String[] args) throws Exception { | |
URL url = new URL(args[0]); // e.g. http://httpbin.org/get | |
// Check protocol | |
if (!url.getProtocol().startsWith("http")) { | |
throw new MalformedURLException("wrong protocol"); | |
} | |
String hostname = url.getHost(); | |
InetAddress inetAddress = InetAddress.getByName(hostname); | |
// Check host address | |
if (isInnerAddress(inetAddress)) { | |
throw new MalformedURLException("wrong host address"); | |
} | |
HttpURLConnection connection = (HttpURLConnection) url.openConnection(); | |
connection.setRequestMethod("GET"); | |
connection.setInstanceFollowRedirects(false); // Do not follow redirects | |
InputStream responseStream = connection.getInputStream(); | |
// Output http response content | |
BufferedInputStream bis = new BufferedInputStream(responseStream); | |
ByteArrayOutputStream buf = new ByteArrayOutputStream(); | |
int result = bis.read(); | |
while(result != -1) { | |
buf.write((byte) result); | |
result = bis.read(); | |
} | |
String response = buf.toString("UTF-8"); | |
System.out.println(response); | |
} | |
public static boolean isInnerAddress(InetAddress inetAddress) { | |
return inetAddress.isAnyLocalAddress() | |
|| inetAddress.isLoopbackAddress() | |
|| inetAddress.isLinkLocalAddress() | |
|| inetAddress.isSiteLocalAddress(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Since the default security configuration TTL time in Java is 10 seconds, the problem of DNS rebinding attack is not considered.