Search in sources :

Example 86 with SSLSession

use of javax.net.ssl.SSLSession in project opentheso by miledrousset.

the class HandleClient method deleteHandle.

/**
 * Permet de supprimer l'identifiant Handle d'une resource
 * @param pass
 * @param pathKey
 * @param pathCert
 * @param urlHandle
 * @param idHandle
 * @return
 */
public boolean deleteHandle(String pass, String pathKey, String pathCert, String urlHandle, String idHandle) {
    // exp : idHandle = (20.500.11942/LDx76olvIm)
    String output;
    String xmlRecord = "";
    try {
        KeyStore clientStore = KeyStore.getInstance("PKCS12");
        // "motdepasse" = le mot de passe saisie pour la génération des certificats.
        // clientStore.load(new FileInputStream("key.p12"), "motdepasse".toCharArray());
        clientStore.load(this.getClass().getResourceAsStream(pathKey), pass.toCharArray());
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(clientStore, pass.toCharArray());
        KeyStore trustStore = KeyStore.getInstance("JKS");
        // trustStore.load(new FileInputStream("cacerts2"), pass.toCharArray());
        trustStore.load(this.getClass().getResourceAsStream(pathCert), pass.toCharArray());
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(trustStore);
        SSLContext sslContext;
        sslContext = SSLContext.getInstance("TLS");
        sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom());
        // URL url = new URL("https://cchum-isi-handle01.in2p3.fr:8001/api/handles/20.500.11942/opentheso443");
        URL url = new URL(urlHandle + idHandle);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setSSLSocketFactory(sslContext.getSocketFactory());
        conn.setRequestMethod("DELETE");
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("Authorization", "Handle clientCert=\"true\"");
        conn.setHostnameVerifier(new HostnameVerifier() {

            @Override
            public boolean verify(String arg0, SSLSession arg1) {
                return true;
            }
        });
        conn.setUseCaches(false);
        conn.setDoInput(true);
        conn.setDoOutput(true);
        int status = conn.getResponseCode();
        InputStream in = status >= 400 ? conn.getErrorStream() : conn.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        while ((output = br.readLine()) != null) {
            xmlRecord += output;
        }
        byte[] bytes = xmlRecord.getBytes();
        xmlRecord = new String(bytes, Charset.forName("UTF-8"));
        if (status == 200) {
            message = "Suppression du Handle réussie";
        }
        if (status == 100) {
            message = "Handle n'existe pas";
        }
        message = message + "\n" + xmlRecord;
        message = message + "\n" + "status de la réponse : " + status;
        return true;
    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(HandleClient.class.getName()).log(Level.SEVERE, null, ex);
    } catch (KeyStoreException ex) {
        Logger.getLogger(HandleClient.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(HandleClient.class.getName()).log(Level.SEVERE, null, ex);
    } catch (CertificateException ex) {
        Logger.getLogger(HandleClient.class.getName()).log(Level.SEVERE, null, ex);
    } catch (UnrecoverableKeyException ex) {
        Logger.getLogger(HandleClient.class.getName()).log(Level.SEVERE, null, ex);
    } catch (KeyManagementException ex) {
        Logger.getLogger(HandleClient.class.getName()).log(Level.SEVERE, null, ex);
    } catch (MalformedURLException ex) {
        Logger.getLogger(HandleClient.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(HandleClient.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        Logger.getLogger(HandleClient.class.getName()).log(Level.SEVERE, null, ex);
    }
    return false;
}
Also used : MalformedURLException(java.net.MalformedURLException) CertificateException(java.security.cert.CertificateException) JsonString(javax.json.JsonString) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) URL(java.net.URL) KeyManagementException(java.security.KeyManagementException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) SSLSession(javax.net.ssl.SSLSession) SecureRandom(java.security.SecureRandom) UnsupportedEncodingException(java.io.UnsupportedEncodingException) SSLContext(javax.net.ssl.SSLContext) KeyStoreException(java.security.KeyStoreException) IOException(java.io.IOException) KeyStore(java.security.KeyStore) KeyStoreException(java.security.KeyStoreException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) KeyManagementException(java.security.KeyManagementException) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) KeyManagerFactory(javax.net.ssl.KeyManagerFactory) HostnameVerifier(javax.net.ssl.HostnameVerifier) TrustManagerFactory(javax.net.ssl.TrustManagerFactory) BufferedReader(java.io.BufferedReader) HttpsURLConnection(javax.net.ssl.HttpsURLConnection)

Example 87 with SSLSession

use of javax.net.ssl.SSLSession in project opentheso by miledrousset.

the class HandleClient method updateHandle.

/**
 * Permet de mettre à jour l'URL et les données d'une resource Handle
 * cette fonction donne la même action que le putHandle
 * @param pass
 * @param pathKey
 * @param pathCert
 * @param urlHandle
 * @param idHandle
 * @param jsonData
 * @return
 */
public boolean updateHandle(String pass, String pathKey, String pathCert, String urlHandle, String idHandle, String jsonData) {
    String output;
    String xmlRecord = "";
    try {
        KeyStore clientStore = KeyStore.getInstance("PKCS12");
        // "motdepasse" = le mot de passe saisie pour la génération des certificats.
        // clientStore.load(new FileInputStream("key.p12"), "motdepasse".toCharArray());
        clientStore.load(this.getClass().getResourceAsStream(pathKey), pass.toCharArray());
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(clientStore, pass.toCharArray());
        KeyStore trustStore = KeyStore.getInstance("JKS");
        // trustStore.load(new FileInputStream("cacerts2"), pass.toCharArray());
        trustStore.load(this.getClass().getResourceAsStream(pathCert), pass.toCharArray());
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(trustStore);
        SSLContext sslContext;
        sslContext = SSLContext.getInstance("TLS");
        sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom());
        // URL url = new URL("https://cchum-isi-handle01.in2p3.fr:8001/api/handles/20.500.11942/opentheso443");
        URL url = new URL(urlHandle + idHandle);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setSSLSocketFactory(sslContext.getSocketFactory());
        conn.setRequestMethod("PUT");
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("Authorization", "Handle clientCert=\"true\"");
        conn.setHostnameVerifier(new HostnameVerifier() {

            @Override
            public boolean verify(String arg0, SSLSession arg1) {
                return true;
            }
        });
        conn.setUseCaches(false);
        conn.setDoInput(true);
        conn.setDoOutput(true);
        OutputStream os = conn.getOutputStream();
        OutputStreamWriter out = new OutputStreamWriter(os);
        out.write(jsonData);
        out.flush();
        int status = conn.getResponseCode();
        InputStream in = status >= 400 ? conn.getErrorStream() : conn.getInputStream();
        // status = 201 = création réussie
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        while ((output = br.readLine()) != null) {
            xmlRecord += output;
        }
        byte[] bytes = xmlRecord.getBytes();
        xmlRecord = new String(bytes, Charset.forName("UTF-8"));
        os.close();
        conn.disconnect();
        if (status == 200) {
            message = "Mise à jour du Handle réussie";
        }
        if (status == 100) {
            message = "Handle n'existe pas";
        }
        message = message + "\n" + xmlRecord;
        message = message + "\n" + "status de la réponse : " + status;
        return true;
    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(HandleClient.class.getName()).log(Level.SEVERE, null, ex);
    } catch (KeyStoreException ex) {
        Logger.getLogger(HandleClient.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(HandleClient.class.getName()).log(Level.SEVERE, null, ex);
    } catch (CertificateException ex) {
        Logger.getLogger(HandleClient.class.getName()).log(Level.SEVERE, null, ex);
    } catch (UnrecoverableKeyException ex) {
        Logger.getLogger(HandleClient.class.getName()).log(Level.SEVERE, null, ex);
    } catch (KeyManagementException ex) {
        Logger.getLogger(HandleClient.class.getName()).log(Level.SEVERE, null, ex);
    } catch (MalformedURLException ex) {
        Logger.getLogger(HandleClient.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(HandleClient.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        Logger.getLogger(HandleClient.class.getName()).log(Level.SEVERE, null, ex);
    }
    return false;
}
Also used : MalformedURLException(java.net.MalformedURLException) OutputStream(java.io.OutputStream) CertificateException(java.security.cert.CertificateException) JsonString(javax.json.JsonString) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) URL(java.net.URL) KeyManagementException(java.security.KeyManagementException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) SSLSession(javax.net.ssl.SSLSession) SecureRandom(java.security.SecureRandom) UnsupportedEncodingException(java.io.UnsupportedEncodingException) SSLContext(javax.net.ssl.SSLContext) KeyStoreException(java.security.KeyStoreException) IOException(java.io.IOException) KeyStore(java.security.KeyStore) KeyStoreException(java.security.KeyStoreException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) KeyManagementException(java.security.KeyManagementException) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) KeyManagerFactory(javax.net.ssl.KeyManagerFactory) HostnameVerifier(javax.net.ssl.HostnameVerifier) TrustManagerFactory(javax.net.ssl.TrustManagerFactory) BufferedReader(java.io.BufferedReader) OutputStreamWriter(java.io.OutputStreamWriter) HttpsURLConnection(javax.net.ssl.HttpsURLConnection)

Example 88 with SSLSession

use of javax.net.ssl.SSLSession in project yamcs-studio by yamcs.

the class ResourceUtil method openRawURLStream.

/**
 * Open URL Stream from remote.
 *
 * @param url
 * @return
 * @throws IOException
 */
private static InputStream openRawURLStream(final URL url) throws IOException {
    if (url.getProtocol().equals("https")) {
        // $NON-NLS-1$
        // The code to support https protocol is provided by Eric Berryman (eric.berryman@gmail.com) from Frib
        // Create a trust manager that does not validate certificate chains
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

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

            @Override
            public void checkClientTrusted(X509Certificate[] certs, String authType) {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            }
        } };
        // Install the all-trusting trust manager
        SSLContext sc = null;
        try {
            sc = SSLContext.getInstance("SSL");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
        try {
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
        } catch (KeyManagementException e) {
            e.printStackTrace();
        }
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        // Create all-trusting host name verifier
        HostnameVerifier allHostsValid = new HostnameVerifier() {

            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };
        // Install the all-trusting host verifier
        HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
    }
    URLConnection connection = url.openConnection();
    connection.setReadTimeout(PreferencesHelper.getURLFileLoadingTimeout());
    return connection.getInputStream();
}
Also used : SSLSession(javax.net.ssl.SSLSession) SSLContext(javax.net.ssl.SSLContext) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) X509Certificate(java.security.cert.X509Certificate) KeyManagementException(java.security.KeyManagementException) URLConnection(java.net.URLConnection) HttpsURLConnection(javax.net.ssl.HttpsURLConnection) TrustManager(javax.net.ssl.TrustManager) X509TrustManager(javax.net.ssl.X509TrustManager) HostnameVerifier(javax.net.ssl.HostnameVerifier) X509TrustManager(javax.net.ssl.X509TrustManager)

Example 89 with SSLSession

use of javax.net.ssl.SSLSession in project athenz by yahoo.

the class ZTSClientTest method testHostNameVerifierVerifyCertNull.

@Test
public void testHostNameVerifierVerifyCertNull() throws SSLPeerUnverifiedException {
    ZTSRDLClientMock ztsClientMock = new ZTSRDLClientMock();
    Principal principal = SimplePrincipal.create("user_domain", "user", "v=S1;d=user_domain;n=user;s=sig", PRINCIPAL_AUTHORITY);
    ZTSClient client = new ZTSClient("http://localhost:4080", principal);
    client.setZTSRDLGeneratedClient(ztsClientMock);
    ZTSClient.AWSHostNameVerifier hostnameVerifier = client.new AWSHostNameVerifier("host1");
    SSLSession session = Mockito.mock(SSLSession.class);
    Mockito.when(session.getPeerCertificates()).thenReturn(null);
    assertFalse(hostnameVerifier.verify("host1", session));
    System.out.println("hashCode:" + client.hashCode());
    client.close();
}
Also used : SSLSession(javax.net.ssl.SSLSession) SimplePrincipal(com.yahoo.athenz.auth.impl.SimplePrincipal) Principal(com.yahoo.athenz.auth.Principal) Test(org.testng.annotations.Test)

Example 90 with SSLSession

use of javax.net.ssl.SSLSession in project athenz by yahoo.

the class ZTSClientTest method testHostNameVerifierVerifyCert.

@Test
public void testHostNameVerifierVerifyCert() throws CertificateException, IOException {
    ZTSRDLClientMock ztsClientMock = new ZTSRDLClientMock();
    Principal principal = SimplePrincipal.create("user_domain", "user", "v=S1;d=user_domain;n=user;s=sig", PRINCIPAL_AUTHORITY);
    ZTSClient client = new ZTSClient("http://localhost:4080", principal);
    client.setZTSRDLGeneratedClient(ztsClientMock);
    ZTSClient.AWSHostNameVerifier hostnameVerifier = client.new AWSHostNameVerifier("host1");
    InputStream is = new ByteArrayInputStream(test_cert.getBytes("utf-8"));
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    java.security.cert.Certificate cert = cf.generateCertificate(is);
    is.close();
    Certificate[] certs = new Certificate[1];
    certs[0] = cert;
    SSLSession session = Mockito.mock(SSLSession.class);
    Mockito.when(session.getPeerCertificates()).thenReturn(certs);
    assertFalse(hostnameVerifier.verify("unknown", session));
    client.close();
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) SSLSession(javax.net.ssl.SSLSession) CertificateFactory(java.security.cert.CertificateFactory) Certificate(java.security.cert.Certificate) ByteArrayInputStream(java.io.ByteArrayInputStream) SimplePrincipal(com.yahoo.athenz.auth.impl.SimplePrincipal) Principal(com.yahoo.athenz.auth.Principal) Certificate(java.security.cert.Certificate) Test(org.testng.annotations.Test)

Aggregations

SSLSession (javax.net.ssl.SSLSession)187 HostnameVerifier (javax.net.ssl.HostnameVerifier)50 SSLSocket (javax.net.ssl.SSLSocket)34 X509Certificate (java.security.cert.X509Certificate)32 IOException (java.io.IOException)31 SSLContext (javax.net.ssl.SSLContext)30 Test (org.junit.Test)29 CertificateException (java.security.cert.CertificateException)27 Certificate (java.security.cert.Certificate)20 SSLException (javax.net.ssl.SSLException)17 X509TrustManager (javax.net.ssl.X509TrustManager)16 URL (java.net.URL)14 HttpsURLConnection (javax.net.ssl.HttpsURLConnection)14 SSLPeerUnverifiedException (javax.net.ssl.SSLPeerUnverifiedException)14 TrustManager (javax.net.ssl.TrustManager)14 SecureRandom (java.security.SecureRandom)13 FakeSSLSession (okhttp3.FakeSSLSession)13 SSLSocketFactory (javax.net.ssl.SSLSocketFactory)12 InputStream (java.io.InputStream)11 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)11