Search in sources :

Example 56 with TrustManager

use of javax.net.ssl.TrustManager in project quorrabot by GloriousEggroll.

the class SingularityAPI method StartService.

public void StartService() {
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return new java.security.cert.X509Certificate[] {};
        }

        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }
    } };
    try {
        SSLContext mySSLContext = SSLContext.getInstance("TLS");
        mySSLContext.init(null, null, null);
        IO.Options opts = new IO.Options();
        opts.sslContext = mySSLContext;
        opts.hostnameVerifier = new NullHostnameVerifier();
        webSocket = IO.socket(apiURL);
        webSocket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {

            @Override
            public void call(Object... args) {
                //com.gmt2001.Console.out.println("GameWisp API: Connected to Singularity");
                webSocket.emit("authentication", new JSONObject().put("key", gwIdentifier).put("access_token", AccessToken));
            }
        });
        webSocket.on("unauthorized", new Emitter.Listener() {

            @Override
            public void call(Object... args) {
                JSONObject jsonObject = new JSONObject(args[0].toString());
                com.gmt2001.Console.err.println("GameWisp API: Authorization Failed: " + jsonObject.getString("message"));
                com.gmt2001.Console.err.println("Token: " + AccessToken + " Session ID: " + SessionID + " Client ID: " + gwIdentifier);
            }
        });
        webSocket.on("authenticated", new Emitter.Listener() {

            @Override
            public void call(Object... args) {
                //com.gmt2001.Console.out.println("GameWisp API: Authenticated");
                JSONObject jsonObject = new JSONObject(args[0].toString());
                if (!jsonObject.has("session")) {
                    com.gmt2001.Console.err.println("GameWisp API: Missing Session in Authenticated Return JSON");
                    Authenticated = false;
                    return;
                }
                SessionID = jsonObject.getString("session");
                Authenticated = true;
            }
        });
        webSocket.on("app-channel-connected", new Emitter.Listener() {

            @Override
            public void call(Object... args) {
                if (Authenticated) {
                    if (Quorrabot.enableDebugging) {
                        com.gmt2001.Console.out.println("GameWisp API: Connected to Channel");
                    } else {
                        com.gmt2001.Console.out.println("GameWisp API: Connected and Ready for Requests");
                    }
                    ChannelConnected = true;
                } else {
                    com.gmt2001.Console.out.println("GameWisp API: Connected to Channel; Missing Session ID; Unusable Session");
                    ChannelConnected = false;
                }
            }
        });
        webSocket.on("subscriber-new", new Emitter.Listener() {

            @Override
            public void call(Object... args) {
                com.gmt2001.Console.out.println("GameWisp API: subscriber-new received");
                JSONObject jsonObject = new JSONObject(args[0].toString());
                if (!jsonObject.has("data")) {
                    return;
                }
                if (!jsonObject.getJSONObject("data").has("usernames")) {
                    return;
                }
                if (!jsonObject.getJSONObject("data").getJSONObject("usernames").has("twitch")) {
                    return;
                }
                if (!jsonObject.getJSONObject("data").has("tier")) {
                    return;
                }
                if (!jsonObject.getJSONObject("data").getJSONObject("tier").has("level")) {
                    return;
                }
                String username = jsonObject.getJSONObject("data").getJSONObject("usernames").getString("twitch");
                int tier = jsonObject.getJSONObject("data").getJSONObject("tier").getInt("level");
                EventBus.instance().post(new GameWispSubscribeEvent(username, tier));
            }
        });
        webSocket.on("subscriber-anniversary", new Emitter.Listener() {

            @Override
            public void call(Object... args) {
                com.gmt2001.Console.out.println("GameWisp API: subscriber-anniversary received");
                JSONObject jsonObject = new JSONObject(args[0].toString());
                if (!jsonObject.has("data")) {
                    return;
                }
                if (!jsonObject.getJSONObject("data").has("subscriber")) {
                    return;
                }
                if (!jsonObject.getJSONObject("data").getJSONObject("subscriber").has("usernames")) {
                    return;
                }
                if (!jsonObject.getJSONObject("data").getJSONObject("subscriber").getJSONObject("usernames").has("twitch")) {
                    return;
                }
                if (!jsonObject.getJSONObject("data").has("month_count")) {
                    return;
                }
                String username = jsonObject.getJSONObject("data").getJSONObject("subscriber").getJSONObject("usernames").getString("twitch");
                int tier = jsonObject.getJSONObject("data").getJSONObject("subscriber").getJSONObject("tier").getInt("level");
                int months = jsonObject.getJSONObject("data").getInt("month_count");
                EventBus.instance().post(new GameWispAnniversaryEvent(username, months, tier));
            }
        });
        webSocket.on("subscriber-benefits-change", new Emitter.Listener() {

            @Override
            public void call(Object... args) {
                com.gmt2001.Console.out.println("GameWisp API: subscriber-benefits-change received");
                JSONObject jsonObject = new JSONObject(args[0].toString());
                if (!jsonObject.has("data")) {
                    return;
                }
                if (!jsonObject.getJSONObject("data").has("usernames")) {
                    return;
                }
                if (!jsonObject.getJSONObject("data").getJSONObject("usernames").has("twitch")) {
                    return;
                }
                if (!jsonObject.has("tier")) {
                    return;
                }
                if (!jsonObject.getJSONObject("tier").has("level")) {
                    return;
                }
                String username = jsonObject.getJSONObject("data").getJSONObject("usernames").getString("twitch");
                int tier = jsonObject.getJSONObject("tier").getInt("level");
                EventBus.instance().post(new GameWispBenefitsEvent(username, tier));
            }
        });
        /**
             * Status Change Values:
             * https://gamewisp.readme.io/docs/subscriber-new active - a
             * currently active subscriber trial - a subscriber on a trial code
             * grace_period - a canceled subscriber that is still received
             * benefits billing_grace_period - a canceled subscriber still
             * receiving benefits that was canceled due to a payment processing
             * error inactive - a subscriber that is canceled and receiving no
             * benefits twitch - a subscriber that is receiving free benefits
             * from a partnered Twitch streamer.
             */
        webSocket.on("subscriber-status-change", new Emitter.Listener() {

            @Override
            public void call(Object... args) {
                com.gmt2001.Console.out.println("GameWisp API: subscriber-status-changed received");
                JSONObject jsonObject = new JSONObject(args[0].toString());
                if (!jsonObject.has("data")) {
                    return;
                }
                if (!jsonObject.getJSONObject("data").has("usernames")) {
                    return;
                }
                if (!jsonObject.getJSONObject("data").getJSONObject("usernames").has("twitch")) {
                    return;
                }
                if (!jsonObject.getJSONObject("data").has("status")) {
                    return;
                }
                String username = jsonObject.getJSONObject("data").getJSONObject("usernames").getString("twitch");
                String status = jsonObject.getJSONObject("data").getString("status");
                EventBus.instance().post(new GameWispChangeEvent(username, status));
            }
        });
        webSocket.on(Socket.EVENT_DISCONNECT, new Emitter.Listener() {

            @Override
            public void call(Object... args) {
                com.gmt2001.Console.out.println("GameWisp API: Disconnected");
            }
        });
        webSocket.connect();
    } catch (Exception ex) {
        com.gmt2001.Console.err.println("GameWisp API: Exception: " + ex.getMessage());
    }
}
Also used : Options(io.socket.client.IO.Options) Emitter(io.socket.emitter.Emitter) GameWispSubscribeEvent(me.gloriouseggroll.quorrabot.event.gamewisp.GameWispSubscribeEvent) IO(io.socket.client.IO) GameWispChangeEvent(me.gloriouseggroll.quorrabot.event.gamewisp.GameWispChangeEvent) SSLContext(javax.net.ssl.SSLContext) X509Certificate(java.security.cert.X509Certificate) URISyntaxException(java.net.URISyntaxException) JSONException(org.json.JSONException) IOException(java.io.IOException) KeyManagementException(java.security.KeyManagementException) CertificateException(java.security.cert.CertificateException) IllegalArgumentException(java.lang.IllegalArgumentException) InterruptedException(java.lang.InterruptedException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) TrustManager(javax.net.ssl.TrustManager) X509TrustManager(javax.net.ssl.X509TrustManager) Options(io.socket.client.IO.Options) GameWispBenefitsEvent(me.gloriouseggroll.quorrabot.event.gamewisp.GameWispBenefitsEvent) JSONObject(org.json.JSONObject) GameWispAnniversaryEvent(me.gloriouseggroll.quorrabot.event.gamewisp.GameWispAnniversaryEvent) X509TrustManager(javax.net.ssl.X509TrustManager) JSONObject(org.json.JSONObject)

Example 57 with TrustManager

use of javax.net.ssl.TrustManager in project zm-mailbox by Zimbra.

the class SSLUtil method getDummySSLContext.

/**
     * Returns an SSLContext that can be used to create SSL connections without
     * certificates. This is obviously insecure and should only be used for
     * testing.
     *
     * @return an SSLContext that trusts all certificates
     */
public static SSLContext getDummySSLContext() {
    TrustManager tm = new X509TrustManager() {

        public void checkClientTrusted(X509Certificate[] cert, String authType) {
        // trust all certs
        }

        public void checkServerTrusted(X509Certificate[] cert, String authType) {
        // trust all certs
        }

        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    };
    try {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, new TrustManager[] { tm }, null);
        return sc;
    } catch (Exception e) {
        throw new IllegalStateException("Could not create SSL context", e);
    }
}
Also used : X509TrustManager(javax.net.ssl.X509TrustManager) SSLContext(javax.net.ssl.SSLContext) X509Certificate(java.security.cert.X509Certificate) X509TrustManager(javax.net.ssl.X509TrustManager) TrustManager(javax.net.ssl.TrustManager)

Example 58 with TrustManager

use of javax.net.ssl.TrustManager in project maven-plugins by apache.

the class ProjectInfoReportUtils method getURLConnection.

/**
     * @param url not null
     * @param project not null
     * @param settings not null
     * @return the url connection with auth if required. Don't check the certificate if SSL scheme.
     * @throws IOException if any
     */
private static URLConnection getURLConnection(URL url, MavenProject project, Settings settings) throws IOException {
    URLConnection conn = url.openConnection();
    conn.setConnectTimeout(TIMEOUT);
    conn.setReadTimeout(TIMEOUT);
    //@formatter:off
    if (settings.getServers() != null && !settings.getServers().isEmpty() && project != null && project.getDistributionManagement() != null && (project.getDistributionManagement().getRepository() != null || project.getDistributionManagement().getSnapshotRepository() != null) && (StringUtils.isNotEmpty(project.getDistributionManagement().getRepository().getUrl()) || StringUtils.isNotEmpty(project.getDistributionManagement().getSnapshotRepository().getUrl()))) //@formatter:on
    {
        Server server = null;
        if (url.toString().contains(project.getDistributionManagement().getRepository().getUrl())) {
            server = settings.getServer(project.getDistributionManagement().getRepository().getId());
        }
        if (server == null && url.toString().contains(project.getDistributionManagement().getSnapshotRepository().getUrl())) {
            server = settings.getServer(project.getDistributionManagement().getSnapshotRepository().getId());
        }
        if (server != null && StringUtils.isNotEmpty(server.getUsername()) && StringUtils.isNotEmpty(server.getPassword())) {
            String up = server.getUsername().trim() + ":" + server.getPassword().trim();
            String upEncoded = new String(Base64.encodeBase64Chunked(up.getBytes())).trim();
            conn.setRequestProperty("Authorization", "Basic " + upEncoded);
        }
    }
    if (conn instanceof HttpsURLConnection) {
        HostnameVerifier hostnameverifier = new HostnameVerifier() {

            /** {@inheritDoc} */
            public boolean verify(String urlHostName, SSLSession session) {
                return true;
            }
        };
        ((HttpsURLConnection) conn).setHostnameVerifier(hostnameverifier);
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

            /** {@inheritDoc} */
            public void checkClientTrusted(final X509Certificate[] chain, final String authType) {
            }

            /** {@inheritDoc} */
            public void checkServerTrusted(final X509Certificate[] chain, final String authType) {
            }

            /** {@inheritDoc} */
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        } };
        try {
            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustAllCerts, new SecureRandom());
            SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
            ((HttpsURLConnection) conn).setSSLSocketFactory(sslSocketFactory);
        } catch (NoSuchAlgorithmException e1) {
        // ignore
        } catch (KeyManagementException e) {
        // ignore
        }
    }
    return conn;
}
Also used : Server(org.apache.maven.settings.Server) SSLSession(javax.net.ssl.SSLSession) SecureRandom(java.security.SecureRandom) SSLContext(javax.net.ssl.SSLContext) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) URLConnection(java.net.URLConnection) HttpsURLConnection(javax.net.ssl.HttpsURLConnection) X509Certificate(java.security.cert.X509Certificate) KeyManagementException(java.security.KeyManagementException) HostnameVerifier(javax.net.ssl.HostnameVerifier) TrustManager(javax.net.ssl.TrustManager) X509TrustManager(javax.net.ssl.X509TrustManager) X509TrustManager(javax.net.ssl.X509TrustManager) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) HttpsURLConnection(javax.net.ssl.HttpsURLConnection)

Example 59 with TrustManager

use of javax.net.ssl.TrustManager in project wildfly by wildfly.

the class ElytronIntegrationResourceDefinitions method getElytronTrustManagersResourceDefinition.

/**
     * Defines a resource that represents Elytron-compatible trust managers that can be exported by a JSSE-enabled domain
     * in the legacy security subsystem.
     *
     * To export the trust managers the resource uses a {@code BasicAddHandler} implementation that registers the elytron
     * trust-managers capability and implements a {@code org.jboss.as.security.elytron.BasicService.ValueSupplier} that uses
     * the injected {@code SecurityDomainContext} to obtain a {@code JSSESecurityDomain}. If such domain is found, its
     * configured trust manager array is obtained and returned.
     *
     * The {@code ValueSupplier} implementation throws an exception if the referenced legacy domain is not a JSSE-enabled
     * domain or if the domain doesn't contain a trust store configuration that can be used to build the trust managers.
     *
     * NOTE: The {@code PicketBox} implementation of a {@code JSSESecurityDomain} returns a reference to the key store if
     * a trust store was not configured. This means that the trust managers that it builds will use the configured key store
     * instead of throwing an exception to alert about a missing trust store configuration. So extra care must be taken
     * to ensure that the exported trust managers are being built using the correct trust stores.
     */
public static ResourceDefinition getElytronTrustManagersResourceDefinition() {
    final AttributeDefinition[] attributes = new AttributeDefinition[] { LEGACY_JSSE_CONFIG };
    final AbstractAddStepHandler addHandler = new BasicAddHandler<TrustManager[]>(attributes, TRUST_MANAGERS_RUNTIME_CAPABILITY) {

        @Override
        protected BasicService.ValueSupplier<TrustManager[]> getValueSupplier(ServiceBuilder<TrustManager[]> serviceBuilder, OperationContext context, ModelNode model) throws OperationFailedException {
            final String legacyJSSEConfig = asStringIfDefined(context, LEGACY_JSSE_CONFIG, model);
            final InjectedValue<SecurityDomainContext> securityDomainContextInjector = new InjectedValue<>();
            if (legacyJSSEConfig != null) {
                serviceBuilder.addDependency(SecurityDomainService.SERVICE_NAME.append(legacyJSSEConfig), SecurityDomainContext.class, securityDomainContextInjector);
            }
            return () -> {
                final SecurityDomainContext domainContext = securityDomainContextInjector.getValue();
                final JSSESecurityDomain jsseDomain = domainContext.getJSSE();
                if (jsseDomain == null) {
                    throw SecurityLogger.ROOT_LOGGER.unableToLocateJSSEConfig(legacyJSSEConfig);
                }
                final TrustManager[] trustManagers = jsseDomain.getTrustManagers();
                if (trustManagers == null) {
                    throw SecurityLogger.ROOT_LOGGER.unableToLocateComponentInJSSEDomain("trust manager", legacyJSSEConfig);
                }
                return trustManagers;
            };
        }
    };
    return new BasicResourceDefinition(Constants.ELYTRON_TRUST_MANAGER, addHandler, attributes, TRUST_MANAGERS_RUNTIME_CAPABILITY);
}
Also used : OperationContext(org.jboss.as.controller.OperationContext) InjectedValue(org.jboss.msc.value.InjectedValue) JSSESecurityDomain(org.jboss.security.JSSESecurityDomain) AttributeDefinition(org.jboss.as.controller.AttributeDefinition) SimpleAttributeDefinition(org.jboss.as.controller.SimpleAttributeDefinition) SecurityDomainContext(org.jboss.as.security.plugins.SecurityDomainContext) TrustManager(javax.net.ssl.TrustManager) ServiceBuilder(org.jboss.msc.service.ServiceBuilder) AbstractAddStepHandler(org.jboss.as.controller.AbstractAddStepHandler) ModelNode(org.jboss.dmr.ModelNode)

Example 60 with TrustManager

use of javax.net.ssl.TrustManager in project robovm by robovm.

the class MySslContext method test_init$Ljavax_net_ssl_KeyManager$Ljavax_net_ssl_TrustManagerLjava_security_SecureRandom.

/**
      * @throws NoSuchAlgorithmException
     * @throws KeyStoreException
     * @throws FileNotFoundException
     * @throws KeyManagementException
     * javax.net.ssl.SSLContext#
      *     init(javax.net.ssl.KeyManager[], javax.net.ssl.TrustManager[],
      *     java.security.SecureRandom)
      */
public void test_init$Ljavax_net_ssl_KeyManager$Ljavax_net_ssl_TrustManagerLjava_security_SecureRandom() throws Exception {
    if (!DEFSupported)
        fail(NotSupportMsg);
    SSLContextSpi spi = new MySSLContextSpi();
    SSLContext sslContext = new MySslContext(spi, defaultProvider, defaultProtocol);
    try {
        sslContext.createSSLEngine();
        fail("Expected RuntimeException was not thrown");
    } catch (RuntimeException rte) {
    // expected
    }
    try {
        sslContext.init(null, null, null);
        fail("KeyManagementException wasn't thrown");
    } catch (KeyManagementException kme) {
    //expected
    }
    try {
        String tAlg = TrustManagerFactory.getDefaultAlgorithm();
        String kAlg = KeyManagerFactory.getDefaultAlgorithm();
        if (tAlg == null)
            fail("TrustManagerFactory default algorithm is not defined");
        if (kAlg == null)
            fail("KeyManagerFactory default algorithm is not defined");
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(kAlg);
        kmf.init(null, new char[11]);
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(tAlg);
        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        tmf.init(ks);
        TrustManager[] tms = tmf.getTrustManagers();
        sslContext.init(kmf.getKeyManagers(), tms, new SecureRandom());
    } catch (Exception e) {
        System.out.println("EE = " + e);
    }
}
Also used : SecureRandom(java.security.SecureRandom) SSLContext(javax.net.ssl.SSLContext) KeyStore(java.security.KeyStore) KeyManagementException(java.security.KeyManagementException) KeyManagementException(java.security.KeyManagementException) KeyStoreException(java.security.KeyStoreException) FileNotFoundException(java.io.FileNotFoundException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) NoSuchProviderException(java.security.NoSuchProviderException) KeyManagerFactory(javax.net.ssl.KeyManagerFactory) TrustManager(javax.net.ssl.TrustManager) MySSLContextSpi(org.apache.harmony.xnet.tests.support.MySSLContextSpi) MySSLContextSpi(org.apache.harmony.xnet.tests.support.MySSLContextSpi) SSLContextSpi(javax.net.ssl.SSLContextSpi) TrustManagerFactory(javax.net.ssl.TrustManagerFactory)

Aggregations

TrustManager (javax.net.ssl.TrustManager)229 SSLContext (javax.net.ssl.SSLContext)139 X509TrustManager (javax.net.ssl.X509TrustManager)139 TrustManagerFactory (javax.net.ssl.TrustManagerFactory)90 X509Certificate (java.security.cert.X509Certificate)70 IOException (java.io.IOException)60 KeyStore (java.security.KeyStore)60 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)60 SecureRandom (java.security.SecureRandom)58 KeyManagementException (java.security.KeyManagementException)54 KeyManager (javax.net.ssl.KeyManager)52 CertificateException (java.security.cert.CertificateException)43 KeyStoreException (java.security.KeyStoreException)37 KeyManagerFactory (javax.net.ssl.KeyManagerFactory)34 HostnameVerifier (javax.net.ssl.HostnameVerifier)23 URL (java.net.URL)22 GeneralSecurityException (java.security.GeneralSecurityException)22 SSLSocketFactory (javax.net.ssl.SSLSocketFactory)20 InputStream (java.io.InputStream)18 FileInputStream (java.io.FileInputStream)16