Skip to content

Java Code Scanning and Semmle Query Suites Allows for Trusting All Certificates in SSL Connection #4852

@LordAmit

Description

@LordAmit

CodeQL’s java-code-scanning or java-lgtm-full query suite will not flag empty checkServerTrusted, and checkClientTrusted which allows for Trusting All Certificates. Additionally, the experimental UnsafeCert.ql query (reference: https://github.com/github/codeql/blob/main/java/ql/src/experimental/Security/CWE/CWE-273/UnsafeCertTrust.ql) does not flag these:

Here is the evaluated example:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URLConnection;

import javax.net.ssl.*;
import java.net.URL;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

public class BadSSL_Naive {

    public static final String userURL = "https://self-signed.badssl.com";

    private static X509TrustManager getX509TrustManager(){
        return new X509TrustManager(){
        
            @Override
            public X509Certificate[] getAcceptedIssuers() {
                // TODO Auto-generated method stub
                return null;
            }
        
            @Override
            public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                // TODO Auto-generated method stub
                
            }
        
            @Override
            public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                // TODO Auto-generated method stub
                
            }
        };
    }

    public static void main(final String[] args) {
        try {
            
            TrustManager[] trustAll = new TrustManager[]{
                getX509TrustManager()
            };

            SSLContext context = SSLContext.getInstance("SSL");
            context.init(null, trustAll, new SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
            // HttpsURLConnection.setDefaultHostnameVerifier(new DefaultHostnameVerifier());
            final URLConnection conn = new URL(userURL).openConnection();

            if (conn != null) {
                try (BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
                    String input;

                    while ((input = br.readLine()) != null) {
                        System.out.println(input);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    questionFurther information is requested

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions