Перезагрузка пользователей с помощью ReloadableX509TrustManager - PullRequest
0 голосов
/ 17 декабря 2018

У меня следующая проблема.Я пытаюсь реализовать динамическую замену файла truststore.jks.Ситуация выглядит так: если на моем сервере нет сертификата клиента на сервере.Сервер не пропустит это.Когда я заменяю файл truststore.jks загружен, клиент принят, сервер получает сообщение от клиента.Однако через короткое время клиент отключается и делает так:

Пример кода моего сервера:

public void run() {
    try {
        factory = getSSLContext(TRUSTSTORE_PATH).getServerSocketFactory();
        SSLServerSocket ss = (SSLServerSocket) factory.createServerSocket(port);
        while (true) {
            SSLSocket s = (SSLSocket) ss.accept();
            s.setNeedClientAuth(true);
            SSLSession sslSession = s.getSession();
            String username = null;
            try {
                javax.security.cert.X509Certificate x509Certificate = sslSession.getPeerCertificateChain()[0];
                username = x509Certificate.getSubjectDN().getName().split("CN=")[1].split(",")[0];
                x509Certificate.checkValidity();
                if (username != null) {
                    System.out.println("User" + username + " signed in.");
                    System.out.println("Welcome " + username + ", you are authenticated!");
                } else {
                    System.out.println("User" + username + " tried to sign in but was rejected by the ACL.");
                    System.out.println("Username is not valid. Connection will be closed");
                    ss.close();
                    sslSession.invalidate();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

и мой ReloadableX509TrustManager класс:

class ReloadableX509TrustManager implements X509TrustManager {
    private final String trustStorePath;
    private X509TrustManager trustManager;
    private ArrayList tempCertList = new ArrayList();

    public ReloadableX509TrustManager(String tspath) throws Exception {
        this.trustStorePath = tspath;
        reloadTrustManager();
    }

    @Override
    public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
        try {
            reloadTrustManager();
        } catch (Exception e) {
            e.printStackTrace();
        }
        trustManager.checkClientTrusted(x509Certificates, s);
    }

    @Override
    public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
        try {
            trustManager.checkServerTrusted(x509Certificates, s);
        } catch (CertificateException cx) {
            trustManager.checkServerTrusted(x509Certificates, s);
        }
    }

    @Override
    public java.security.cert.X509Certificate[] getAcceptedIssuers() {
        java.security.cert.X509Certificate[] issuers = trustManager.getAcceptedIssuers();
        return issuers;
    }

    private void reloadTrustManager() throws Exception {
        KeyStore ts = KeyStore.getInstance("JKS");
        InputStream in = new FileInputStream(trustStorePath);
        try {
            ts.load(in, TRUSTSTORE_PASSWORD.toCharArray());
        } finally {
            in.close();
        }

        // add all temporary certs to KeyStore (ts)
        for (Object cert : tempCertList) {
            ts.setCertificateEntry(UUID.randomUUID().toString(), (Certificate) cert);
        }
        TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
        tmf.init(ts);

        // acquire X509 trust manager from factory
        TrustManager tms[] = tmf.getTrustManagers();
        for (int i = 0; i < tms.length; i++) {
            if (tms[i] instanceof X509TrustManager) {
                trustManager = (X509TrustManager) tms[i];
                return;
            }
        }

        throw new NoSuchAlgorithmException("No X509TrustManager in TrustManagerFactory");
    }
}
...