How to avoid this sonar security violation 'Security - URLConnection Server-Side Request Forgery (SSRF) and File Disclosure'?

Viewed 1051

I followed directions here.

https://rules.sonarsource.com/java/tag/injection/RSPEC-5144

As well as from here.

https://security.stackexchange.com/questions/123655/preventing-server-side-request-forgeries-in-java

Neither solutions worked to get rid of the vulnerability.

I don't know what else to do. Any ideas, or even pointers to what is wrong.

My code which has the Security Violation.

,,,

String vmUrl = TerraformStateService.findFqdnForVM(Long.parseLong(subid), workspace, vmName);
String jupyterUrl = vmUrl + "/hub";
URL url = new URL(jupyterUrl);

try {
    HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
    try {
        SSLService.setupSSL(keystoreCred, httpConnection);
        httpConnection.setRequestMethod("GET");
        if (httpConnection.getResponseCode() == 200 || httpConnection.getResponseCode() == 403) {
            return true;
        }
    } finally {
        httpConnection.disconnect();
    }

,,,

Note the findFqdnForVM gets the url from a state file saved on our end.

Here's my failed attempt at fixing it.

'''

String str = TerraformStateService.findFqdnForVM(Long.parseLong(subid), workspace, vmName);
try {
if (!str.startsWith(CommonConstants.URL_PREFIX_WHITELIST)){
    throw new Exception();
}
if (!str.endsWith(CommonConstants.URL_WHITELIST)){
    throw new Exception();
}
URL url = new URL(str);
if(!url.getProtocol().startsWith("http"))
    throw new Exception();
if (!url.getHost().equalsIgnoreCase(CommonConstants.URL_WHITELIST)){
    throw new Exception();
}
if (!url.getAuthority().equalsIgnoreCase(CommonConstants.URL_WHITELIST)) {
    throw new Exception();
}
InetAddress inetAddress = InetAddress.getByName(url.getHost());
if(inetAddress.isAnyLocalAddress() || inetAddress.isLoopbackAddress() || inetAddress.isLinkLocalAddress())
    throw new Exception();
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setInstanceFollowRedirects(false);
conn.connect();
try {
    SSLService.setupSSL(keystoreCred, conn);
    conn.setRequestMethod("GET");
    if (conn.getResponseCode() == 200 || conn.getResponseCode() == 403) {
        return true;
    }
} finally {
    conn.disconnect();
}

'''

I'm not sure how there is any danger here, I check against a whitelist which has a single endpoint. How can that not be secure?

0 Answers
Related