List of usage examples for javax.net.ssl KeyManagerFactory init
public final void init(KeyStore ks, char[] password) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException
From source file:io.atomix.cluster.messaging.impl.NettyMessagingService.java
private boolean loadKeyStores() { // Maintain a local copy of the trust and key managers in case anything goes wrong TrustManagerFactory tmf;// w w w . ja v a 2 s. c o m KeyManagerFactory kmf; try { String ksLocation = System.getProperty("javax.net.ssl.keyStore", DEFAULT_KS_FILE.toString()); String tsLocation = System.getProperty("javax.net.ssl.trustStore", DEFAULT_KS_FILE.toString()); char[] ksPwd = System.getProperty("javax.net.ssl.keyStorePassword", DEFAULT_KS_PASSWORD).toCharArray(); char[] tsPwd = System.getProperty("javax.net.ssl.trustStorePassword", DEFAULT_KS_PASSWORD) .toCharArray(); tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); KeyStore ts = KeyStore.getInstance(KeyStore.getDefaultType()); try (FileInputStream fileInputStream = new FileInputStream(tsLocation)) { ts.load(fileInputStream, tsPwd); } tmf.init(ts); kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); try (FileInputStream fileInputStream = new FileInputStream(ksLocation)) { ks.load(fileInputStream, ksPwd); } kmf.init(ks, ksPwd); if (log.isInfoEnabled()) { logKeyStore(ks, ksLocation, ksPwd); } } catch (FileNotFoundException e) { log.warn("Disabling TLS for intra-cluster messaging; Could not load cluster key store: {}", e.getMessage()); return TLS_DISABLED; } catch (Exception e) { //TODO we might want to catch exceptions more specifically log.error("Error loading key store; disabling TLS for intra-cluster messaging", e); return TLS_DISABLED; } this.trustManager = tmf; this.keyManager = kmf; return TLS_ENABLED; }
From source file:org.apache.hive.jdbc.HiveConnection.java
SSLConnectionSocketFactory getTwoWaySSLSocketFactory() throws SQLException { SSLConnectionSocketFactory socketFactory = null; try {//www . j a v a 2 s .com KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance( JdbcConnectionParams.SUNX509_ALGORITHM_STRING, JdbcConnectionParams.SUNJSSE_ALGORITHM_STRING); String keyStorePath = sessConfMap.get(JdbcConnectionParams.SSL_KEY_STORE); String keyStorePassword = sessConfMap.get(JdbcConnectionParams.SSL_KEY_STORE_PASSWORD); KeyStore sslKeyStore = KeyStore.getInstance(JdbcConnectionParams.SSL_KEY_STORE_TYPE); if (keyStorePath == null || keyStorePath.isEmpty()) { throw new IllegalArgumentException(JdbcConnectionParams.SSL_KEY_STORE + " Not configured for 2 way SSL connection, keyStorePath param is empty"); } try (FileInputStream fis = new FileInputStream(keyStorePath)) { sslKeyStore.load(fis, keyStorePassword.toCharArray()); } keyManagerFactory.init(sslKeyStore, keyStorePassword.toCharArray()); TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(JdbcConnectionParams.SUNX509_ALGORITHM_STRING); String trustStorePath = sessConfMap.get(JdbcConnectionParams.SSL_TRUST_STORE); String trustStorePassword = sessConfMap.get(JdbcConnectionParams.SSL_TRUST_STORE_PASSWORD); KeyStore sslTrustStore = KeyStore.getInstance(JdbcConnectionParams.SSL_TRUST_STORE_TYPE); if (trustStorePath == null || trustStorePath.isEmpty()) { throw new IllegalArgumentException( JdbcConnectionParams.SSL_TRUST_STORE + " Not configured for 2 way SSL connection"); } try (FileInputStream fis = new FileInputStream(trustStorePath)) { sslTrustStore.load(fis, trustStorePassword.toCharArray()); } trustManagerFactory.init(sslTrustStore); SSLContext context = SSLContext.getInstance("TLS"); context.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), new SecureRandom()); socketFactory = new SSLConnectionSocketFactory(context); } catch (Exception e) { throw new SQLException("Error while initializing 2 way ssl socket factory ", e); } return socketFactory; }
From source file:com.bytelightning.opensource.pokerface.PokerFace.java
/** * Configures all the needed components, but does not actually start the server. * @param config Contains all information needed to fully wire up the http, https, and httpclient components of this reverse proxy. * @throws Exception Yeah, a lot can go wrong here, but at least it will be caught immediately :-) *//*w ww . j a v a 2 s . c o m*/ public void config(HierarchicalConfiguration config) throws Exception { List<HierarchicalConfiguration> lconf; HttpAsyncRequester executor = null; BasicNIOConnPool connPool = null; ObjectPool<ByteBuffer> byteBufferPool = null; LinkedHashMap<String, TargetDescriptor> mappings = null; ConcurrentMap<String, HttpHost> hosts = null; handlerRegistry = new UriHttpAsyncRequestHandlerMapper(); // Initialize the keystore (if one was specified) KeyStore keystore = null; char[] keypass = null; String keystoreUri = config.getString("keystore"); if ((keystoreUri != null) && (keystoreUri.trim().length() > 0)) { Path keystorePath = Utils.MakePath(keystoreUri); if (!Files.exists(keystorePath)) throw new ConfigurationException("Keystore does not exist."); if (Files.isDirectory(keystorePath)) throw new ConfigurationException("Keystore is not a file"); String storepass = config.getString("storepass"); if ((storepass != null) && "null".equals(storepass)) storepass = null; keystore = KeyStore.getInstance(KeyStore.getDefaultType()); try (InputStream keyStoreStream = Files.newInputStream(keystorePath)) { keystore.load(keyStoreStream, storepass == null ? null : storepass.trim().toCharArray()); } catch (IOException ex) { Logger.error("Unable to load https server keystore from " + keystoreUri); return; } keypass = config.getString("keypass").trim().toCharArray(); } // Wire up the listening reactor lconf = config.configurationsAt("server"); if ((lconf == null) || (lconf.size() != 1)) throw new ConfigurationException("One (and only one) server configuration element is allowed."); else { Builder builder = IOReactorConfig.custom(); builder.setIoThreadCount(ComputeReactorProcessors(config.getDouble("server[@cpu]", 0.667))); builder.setSoTimeout(config.getInt("server[@soTimeout]", 0)); builder.setSoLinger(config.getInt("server[@soLinger]", -1)); builder.setSoReuseAddress(true); builder.setTcpNoDelay(false); builder.setSelectInterval(100); IOReactorConfig rconfig = builder.build(); Logger.info("Configuring server with options: " + rconfig.toString()); listeningReactor = new DefaultListeningIOReactor(rconfig); lconf = config.configurationsAt("server.listen"); InetSocketAddress addr; boolean hasNonWildcardSecure = false; LinkedHashMap<SocketAddress, SSLContext> addrSSLContext = new LinkedHashMap<SocketAddress, SSLContext>(); if ((lconf == null) || (lconf.size() == 0)) { addr = new InetSocketAddress("127.0.0.1", 8080); ListenerEndpoint ep = listeningReactor.listen(addr); Logger.warn("Configured " + ep.getAddress()); } else { TrustManager[] trustManagers = null; KeyManagerFactory kmf = null; // Create all the specified listeners. for (HierarchicalConfiguration hc : lconf) { String addrStr = hc.getString("[@address]"); if ((addrStr == null) || (addrStr.length() == 0)) addrStr = "0.0.0.0"; String alias = hc.getString("[@alias]"); int port = hc.getInt("[@port]", alias != null ? 443 : 80); addr = new InetSocketAddress(addrStr, port); ListenerEndpoint ep = listeningReactor.listen(addr); String protocol = hc.containsKey("[@protocol]") ? hc.getString("[@protocol]") : null; Boolean secure = hc.containsKey("[@secure]") ? hc.getBoolean("[@secure]") : null; if ((alias != null) && (secure == null)) secure = true; if ((protocol != null) && (secure == null)) secure = true; if ((secure != null) && secure) { if (protocol == null) protocol = "TLS"; if (keystore == null) throw new ConfigurationException( "An https listening socket was requested, but no keystore was specified."); if (kmf == null) { kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(keystore, keypass); } // Are we going to trust all clients or just specific ones? if (hc.getBoolean("[@trustAny]", true)) trustManagers = new TrustManager[] { new X509TrustAllManager() }; else { TrustManagerFactory instance = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); instance.init(keystore); trustManagers = instance.getTrustManagers(); } KeyManager[] keyManagers = kmf.getKeyManagers(); if (alias != null) for (int i = 0; i < keyManagers.length; i++) { if (keyManagers[i] instanceof X509ExtendedKeyManager) keyManagers[i] = new PokerFaceKeyManager(alias, (X509ExtendedKeyManager) keyManagers[i]); } SSLContext sslCtx = SSLContext.getInstance(protocol); sslCtx.init(keyManagers, trustManagers, new SecureRandom()); if (addr.getAddress().isAnyLocalAddress()) { // This little optimization helps us respond faster for every connection as we don't have to extrapolate a local connection address to wild card. for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en .hasMoreElements();) { NetworkInterface intf = en.nextElement(); for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr .hasMoreElements();) { addr = new InetSocketAddress(enumIpAddr.nextElement(), port); addrSSLContext.put(addr, sslCtx); } } } else { addrSSLContext.put(addr, sslCtx); hasNonWildcardSecure = true; } } Logger.warn("Configured " + (alias == null ? "" : (protocol + " on")) + ep.getAddress()); } } // We will need an HTTP protocol processor for the incoming connections String serverAgent = config.getString("server.serverAgent", "PokerFace/" + Utils.Version); HttpProcessor inhttpproc = new ImmutableHttpProcessor( new HttpResponseInterceptor[] { new ResponseDateInterceptor(), new ResponseServer(serverAgent), new ResponseContent(), new ResponseConnControl() }); HttpAsyncService serviceHandler = new HttpAsyncService(inhttpproc, new DefaultConnectionReuseStrategy(), null, handlerRegistry, null) { public void exception(final NHttpServerConnection conn, final Exception cause) { Logger.warn(cause.getMessage()); super.exception(conn, cause); } }; if (addrSSLContext.size() > 0) { final SSLContext defaultCtx = addrSSLContext.values().iterator().next(); final Map<SocketAddress, SSLContext> sslMap; if ((!hasNonWildcardSecure) || (addrSSLContext.size() == 1)) sslMap = null; else sslMap = addrSSLContext; listeningDispatcher = new DefaultHttpServerIODispatch(serviceHandler, new SSLNHttpServerConnectionFactory(defaultCtx, null, ConnectionConfig.DEFAULT) { protected SSLIOSession createSSLIOSession(IOSession iosession, SSLContext sslcontext, SSLSetupHandler sslHandler) { SSLIOSession retVal; SSLContext sktCtx = sslcontext; if (sslMap != null) { SocketAddress la = iosession.getLocalAddress(); if (la != null) { sktCtx = sslMap.get(la); if (sktCtx == null) sktCtx = sslcontext; } retVal = new SSLIOSession(iosession, SSLMode.SERVER, sktCtx, sslHandler); } else retVal = super.createSSLIOSession(iosession, sktCtx, sslHandler); if (sktCtx != null) retVal.setAttribute("com.bytelightning.opensource.pokerface.secure", true); return retVal; } }); } else listeningDispatcher = new DefaultHttpServerIODispatch(serviceHandler, ConnectionConfig.DEFAULT); } // Configure the httpclient reactor that will be used to do reverse proxing to the specified targets. lconf = config.configurationsAt("targets"); if ((lconf != null) && (lconf.size() > 0)) { HierarchicalConfiguration conf = lconf.get(0); Builder builder = IOReactorConfig.custom(); builder.setIoThreadCount(ComputeReactorProcessors(config.getDouble("targets[@cpu]", 0.667))); builder.setSoTimeout(conf.getInt("targets[@soTimeout]", 0)); builder.setSoLinger(config.getInt("targets[@soLinger]", -1)); builder.setConnectTimeout(conf.getInt("targets[@connectTimeout]", 0)); builder.setSoReuseAddress(true); builder.setTcpNoDelay(false); connectingReactor = new DefaultConnectingIOReactor(builder.build()); final int bufferSize = conf.getInt("targets[@bufferSize]", 1024) * 1024; byteBufferPool = new SoftReferenceObjectPool<ByteBuffer>(new BasePooledObjectFactory<ByteBuffer>() { @Override public ByteBuffer create() throws Exception { return ByteBuffer.allocateDirect(bufferSize); } @Override public PooledObject<ByteBuffer> wrap(ByteBuffer buffer) { return new DefaultPooledObject<ByteBuffer>(buffer); } }); KeyManager[] keyManagers = null; TrustManager[] trustManagers = null; if (keystore != null) { KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(keystore, keypass); keyManagers = kmf.getKeyManagers(); } // Will the httpclient's trust any remote target, or only specific ones. if (conf.getBoolean("targets[@trustAny]", false)) trustManagers = new TrustManager[] { new X509TrustAllManager() }; else if (keystore != null) { TrustManagerFactory instance = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); instance.init(keystore); trustManagers = instance.getTrustManagers(); } SSLContext clientSSLContext = SSLContext.getInstance(conf.getString("targets[@protocol]", "TLS")); clientSSLContext.init(keyManagers, trustManagers, new SecureRandom()); // Setup an SSL capable connection pool for the httpclients. connPool = new BasicNIOConnPool(connectingReactor, new BasicNIOConnFactory(clientSSLContext, null, ConnectionConfig.DEFAULT), conf.getInt("targets[@connectTimeout]", 0)); connPool.setMaxTotal(conf.getInt("targets[@connMaxTotal]", 1023)); connPool.setDefaultMaxPerRoute(conf.getInt("targets[@connMaxPerRoute]", 1023)); // Set up HTTP protocol processor for outgoing connections String userAgent = conf.getString("targets.userAgent", "PokerFace/" + Utils.Version); HttpProcessor outhttpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] { new RequestContent(), new RequestTargetHost(), new RequestConnControl(), new RequestUserAgent(userAgent), new RequestExpectContinue(true) }); executor = new HttpAsyncRequester(outhttpproc, new DefaultConnectionReuseStrategy()); // Now set up all the configured targets. mappings = new LinkedHashMap<String, TargetDescriptor>(); hosts = new ConcurrentHashMap<String, HttpHost>(); String[] scheme = { null }; String[] host = { null }; int[] port = { 0 }; String[] path = { null }; int[] stripPrefixCount = { 0 }; for (HierarchicalConfiguration targetConfig : conf.configurationsAt("target")) { String match = targetConfig.getString("[@pattern]"); if ((match == null) || (match.trim().length() < 1)) { Logger.error("Unable to configure target; Invalid url match pattern"); continue; } String key = RequestForTargetConsumer.UriToTargetKey(targetConfig.getString("[@url]"), scheme, host, port, path, stripPrefixCount); if (key == null) { Logger.error("Unable to configure target"); continue; } HttpHost targetHost = hosts.get(key); if (targetHost == null) { targetHost = new HttpHost(host[0], port[0], scheme[0]); hosts.put(key, targetHost); } TargetDescriptor desc = new TargetDescriptor(targetHost, path[0], stripPrefixCount[0]); mappings.put(match, desc); } connectionDispatcher = new DefaultHttpClientIODispatch(new HttpAsyncRequestExecutor(), ConnectionConfig.DEFAULT); } // Allocate the script map which will be populated by it's own executor thread. if (config.containsKey("scripts.rootDirectory")) { Path tmp = Utils.MakePath(config.getProperty("scripts.rootDirectory")); if (!Files.exists(tmp)) throw new FileNotFoundException("Scripts directory does not exist."); if (!Files.isDirectory(tmp)) throw new FileNotFoundException("'scripts' path is not a directory."); scripts = new ConcurrentSkipListMap<String, ScriptObjectMirror>(); boolean watch = config.getBoolean("scripts.dynamicWatch", false); List<Path> jsLibs; Object prop = config.getProperty("scripts.library"); if (prop != null) { jsLibs = new ArrayList<Path>(); if (prop instanceof Collection<?>) { @SuppressWarnings("unchecked") Collection<Object> oprop = (Collection<Object>) prop; for (Object obj : oprop) jsLibs.add(Utils.MakePath(obj)); } else { jsLibs.add(Utils.MakePath(prop)); } } else jsLibs = null; lconf = config.configurationsAt("scripts.scriptConfig"); if (lconf != null) { if (lconf.size() > 1) throw new ConfigurationException("Only one scriptConfig element is allowed."); if (lconf.size() == 0) lconf = null; } HierarchicalConfiguration scriptConfig; if (lconf == null) scriptConfig = new HierarchicalConfiguration(); else scriptConfig = lconf.get(0); scriptConfig.setProperty("pokerface.scripts.rootDirectory", tmp.toString()); configureScripts(jsLibs, scriptConfig, tmp, watch); if (watch) ScriptDirectoryWatcher = new DirectoryWatchService(); } // Configure the static file directory (if any) Path staticFilesPath = null; if (config.containsKey("files.rootDirectory")) { Path tmp = Utils.MakePath(config.getProperty("files.rootDirectory")); if (!Files.exists(tmp)) throw new FileNotFoundException("Files directory does not exist."); if (!Files.isDirectory(tmp)) throw new FileNotFoundException("'files' path is not a directory."); staticFilesPath = tmp; List<HierarchicalConfiguration> mimeEntries = config.configurationsAt("files.mime-entry"); if (mimeEntries != null) { for (HierarchicalConfiguration entry : mimeEntries) { entry.setDelimiterParsingDisabled(true); String type = entry.getString("[@type]", "").trim(); if (type.length() == 0) throw new ConfigurationException("Invalid mime type entry"); String extensions = entry.getString("[@extensions]", "").trim(); if (extensions.length() == 0) throw new ConfigurationException("Invalid mime extensions for: " + type); ScriptHelperImpl.AddMimeEntry(type, extensions); } } } handlerRegistry.register("/*", new RequestHandler(executor, connPool, byteBufferPool, staticFilesPath, mappings, scripts != null ? Collections.unmodifiableNavigableMap(scripts) : null, config.getBoolean("scripts.allowScriptsToSpecifyDynamicHosts", false) ? hosts : null)); }
From source file:org.apache.servicemix.http.processors.CommonsHttpSSLSocketFactory.java
protected final void createUnmanagedFactory(SslParameters ssl) throws Exception { SSLContext context;//from w ww . j a va2 s .c om if (ssl.getProvider() == null) { context = SSLContext.getInstance(ssl.getProtocol()); } else { context = SSLContext.getInstance(ssl.getProtocol(), ssl.getProvider()); } KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(ssl.getKeyManagerFactoryAlgorithm()); String keyStore = ssl.getKeyStore(); if (keyStore == null) { keyStore = System.getProperty("javax.net.ssl.keyStore"); if (keyStore == null) { throw new IllegalArgumentException( "keyStore or system property javax.net.ssl.keyStore must be set"); } } if (keyStore.startsWith("classpath:")) { try { String res = keyStore.substring(10); URL url = new ClassPathResource(res).getURL(); keyStore = url.toString(); } catch (IOException e) { throw new JBIException("Unable to find keyStore " + keyStore, e); } } String keyStorePassword = ssl.getKeyStorePassword(); if (keyStorePassword == null) { keyStorePassword = System.getProperty("javax.net.ssl.keyStorePassword"); if (keyStorePassword == null) { throw new IllegalArgumentException( "keyStorePassword or system property javax.net.ssl.keyStorePassword must be set"); } } String trustStore = ssl.getTrustStore(); String trustStorePassword = null; if (trustStore == null) { trustStore = System.getProperty("javax.net.ssl.trustStore"); } if (trustStore != null) { if (trustStore.startsWith("classpath:")) { try { String res = trustStore.substring(10); URL url = new ClassPathResource(res).getURL(); trustStore = url.toString(); } catch (IOException e) { throw new JBIException("Unable to find trustStore " + trustStore, e); } } trustStorePassword = ssl.getTrustStorePassword(); if (trustStorePassword == null) { trustStorePassword = System.getProperty("javax.net.ssl.trustStorePassword"); if (trustStorePassword == null) { throw new IllegalArgumentException( "trustStorePassword or system property javax.net.ssl.trustStorePassword must be set"); } } } KeyStore ks = KeyStore.getInstance(ssl.getKeyStoreType()); ks.load(Resource.newResource(keyStore).getInputStream(), keyStorePassword.toCharArray()); keyManagerFactory.init(ks, ssl.getKeyPassword() != null ? ssl.getKeyPassword().toCharArray() : keyStorePassword.toCharArray()); if (trustStore != null) { KeyStore ts = KeyStore.getInstance(ssl.getTrustStoreType()); ts.load(Resource.newResource(trustStore).getInputStream(), trustStorePassword.toCharArray()); TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(ssl.getTrustManagerFactoryAlgorithm()); trustManagerFactory.init(ts); context.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), new java.security.SecureRandom()); } else { context.init(keyManagerFactory.getKeyManagers(), null, new java.security.SecureRandom()); } factory = context.getSocketFactory(); }
From source file:com.microsoft.tooling.msservices.helpers.azure.AzureManagerImpl.java
private SSLSocketFactory initSSLSocketFactory(@NotNull String managementCertificate) throws NoSuchAlgorithmException, IOException, KeyStoreException, CertificateException, UnrecoverableKeyException, KeyManagementException { byte[] decodeBuffer = new BASE64Decoder().decodeBuffer(managementCertificate); KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509"); InputStream is = new ByteArrayInputStream(decodeBuffer); KeyStore ks = KeyStore.getInstance("PKCS12"); ks.load(is, OpenSSLHelper.PASSWORD.toCharArray()); keyManagerFactory.init(ks, OpenSSLHelper.PASSWORD.toCharArray()); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(keyManagerFactory.getKeyManagers(), null, new SecureRandom()); return sslContext.getSocketFactory(); }
From source file:org.ejbca.core.protocol.ws.CommonEjbcaWS.java
/** Getting SSL socket factory using the Admin cert created for client certificate authentication **/ private SSLSocketFactory getSSLFactory() throws IOException, NoSuchAlgorithmException, UnrecoverableKeyException, KeyStoreException, CertificateException, KeyManagementException { // Put the key and certs in the user keystore (if available) java.security.KeyStore ks = java.security.KeyStore.getInstance("jks"); ks.load(new FileInputStream(TEST_ADMIN_FILE), PASSWORD.toCharArray()); final KeyManagerFactory kmf; kmf = KeyManagerFactory.getInstance("SunX509"); kmf.init(ks, PASSWORD.toCharArray()); final KeyManager km[] = kmf.getKeyManagers(); final TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); tmf.init(ks);//from w w w. ja va 2s.c o m final TrustManager tm[] = tmf.getTrustManagers(); if (km == null && tm == null) { return (SSLSocketFactory) SSLSocketFactory.getDefault(); } final SSLContext ctx = SSLContext.getInstance("TLS"); ctx.init(km, tm, null); return ctx.getSocketFactory(); }
From source file:org.beepcore.beep.profile.tls.jsse.TLSProfileJSSE.java
/** * init sets the criteria for which an SSL connection is made when * a TLS channel is started for a profile. It should only be * called once. For the properties, the initiator is defined as * the peer who starts the channel for the TLS profile, the * listener is the peer that receives the the channel start * request, irregardless of which actually started the session.<p> * * @param config <code>ProfileConfiguration</code> object that * contains key value pairs to initialize the TLS layer. None of * these are mandatory, but if you wish communication to be * anonymous with no authentication, (i.e., the listener to not * send back a certificate), you must set "Listener Anonymous" to * "true" and "Initiator Authentication Required" to "false". * The meaningful properties that can be set are these:<p> * <table>//from w w w . jav a 2 s. c o m * <tr> * <td>Listener Anonymous</td><td>(true|false) must be set to false if the * listener will not authenticate itself</td> * </tr><tr> * <td>Initiator Authentication Required</td><td>(true|false) set if the * initiator should send a certificate and the listener expects a * certificate.</td> * </tr><tr> * <td>Cipher Suite</td><td><i>not yet implemented.</i>the algorithms that * can be used for encryption, authentication, and key exchange.</td> * </tr><tr> * <td>Key Algorithm</td><td>key management algorithm. See * {@link com.sun.net.ssl.KeyManagerFactory#getInstance}</td> * </tr><tr> * <td>Key Provider</td><td>provider of the key management * algorithm. Defaults to * <code>com.sun.net.ssl.internal.ssl.Provider</code> See * {@link com.sun.net.ssl.KeyManagerFactory#getInstance}</td> * </tr><tr> * <td>Trust Algorithm</td><td>algorithm to be used by the trust * manager. See * {@link com.sun.net.ssl.TrustManagerFactory#getInstance}</td> * </tr><tr> * <td>Trust Provider</td><td>provider of the trust manager. Defaults to * <code>com.sun.net.ssl.internal.ssl.Provider</code>. See * {@link com.sun.net.ssl.TrustManagerFactory#getInstance}</td> * </tr><tr> * <td>Key Store Passphrase</td><td>pass phrase used to encrypt the key * store. See {@link java.security.KeyStore#load}</td> * </tr><tr> * <td>Key Store Data Type</td><td>data type of the key store passed in. * "file" is currently the only value accepted, meaning Key Store * is the name of a file containing keys. See * {@link java.security.KeyStore#load}</td> * </tr><tr> * <td>Key Store</td><td>value of the key store, dependent on the type in * Key Store Data Type. See {@link java.security.KeyStore#load}</td> * </tr><tr> * <td>Key Store Format</td><td>format of the keys within the key store. * Default is "JKS". See {@link java.security.KeyStore#getInstance}</td> * </tr><tr> * <td>Key Store Provider</td><td>provider for the key stores. See * {@link java.security.KeyStore#getInstance}</td> * </tr><tr> * <td>Trust Store Passphrase</td><td>pass phrase used to encrypt the trust * store. See {@link java.security.KeyStore#load}</td> * </tr><tr> * <td>Trust Store Data Type</td><td>data type of the certificates in the * trust store. "file" is currently th only value accepted, * meaning the trust store is a file on the local disk. See * {@link java.security.KeyStore#load}</td> * </tr><tr> * <td>Trust Store</td><td>value of the trust store, dependent on the type * in Trust * Store Data Type See {@link java.security.KeyStore#load}</td> * </tr><tr> * <td>Trust Store Format</td><td>format of the certificates within the * trust store. * Default is "JKS". See {@link java.security.KeyStore#getInstance}</td> * </tr><tr> * <td>Trust Store Provider</td><td>provider for the trust stores. See * {@link java.security.KeyStore#getInstance}</td> * </tr><tr> * <td>Allowed SSL Protocols</td><td>Comma separated list of algorithms * that may be used for SSL/TLS negotiations. By default, this will be * whatever the {@link SSLSocket} implementation supports. * @see SSLSocket#getSupportedProtocols() * @see SSLSocket#setEnabledProtocols(String[]) * </tr><tr> * </table> * @throws BEEPException For any error in the profile configuration, a * negative response in the form of a BEEP error will be sent back to the * requesting peer. The session will continue to be open and usable, at * least from the standpoint of this peer. * * @see com.sun.net.ssl.KeyManagerFactory * @see com.sun.net.ssl.TrustManagerFactory * @see java.security.KeyStore * @see com.sun.net.ssl.SSLContext */ public StartChannelListener init(String uri, ProfileConfiguration config) throws BEEPException { KeyManagerFactory kmf = null; KeyManager[] km = null; KeyStore ks = null; TrustManagerFactory tmf = null; TrustManager[] tm = null; KeyStore ts = null; SSLContext ctx; this.sslProtocols = null; // set the URI of this instance of the profile this.uri = uri; try { // create an SSL context object ctx = SSLContext.getInstance("TLS"); } catch (java.security.NoSuchAlgorithmException e) { throw new BEEPException("TLS Algorithm Not Found. Probable " + "cause is the JSSE provider has not " + "been added to the java.security file."); } try { String protocols = config.getProperty(PROPERTY_SSL_PROTOCOLS); if (protocols != null) { this.sslProtocols = protocols.split(","); } // initialize the key managers, trust managers, and keyAlgorithm = config.getProperty(PROPERTY_KEY_MANAGER_ALGORITHM); keyProvider = config.getProperty(PROPERTY_KEY_MANAGER_PROVIDER); trustAlgorithm = config.getProperty(PROPERTY_TRUST_MANAGER_ALGORITHM); trustProvider = config.getProperty(PROPERTY_TRUST_MANAGER_PROVIDER); keyPassphrase = config.getProperty(PROPERTY_KEYSTORE_PASSPHRASE); keyStoreType = config.getProperty(PROPERTY_KEYSTORE_TYPE); keyStoreName = config.getProperty(PROPERTY_KEYSTORE_NAME); keyStoreFormat = config.getProperty(PROPERTY_KEYSTORE_FORMAT, "JKS"); keyStoreProvider = config.getProperty(PROPERTY_KEYSTORE_PROVIDER); trustPassphrase = config.getProperty(PROPERTY_TRUSTSTORE_PASSPHRASE); trustStoreType = config.getProperty(PROPERTY_TRUSTSTORE_TYPE); trustStoreName = config.getProperty(PROPERTY_TRUSTSTORE_NAME); trustStoreFormat = config.getProperty(PROPERTY_TRUSTSTORE_FORMAT, "JKS"); trustStoreProvider = config.getProperty(PROPERTY_TRUSTSTORE_PROVIDER); // determine if the client must authenticate or if the server can // needClientAuth = new Boolean(config.getProperty(PROPERTY_CLIENT_AUTHENTICATION, "false")) .booleanValue(); serverAnonymous = new Boolean(config.getProperty(PROPERTY_SERVER_ANONYMOUS, "true")).booleanValue(); if (keyAlgorithm != null) { if (keyProvider != null) { kmf = KeyManagerFactory.getInstance(keyAlgorithm, keyProvider); } else { kmf = KeyManagerFactory.getInstance(keyAlgorithm); } // add support for a default type of key manager factory? if (keyStoreProvider != null) { ks = KeyStore.getInstance(keyStoreFormat, keyStoreProvider); } else { ks = KeyStore.getInstance(keyStoreFormat); } if (keyStoreType.equals("file")) { ks.load(new FileInputStream(keyStoreName), keyPassphrase.toCharArray()); } else { throw new BEEPException(ERR_ILLEGAL_KEY_STORE); } // initialize the key factory manager kmf.init(ks, keyPassphrase.toCharArray()); km = kmf.getKeyManagers(); } else { km = null; } if (trustAlgorithm != null) { if (trustProvider != null) { tmf = TrustManagerFactory.getInstance(trustAlgorithm, trustProvider); } else { tmf = TrustManagerFactory.getInstance(trustAlgorithm); } // add support for a default type of trust manager factory? if (trustStoreProvider != null) { ts = KeyStore.getInstance(trustStoreFormat, trustStoreProvider); } else { ts = KeyStore.getInstance(trustStoreFormat); } if (trustStoreType.equals("file")) { ts.load(new FileInputStream(trustStoreName), trustPassphrase.toCharArray()); } else { throw new BEEPException(ERR_ILLEGAL_TRUST_STORE); } // initialize the trust factory manager tmf.init(ts); tm = tmf.getTrustManagers(); } else { tm = null; } // create a socket factory from the key factories and // trust factories created for the algorithms and stores // specfied. No option is given to change the secure // random number generator ctx.init(km, tm, null); socketFactory = ctx.getSocketFactory(); return this; } catch (Exception e) { log.error(e); throw new BEEPException(e); } }
From source file:org.openecomp.sdnc.sli.aai.AAIService.java
public AAIService(URL propURL) { LOG.info("Entered AAIService.ctor"); String runtime = System.getProperty("aaiclient.runtime"); if (runtime != null && runtime.equals("OSGI")) { runtimeOSGI = true;/* ww w. j a v a2 s . com*/ } else { runtimeOSGI = false; } Properties props = null; try { props = initialize(propURL); AAIRequest.setProperties(props, this); } catch (Exception exc) { LOG.error("AicAAIResource.static", exc); } executor = new AAIRequestExecutor(); user_name = props.getProperty(CLIENT_NAME); user_password = props.getProperty(CLIENT_PWWD); if (user_name == null || user_name.isEmpty()) { LOG.debug("Basic user name is not set"); } if (user_password == null || user_password.isEmpty()) { LOG.debug("Basic password is not set"); } truststore_path = props.getProperty(TRUSTSTORE_PATH); truststore_password = props.getProperty(TRUSTSTORE_PSSWD); keystore_path = props.getProperty(KEYSTORE_PATH); keystore_password = props.getProperty(KEYSTORE_PSSWD); target_uri = props.getProperty(TARGET_URI); query_path = props.getProperty(QUERY_PATH); update_path = props.getProperty(UPDATE_PATH); String applicationId = props.getProperty(APPLICATION_ID); if (applicationId == null || applicationId.isEmpty()) { applicationId = "SDNC"; } application_id = applicationId; // connection timeout int tmpConnectionTimeout = 30000; int tmpReadTimeout = 30000; try { String tmpValue = null; tmpValue = props.getProperty(CONNECTION_TIMEOUT, "30000"); tmpConnectionTimeout = Integer.parseInt(tmpValue); tmpValue = props.getProperty(READ_TIMEOUT, "30000"); tmpReadTimeout = Integer.parseInt(tmpValue); } catch (Exception exc) { LOG.error("Failed setting connection timeout", exc); tmpConnectionTimeout = 30000; tmpReadTimeout = 30000; } connection_timeout = tmpConnectionTimeout; read_timeout = tmpReadTimeout; network_vserver_path = props.getProperty(NETWORK_VSERVER_PATH); svc_instance_path = props.getProperty(SVC_INSTANCE_PATH); // "/aai/v1/business/customers/customer/{customer-id}/service-subscriptions/service-subscription/{service-type}/service-instances"); // "/aai/v1/business/customers/customer/ma9181-203-customerid/service-subscriptions/service-subscription/ma9181%20Hosted%20Voice/service-instances"; // svc_inst_qry_path = props.getProperty(SVC_INST_QRY_PATH, "/aai/v1/search/generic-query?key=service-instance.service-instance-id:ma9181-204-instance&start-node-type=service-instance&include=service-instance"); svc_inst_qry_path = props.getProperty(SVC_INST_QRY_PATH); // "/aai/v1/search/generic-query?key=service-instance.service-instance-id:{svc-instance-id}&start-node-type=service-instance&include=service-instance"); param_service_type = props.getProperty(PARAM_SERVICE_TYPE, "service-type"); // P-Interfaces p_interface_path = props.getProperty(P_INTERFACE_PATH); vnf_image_query_path = props.getProperty(VNF_IMAGE_QUERY_PATH); ubb_notify_path = props.getProperty(UBB_NOTIFY_PATH); selflink_avpn = props.getProperty(SELFLINK_AVPN); selflink_fqdn = props.getProperty(SELFLINK_FQDN); service_path = props.getProperty(SERVICE_PATH); site_pair_set_path = props.getProperty(SITE_PAIR_SET_PATH); query_nodes_path = props.getProperty(QUERY_NODES_PATH); String iche = props.getProperty(CERTIFICATE_HOST_ERROR); boolean host_error = false; if (iche != null && !iche.isEmpty()) { host_error = Boolean.valueOf(iche); } ignore_certificate_host_error = host_error; HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() { public boolean verify(String string, SSLSession ssls) { return ignore_certificate_host_error; } }); if (truststore_path != null && truststore_password != null && (new File(truststore_path)).exists()) { System.setProperty("javax.net.ssl.trustStore", truststore_path); System.setProperty("javax.net.ssl.trustStorePassword", truststore_password); } if (keystore_path != null && keystore_password != null && (new File(keystore_path)).exists()) { DefaultClientConfig config = new DefaultClientConfig(); //both jersey and HttpURLConnection can use this SSLContext ctx = null; try { ctx = SSLContext.getInstance("TLS"); KeyManagerFactory kmf = null; try { String def = "SunX509"; String storeType = "PKCS12"; def = KeyStore.getDefaultType(); kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); FileInputStream fin = new FileInputStream(keystore_path); // KeyStore ks = KeyStore.getInstance("PKCS12"); String extension = keystore_path.substring(keystore_path.lastIndexOf(".") + 1); if (extension != null && !extension.isEmpty() && extension.equalsIgnoreCase("JKS")) { storeType = "JKS"; } KeyStore ks = KeyStore.getInstance(storeType); char[] pwd = keystore_password.toCharArray(); ks.load(fin, pwd); kmf.init(ks, pwd); } catch (Exception ex) { LOG.error("AAIResource", ex); } ctx.init(kmf.getKeyManagers(), null, null); config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, new HTTPSProperties(new HostnameVerifier() { @Override public boolean verify(String s, SSLSession sslSession) { return ignore_certificate_host_error; } }, ctx)); CTX = ctx; LOG.debug("SSLContext created"); } catch (KeyManagementException | NoSuchAlgorithmException exc) { LOG.error("AAIResource", exc); } } LOG.info("AAIResource.ctor initialized."); try { Field methodsField = HttpURLConnection.class.getDeclaredField("methods"); methodsField.setAccessible(true); // get the methods field modifiers Field modifiersField = Field.class.getDeclaredField("modifiers"); // bypass the "private" modifier modifiersField.setAccessible(true); // remove the "final" modifier modifiersField.setInt(methodsField, methodsField.getModifiers() & ~Modifier.FINAL); /* valid HTTP methods */ String[] methods = { "GET", "POST", "HEAD", "OPTIONS", "PUT", "DELETE", "TRACE", "PATCH" }; // set the new methods - including patch methodsField.set(null, methods); } catch (SecurityException | IllegalArgumentException | IllegalAccessException | NoSuchFieldException e) { e.printStackTrace(); } }