Creates {@link TrustManager} instances based on the javax.net.ssl.trustStore
and javax.net.ssl.trustStorePassword environment variables.

@return an array of {@link TrustManager} instances
@throws InitializationException
324940
public static TrustManager[] getTrustManagers() throws InitializationException {
		String file = System.getProperty("javax.net.ssl.trustStore");
		String pass = System.getProperty("javax.net.ssl.trustStorePassword");

		if (file == null || pass == null) {
			throw new InitializationException("javax.net.ssl.trustStore / "
					+ "javax.net.ssl.trustStorePassword not set");
		}

		return getTrustManagers(file, pass);
	}
772850
protected SSLServerSocketFactory createFactory() 
    	throws Exception
    {
        SSLContext context;
        if (_provider == null) {
			context = SSLContext.getInstance(_protocol);
		} else {
			context = SSLContext.getInstance(_protocol, _provider);
		}

        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(_algorithm);        
        KeyStore keyStore = KeyStore.getInstance(_keystoreType);
        keyStore.load(Resource.newResource(_keystore).getInputStream(), _password.toString().toCharArray());
        keyManagerFactory.init(keyStore,_keypassword.toString().toCharArray());
        
        context.init(keyManagerFactory.getKeyManagers(), null, new java.security.SecureRandom());

        return context.getServerSocketFactory();
    }
951654
private SSLSocketFactory defaultSslSocketFactory(X509TrustManager trustManager)
      throws NoSuchAlgorithmException, KeyManagementException {
    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(null, new TrustManager[] { trustManager }, null);

    return sslContext.getSocketFactory();
  }
881252
private HttpHandler setupSecurityHandlers(HttpHandler initialHandler) {
        final DeploymentInfo deploymentInfo = deployment.getDeploymentInfo();
        final LoginConfig loginConfig = deploymentInfo.getLoginConfig();

        HttpHandler current = initialHandler;
        current = new SSLInformationAssociationHandler(current);

        final SecurityPathMatches securityPathMatches = buildSecurityConstraints();
        securityPathMatches.logWarningsAboutUncoveredMethods();
        current = new ServletAuthenticationCallHandler(current);

        for(HandlerWrapper wrapper : deploymentInfo.getSecurityWrappers()) {
            current = wrapper.wrap(current);
        }

        if(deploymentInfo.isDisableCachingForSecuredPages()) {
            current = Handlers.predicate(Predicates.authRequired(), Handlers.disableCache(current), current);
        }
        if (!securityPathMatches.isEmpty()) {
            current = new ServletAuthenticationConstraintHandler(current);
        }
        current = new ServletConfidentialityConstraintHandler(deploymentInfo.getConfidentialPortManager(), current);
        if (!securityPathMatches.isEmpty()) {
            current = new ServletSecurityConstraintHandler(securityPathMatches, current);
        }

        HandlerWrapper initialSecurityWrapper = deploymentInfo.getInitialSecurityWrapper();

        String mechName = null;
        if (initialSecurityWrapper == null) {
            final Map<String, AuthenticationMechanismFactory> factoryMap = new HashMap<>(deploymentInfo.getAuthenticationMechanisms());
            final IdentityManager identityManager = deploymentInfo.getIdentityManager();
            if(!factoryMap.containsKey(BASIC_AUTH)) {
                factoryMap.put(BASIC_AUTH, BasicAuthenticationMechanism.FACTORY);
            }
            if(!factoryMap.containsKey(FORM_AUTH)) {
                factoryMap.put(FORM_AUTH, ServletFormAuthenticationMechanism.FACTORY);
            }
            if(!factoryMap.containsKey(DIGEST_AUTH)) {
                factoryMap.put(DIGEST_AUTH, DigestAuthenticationMechanism.FACTORY);
            }
            if(!factoryMap.containsKey(CLIENT_CERT_AUTH)) {
                factoryMap.put(CLIENT_CERT_AUTH, ClientCertAuthenticationMechanism.FACTORY);
            }
            if(!factoryMap.containsKey(ExternalAuthenticationMechanism.NAME)) {
                factoryMap.put(ExternalAuthenticationMechanism.NAME, ExternalAuthenticationMechanism.FACTORY);
            }
            if(!factoryMap.containsKey(GenericHeaderAuthenticationMechanism.NAME)) {
                factoryMap.put(GenericHeaderAuthenticationMechanism.NAME, GenericHeaderAuthenticationMechanism.FACTORY);
            }
            List<AuthenticationMechanism> authenticationMechanisms = new LinkedList<>();

            if(deploymentInfo.isUseCachedAuthenticationMechanism()) {
                authenticationMechanisms.add(new CachedAuthenticatedSessionMechanism(identityManager));
            }
            if (loginConfig != null || deploymentInfo.getJaspiAuthenticationMechanism() != null) {

                //we don't allow multipart requests, and use the default encoding when it's set
                FormEncodedDataDefinition formEncodedDataDefinition = new FormEncodedDataDefinition();
                String reqEncoding = deploymentInfo.getDefaultRequestEncoding();
                if(reqEncoding == null) {
                    reqEncoding = deploymentInfo.getDefaultEncoding();
                }
                if (reqEncoding != null) {
                    formEncodedDataDefinition.setDefaultEncoding(reqEncoding);
                }
                FormParserFactory parser = FormParserFactory.builder(false)
                        .addParser(formEncodedDataDefinition)
                        .build();

                List<AuthMethodConfig> authMethods = Collections.<AuthMethodConfig>emptyList();
                if(loginConfig != null) {
                    authMethods = loginConfig.getAuthMethods();
                }

                for(AuthMethodConfig method : authMethods) {
                    AuthenticationMechanismFactory factory = factoryMap.get(method.getName());
                    if(factory == null) {
                        throw UndertowServletMessages.MESSAGES.unknownAuthenticationMechanism(method.getName());
                    }
                    if(mechName == null) {
                        mechName = method.getName();
                    }

                    final Map<String, String> properties = new HashMap<>();
                    properties.put(AuthenticationMechanismFactory.CONTEXT_PATH, deploymentInfo.getContextPath());
                    properties.put(AuthenticationMechanismFactory.REALM, loginConfig.getRealmName());
                    properties.put(AuthenticationMechanismFactory.ERROR_PAGE, loginConfig.getErrorPage());
                    properties.put(AuthenticationMechanismFactory.LOGIN_PAGE, loginConfig.getLoginPage());
                    properties.putAll(method.getProperties());

                    String name = method.getName().toUpperCase(Locale.US);
                    // The mechanism name is passed in from the HttpServletRequest interface as the name reported needs to be
                    // comparable using '=='
                    name = name.equals(FORM_AUTH) ? FORM_AUTH : name;
                    name = name.equals(BASIC_AUTH) ? BASIC_AUTH : name;
                    name = name.equals(DIGEST_AUTH) ? DIGEST_AUTH : name;
                    name = name.equals(CLIENT_CERT_AUTH) ? CLIENT_CERT_AUTH : name;

                    authenticationMechanisms.add(factory.create(name, identityManager, parser, properties));
                }
            }


            deployment.setAuthenticationMechanisms(authenticationMechanisms);
            //if the JASPI auth mechanism is set then it takes over
            if(deploymentInfo.getJaspiAuthenticationMechanism() == null) {
                current = new AuthenticationMechanismsHandler(current, authenticationMechanisms);
            } else {
                current = new AuthenticationMechanismsHandler(current, Collections.<AuthenticationMechanism>singletonList(deploymentInfo.getJaspiAuthenticationMechanism()));
            }

            current = new CachedAuthenticatedSessionHandler(current, this.deployment.getServletContext());
        }

        List<NotificationReceiver> notificationReceivers = deploymentInfo.getNotificationReceivers();
        if (!notificationReceivers.isEmpty()) {
            current = new NotificationReceiverHandler(current, notificationReceivers);
        }

        if (initialSecurityWrapper == null) {
            // TODO - A switch to constraint driven could be configurable, however before we can support that with servlets we would
            // need additional tracking within sessions if a servlet has specifically requested that authentication occurs.
            SecurityContextFactory contextFactory = deploymentInfo.getSecurityContextFactory();
            if (contextFactory == null) {
                contextFactory = SecurityContextFactoryImpl.INSTANCE;
            }
            current = new SecurityInitialHandler(deploymentInfo.getAuthenticationMode(), deploymentInfo.getIdentityManager(), mechName,
                    contextFactory, current);
        } else {
            current = initialSecurityWrapper.wrap(current);
        }

        return current;
    }
206910
public static TrustManagerFactory getTrustManagerFactory(String trustStoreFilename, StoreProperties storeProperties)
      throws IOException, GeneralSecurityException {
    InputStream is = getResourceAsStream(trustStoreFilename);
    if (is == null) {
      throw new FileNotFoundException("Certificate file not found: " + getFilenameInfo(trustStoreFilename));
    }
    try {
      return getTrustManagerFactory(is, storeProperties);
    }
    finally {
      try {
        is.close();
      }
      catch (IOException ex) {
        // ignore
      }
    }
  }
1056429
public static JMDictSense create() {
		if (index >= instances.size()) {
			instances.add(new JMDictSense());
		}
		return instances.get(index++);
	}
75770
private boolean setupIgnoreCertificateErrors() {

        // Create a TrustManager that trusts all certificates
        TrustManager[] trustAllCerts = new TrustManager[] { new X509ExtendedTrustManager() {
            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            @Override
            public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }

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

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

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

            @Override
            public void checkServerTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] chain, String authType, SSLEngine engine) throws CertificateException {
            }
        }};

        // Ignore differences between given hostname and certificate hostname
        HostnameVerifier hostnameVerifier = new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };

        try {
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, trustAllCerts, new SecureRandom());
            openSslContext = sslContext;
            openHostnameVerifier = hostnameVerifier;
        } catch (GeneralSecurityException ex) {
            openSslContext = null;
            openHostnameVerifier = null;
            return (false);
        }

        return (true);
    }
1192133
private List<JawrConfigManagerMBean> getInitializedConfigurationManagers() {

		final List<JawrConfigManagerMBean> mBeans = new ArrayList<>();
		if (jsMBean != null) {
			mBeans.add(jsMBean);
		}

		if (cssMBean != null) {
			mBeans.add(cssMBean);
		}
		if (binaryMBean != null) {
			mBeans.add(binaryMBean);
		}

		return mBeans;
	}
650189
public static void configureTls(ServerBuilder sb, Ssl ssl,
                                    @Nullable Supplier<KeyStore> keyStoreSupplier,
                                    @Nullable Supplier<KeyStore> trustStoreSupplier) {
        if (!ssl.isEnabled()) {
            return;
        }
        try {
            if (keyStoreSupplier == null && trustStoreSupplier == null &&
                ssl.getKeyStore() == null && ssl.getTrustStore() == null) {
                logger.warn("Configuring TLS with a self-signed certificate " +
                            "because no key or trust store was specified");
                sb.tlsSelfSigned();
                return;
            }

            final KeyManagerFactory keyManagerFactory = getKeyManagerFactory(ssl, keyStoreSupplier);
            final TrustManagerFactory trustManagerFactory = getTrustManagerFactory(ssl, trustStoreSupplier);

            sb.tls(keyManagerFactory, sslContextBuilder -> {
                sslContextBuilder.trustManager(trustManagerFactory);

                final SslProvider sslProvider = ssl.getProvider();
                if (sslProvider != null) {
                    sslContextBuilder.sslProvider(sslProvider);
                }
                final List<String> enabledProtocols = ssl.getEnabledProtocols();
                if (enabledProtocols != null) {
                    sslContextBuilder.protocols(enabledProtocols.toArray(new String[enabledProtocols.size()]));
                }
                final List<String> ciphers = ssl.getCiphers();
                if (ciphers != null) {
                    sslContextBuilder.ciphers(ImmutableList.copyOf(ciphers),
                                              SupportedCipherSuiteFilter.INSTANCE);
                }
                final ClientAuth clientAuth = ssl.getClientAuth();
                if (clientAuth != null) {
                    sslContextBuilder.clientAuth(clientAuth);
                }
            });
        } catch (Exception e) {
            throw new IllegalStateException("Failed to configure TLS: " + e, e);
        }
    }
1069830
private SSLSocketFactory buildSslSocketFactory() {
        try {
            KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            keyStore.load(null, null);
            keyStore.setCertificateEntry("ca", generateCertificate());

            TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            tmf.init(keyStore);

            SSLContext context = SSLContext.getInstance("TLSv1.2");
            context.init(null, tmf.getTrustManagers(), null);
            return context.getSocketFactory();

        } catch (Exception e) {
            throw new KubernetesClientException("Failure in generating SSLSocketFactory", e);
        }
    }
238740
@Override
    public void initialize(String keyStoreName, String keyStorePath, String keyStoreType, String keyStoreProvider,
                           String keyStorePassword, String keyAlias) throws AuditSigningException {

        WsLocationAdmin locationAdmin = locationAdminRef.getService();
        if (locationAdmin != null) {
            serverName = locationAdmin.getServerName();
        }
        signerAlias = keyAlias;
        signerName = keyStoreName;
        signerKeyFileLocation = keyStorePath;

        crypto = new AuditCrypto();

        String JCEProvider = null;

        try {
            signature = Signature.getInstance(CRYPTO_ALGORITHM);

        } catch (Exception e) {
            Tr.error(tc, "security.audit.signing.init.error", new Object[] { e });
            throw new AuditSigningException(e.getMessage());
        }

        long begin_time = 0;
        if (tc.isDebugEnabled()) {
            Tr.debug(tc, "Initializing audit signer at " + new java.util.Date(System.currentTimeMillis()));
        }

    }
670569
public static ConfigurationManager getInstance()
		throws ConfigurationException
	{

		if (instance == null) {
			throw ErrorFactory
					.createConfigurationException(ErrorKeys.CONFIGURATION_CONFIGURATIONMANAGER_NOT_INITIALIZED);
		}
		return instance;
	}
619583
public SSLConnectionSocketFactory prepareClientSSL() {
        try {
        	String path = Config.getProperty(Config.PROXY_KEYSTORE_PATH);
			String pass = Config.getProperty(Config.PROXY_KEYSTORE_PASSWORD);
			KeyStore trustStore = null;
			if (path != null && pass != null) {

				trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
				FileInputStream	instream = new FileInputStream(new File(path));
				try {
		            trustStore.load(instream, pass.toCharArray());
		        } finally {
		            instream.close();
		        }
			}
			SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();
	        String tlsVersion = Config.getProperty(Config.TLS_VERSION);
	        SSLConnectionSocketFactory sslConnectionFactory = new SSLConnectionSocketFactory(sslContext, new String[]{tlsVersion}, null, new NoopHostnameVerifier());
            return sslConnectionFactory;
        } catch (Exception ex) {
            LOG.error("couldn't create httpClient!! {}", ex.getMessage(), ex);
            return null;
        }
    }
1077680
private SSLSocketFactory createFactory()
    throws Exception
  {
    SSLSocketFactory ssFactory = null;
    
    String host = "localhost";
    int port = 8086;
    
    if (_keyStore == null) {
      return createAnonymousFactory(null, port);
    }
    
    SSLContext sslContext = SSLContext.getInstance(_sslContext);

    KeyManagerFactory kmf
    = KeyManagerFactory.getInstance(keyManagerFactory());

    kmf.init(_keyStore, keyStorePassword().toCharArray());

    sslContext.init(kmf.getKeyManagers(), null, null);

    /*
      if (_cipherSuites != null)
        sslContext.createSSLEngine().setEnabledCipherSuites(_cipherSuites);

     */
    SSLEngine engine = sslContext.createSSLEngine();
    
    _enabledProtocols = enabledProtocols(engine.getEnabledProtocols());
    
    engine.setEnabledProtocols(_enabledProtocols);

    ssFactory = sslContext.getSocketFactory();
    
    return ssFactory;
  }
970252
public SSLSocketFactory build() throws NoSuchAlgorithmException, KeyManagementException{
		SSLContext sslContext = SSLContext.getInstance(protocol);
		sslContext.init(this.keyManagers, this.trustManagers, this.secureRandom);
		return sslContext.getSocketFactory();
	}
282283
public static Authenticator buildAuthenticatorWithTruststore(final String keystorePath,
            final char[] keystorePassword, final List<String> keyids) {
        if (keystorePath != null) {
            final File file = new File(keystorePath);
            if (file.exists()) {
                try (final FileInputStream fis = new FileInputStream(file)) {
                    final KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
                    ks.load(fis, keystorePassword);
                    final List<String> keyIds = filterKeyIds(ks, keyids);
                    switch (keyIds.size()) {
                        case 0:
                            LOGGER.warn("No valid key ids provided! Skipping keystore: {}", keystorePath);
                            return null;
                        case 1:
                            return new JwtAuthenticator(ks.getCertificate(keyIds.get(0)).getPublicKey());
                        default:
                            return new FederatedJwtAuthenticator(ks, keyIds);
                    }
                } catch (final IOException | CertificateException | NoSuchAlgorithmException | KeyStoreException ex) {
                    LOGGER.error("Error reading keystore: {}", ex.getMessage());
                    LOGGER.warn("Ignoring JWT authenticator with keystore: {}", keystorePath);
                }
            }
        }
        return null;
    }
268394
public SSLContext createSSLContextFromKeystores(boolean isServer) {
        String protocol = sslConfig.getSSLProtocol();
        try {
            KeyManager[] keyManagers = null;
            if (sslConfig.getKeyStore() != null) {
                KeyStore ks = getKeyStore(sslConfig.getKeyStore(), sslConfig.getKeyStorePass());
                // Set up key manager factory to use our key store
                kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
                if (ks != null) {
                    kmf.init(ks, sslConfig.getCertPass() != null ?
                            sslConfig.getCertPass().toCharArray() :
                            sslConfig.getKeyStorePass().toCharArray());
                    keyManagers = kmf.getKeyManagers();
                }
            }
            TrustManager[] trustManagers = null;
            if (sslConfig.getTrustStore() != null) {
                KeyStore tks = getKeyStore(sslConfig.getTrustStore(), sslConfig.getTrustStorePass());
                tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
                tmf.init(tks);
                trustManagers = tmf.getTrustManagers();
            }
            sslContext = SSLContext.getInstance(protocol);
            sslContext.init(keyManagers, trustManagers, null);
            int sessionTimeout = sslConfig.getSessionTimeOut();
            if (isServer) {
                if (sessionTimeout > 0) {
                    sslContext.getServerSessionContext().setSessionTimeout(sessionTimeout);
                }
            } else {
                if (sessionTimeout > 0) {
                    sslContext.getClientSessionContext().setSessionTimeout(sessionTimeout);
                }
            }
            return sslContext;

        } catch (UnrecoverableKeyException | KeyManagementException |
                NoSuchAlgorithmException | KeyStoreException | IOException e) {
            throw new IllegalArgumentException("Failed to initialize the SSLContext", e);
        }
    }