Create a TSocket using configured TLS/SSL options.
326355
private TSocket createTLSSocket(String host) throws TTransportException {
        TSSLTransportParameters sslParams = new TSSLTransportParameters("SSL", m_dbtls_cipher_suites);
        if (!Utils.isEmpty(m_keystore)) {
            sslParams.setKeyStore(m_keystore, m_keystorepassword);
        }
        if (!Utils.isEmpty(m_truststore)) {
            sslParams.setTrustStore(m_truststore, m_truststorepassword);
        }
        return TSSLTransportFactory.getClientSocket(host, m_dbport, m_db_timeout_millis, sslParams);
    }
805813
def make_tls_config(app_config):
    """"""

    if not app_config['DOCKER_TLS']:
        return False

    cert_path = app_config['DOCKER_TLS_CERT_PATH']
    if cert_path:
        client_cert = '{0}:{1}'.format(
            os.path.join(cert_path, 'cert.pem'),
            os.path.join(cert_path, 'key.pem'))
        ca_cert = os.path.join(cert_path, 'ca.pem')
    else:
        client_cert = app_config['DOCKER_TLS_CLIENT_CERT']
        ca_cert = app_config['DOCKER_TLS_CA_CERT']

    client_cert = parse_client_cert_pair(client_cert)
    return TLSConfig(
        client_cert=client_cert,
        ca_cert=ca_cert,
        verify=app_config['DOCKER_TLS_VERIFY'],
        ssl_version=app_config['DOCKER_TLS_SSL_VERSION'],
        assert_hostname=app_config['DOCKER_TLS_ASSERT_HOSTNAME'])
347641
protected synchronized void decorateWithTLS(TLSClientParameters tlsClientParameters,
                                                HttpURLConnection connection) throws GeneralSecurityException {

        int hash = tlsClientParameters.hashCode();
        if (hash != lastTlsHash) {
            lastTlsHash = hash;
            socketFactory = null;
        }

        // always reload socketFactory from HttpsURLConnection.defaultSSLSocketFactory and
        // tlsClientParameters.sslSocketFactory to allow runtime configuration change
        if (tlsClientParameters.isUseHttpsURLConnectionDefaultSslSocketFactory()) {
            socketFactory = HttpsURLConnection.getDefaultSSLSocketFactory();

        } else if (tlsClientParameters.getSSLSocketFactory() != null) {
            // see if an SSLSocketFactory was set. This allows easy interop
            // with not-yet-commons-ssl.jar, or even just people who like doing their
            // own JSSE.
            socketFactory = tlsClientParameters.getSSLSocketFactory();

        } else if (socketFactory == null) {
            // ssl socket factory not yet instantiated, create a new one with tlsClientParameters's Trust
            // Managers, Key Managers, etc

            SSLContext ctx = org.apache.cxf.transport.https.SSLUtils.getSSLContext(tlsClientParameters);

            String[] cipherSuites = SSLUtils.getCiphersuitesToInclude(tlsClientParameters.getCipherSuites(),
                                                                      tlsClientParameters.getCipherSuitesFilter(),
                                                                      ctx.getSocketFactory().getDefaultCipherSuites(),
                                                                      SSLUtils.getSupportedCipherSuites(ctx),
                                                                      LOG);
            // The SSLSocketFactoryWrapper enables certain cipher suites
            // from the policy.
            String protocol = tlsClientParameters.getSecureSocketProtocol() != null ? tlsClientParameters.getSecureSocketProtocol() : "TLS";
            socketFactory = new SSLSocketFactoryWrapper(ctx.getSocketFactory(), cipherSuites, protocol);
            //recalc the hashcode since some of the above MAY have changed the tlsClientParameters
            lastTlsHash = tlsClientParameters.hashCode();
        } else {
            // ssl socket factory already initialized, reuse it to benefit of keep alive
        }

        HostnameVerifier verifier = org.apache.cxf.transport.https.SSLUtils.getHostnameVerifier(tlsClientParameters);

        if (connection instanceof HttpsURLConnection) {
            // handle the expected case (javax.net.ssl)
            final HttpsURLConnection conn = (HttpsURLConnection) connection;
            conn.setHostnameVerifier(verifier);
            AccessController.doPrivileged(new PrivilegedAction<Void>() {

                @Override
                public Void run() {
                    conn.setSSLSocketFactory(socketFactory);
                    return null;
                }
            });
        } else {
            // handle the deprecated sun case and other possible hidden API's
            // that are similar to the Sun cases
            try {
                Method method = connection.getClass().getMethod("getHostnameVerifier");

                InvocationHandler handler = new ReflectionInvokationHandler(verifier) {
                    @Override
                    public Object invoke(Object proxy,
                                         Method method,
                                         Object[] args) throws Throwable {
                        try {
                            return super.invoke(proxy, method, args);
                        } catch (Exception ex) {
                            return false;
                        }
                    }
                };
                Object proxy = java.lang.reflect.Proxy.newProxyInstance(this.getClass().getClassLoader(),
                                                                        new Class[] { method.getReturnType() },
                                                                        handler);

                method = connection.getClass().getMethod("setHostnameVerifier", method.getReturnType());
                method.invoke(connection, proxy);
            } catch (Exception ex) {
                //Ignore this one
            }
            try {
                Method getSSLSocketFactory = connection.getClass().getMethod("getSSLSocketFactory");
                Method setSSLSocketFactory = connection.getClass().getMethod("setSSLSocketFactory", getSSLSocketFactory.getReturnType());
                if (getSSLSocketFactory.getReturnType().isInstance(socketFactory)) {
                    setSSLSocketFactory.invoke(connection, socketFactory);
                } else {
                    //need to see if we can create one - mostly the weblogic case.   The
                    //weblogic SSLSocketFactory has a protected constructor that can take
                    //a JSSE SSLSocketFactory so we'll try and use that
                    Constructor<?> c = getSSLSocketFactory.getReturnType().getDeclaredConstructor(SSLSocketFactory.class);
                    ReflectionUtil.setAccessible(c);
                    setSSLSocketFactory.invoke(connection, c.newInstance(socketFactory));
                }
            } catch (Exception ex) {
                if (connection.getClass().getName().contains("weblogic")) {
                    if (!weblogicWarned) {
                        weblogicWarned = true;
                        LOG.warning("Could not configure SSLSocketFactory on Weblogic.  "
                                    + " Use the Weblogic control panel to configure the SSL settings.");
                    }
                    return;
                }
                //if we cannot set the SSLSocketFactor, we're in serious trouble.
                throw new IllegalArgumentException("Error decorating connection class "
                                                   + connection.getClass().getName(), ex);
            }
        }
    }
37984
public static SocketIOServer newInstance(int port, SslContext sslContext) {
    return new SocketIOServer(ServerConfiguration.builder()
        .port(port)
        .sslContext(sslContext)
        .build());
  }
1204832
def connect(self):
        """"""
        super(TLSTransport, self).connect()
        self.socket = ssl.wrap_socket(
            self.socket,
            ssl_version=ssl.PROTOCOL_TLSv1,
            cert_reqs=ssl.CERT_REQUIRED,
            ca_certs=self.ca_certs)
712703
public SSLServerSocket buildServerSocket() throws CertificateException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException, IOException
    {
        // Get socket
        final SSLServerSocket s = (SSLServerSocket) build().getServerSocketFactory().createServerSocket(port);

        // Set protocols
        s.setEnabledProtocols(TLS.getUsable(TLS.TLS_PROTOCOLS, s.getSupportedProtocols()));
        s.setEnabledCipherSuites(TLS.getUsable(TLS.TLS_CIPHER_SUITES, s.getSupportedCipherSuites()));

        return s;
    }
1143793
public static ServerSocketFactory createSSLServerSocketFactory(Configuration config) throws Exception {
		SSLContext sslContext = createInternalSSLContext(config);
		if (sslContext == null) {
			throw new IllegalConfigurationException("SSL is not enabled");
		}

		String[] protocols = getEnabledProtocols(config);
		String[] cipherSuites = getEnabledCipherSuites(config);

		SSLServerSocketFactory factory = sslContext.getServerSocketFactory();
		return new ConfiguringSSLServerSocketFactory(factory, protocols, cipherSuites);
	}
1098572
public SSLSocket buildSocket() throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException, UnrecoverableKeyException, KeyManagementException
    {
        if (host == null) throw new IllegalStateException("Cannot create socket without host");

        // Get socket
        final SSLSocket s = (SSLSocket) build().getSocketFactory().createSocket(host, port);

        // Set protocols
        s.setEnabledProtocols(TLS.getUsable(TLS.TLS_PROTOCOLS, s.getSupportedProtocols()));
        s.setEnabledCipherSuites(TLS.getUsable(TLS.TLS_CIPHER_SUITES, s.getSupportedCipherSuites()));

        return s;
    }
792765
@Override
    public Socket createSocket(String host, int port) throws IOException {
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
            Tr.debug(tc, "SocketFactory attempting to create socket for host: " + host + " port: " + port);

        // check for SSL addresses
        if (Util.isEncodedHost(host, HOST_PROTOCOL)) {
            String sslConfigName = Util.decodeHostInfo(host);
            host = Util.decodeHost(host);
            return createSSLSocket(host, (char) port, sslConfigName);
        } else {
            return createPlainSocket(host, port);
        }
    }
687052
def _create_socket(self):
        
        log.warning('No certificate check is performed for SSL connections')
        s = super(SSL, self)._create_socket()
        return wrap_socket(s)
31960
protected SSLSocket createSecureSocket(String host, int port, SecurityDomain securityDomain, Socket nestedSocket) throws NoSecurityDomainException, NoSuchAlgorithmException, KeyManagementException, UnknownHostException, IOException {
        if (!CONTEXT.isTLSEnabled())
            throw new NoSuchAlgorithmException("TLS has been disabled for ATNA connections via " + SecurityDomainManager.class.getName() + ".setSetTLSEnabled(false)");

        SSLContext ctx = null;

        // Attempt to get an instance of the first support TLS protocol
        try {
            ctx = SSLContext.getInstance(securityDomain.getJdkTlsClientProtocols()[0]);
        } catch (NoSuchAlgorithmException e) {
            securityDomain.restoreSystemEnvironment();
            throw e;
        }

        // Initialize the instance for the key and trust stores
        try {
            KeyManager[] keyMgrs = securityDomain.getKeyManagers();
            TrustManager[] trustMgrs = securityDomain.getTrustManagers();

            ctx.init(keyMgrs, trustMgrs, null);
        } catch (KeyManagementException e) {
            throw e;
        }

        SSLSocketFactory factory = ctx.getSocketFactory();
        SSLSocket socket = null;

        if (logger.isDebugEnabled()) {
            String[] supportedSuites = factory.getSupportedCipherSuites();
            logger.debug("\n\nSupported cipher suites are:");
            for (int i = 0; i < supportedSuites.length; i++) {
                logger.debug("\t" + supportedSuites[i]);
            }
        }

        int retries = 0;

        Throwable cause = null;
        // Loop to get a connection or until we've exhausted number of retries
        while (retries < CONTEXT.getConfig().getSocketRetries()) {
            try {

                if (logger.isDebugEnabled()) {
                    logger.debug("Connecting to " + host + " on port " + port +
                            " (timeout: " + CONTEXT.getConfig().getConnectTimeout() + " ms) using factory " + factory.getClass().getName());
                }

                //SocketAddress address = new InetSocketAddress(host,port);
                if (nestedSocket instanceof Socket) {
                    socket = (SSLSocket) (factory.createSocket(nestedSocket, host, port, true));
                } else {
                    socket = (SSLSocket) (factory.createSocket(host, port));
                }

                //socket.connect(address, CONTEXT.getConfig().getConnectTimeout());
                // Set amount of time to wait on socket read before timing out
                socket.setSoTimeout(CONTEXT.getConfig().getSocketTimeout());
                socket.setKeepAlive(true);

                socket.setEnabledProtocols(securityDomain.getJdkTlsClientProtocols());
                socket.setEnabledCipherSuites(securityDomain.getCipherSuites());

                if (logger.isDebugEnabled()) {
                    logger.debug("\n\nEnabled Cipher suites for connection are: ");
                    String[] suites = socket.getEnabledCipherSuites();
                    for (int i = 0; i < suites.length; i++) {
                        logger.debug("\t" + suites[i]);
                    }
                }

                // Force the TLS handshake at this point so we can catch any authentication errors
                socket.startHandshake();
                break;

            } catch (SSLHandshakeException e) {
                logger.error("Handshake failed with server " + host + " on port " + port + " reason " + e.getLocalizedMessage(), e);
                try {
                    socket.close();
                } catch (IOException e1) {
                    logger.error("Error trying to close socket for " + host + " on port " + port + " reason " + e1.getLocalizedMessage(), e1);
                }
                //securityDomain.restoreSystemEnvironment();
                throw e;
            } catch (UnknownHostException e) {
                logger.error("Unable to establish connection to " + host + " on port " + port + " reason " + e.getLocalizedMessage(), e);
                //securityDomain.restoreSystemEnvironment();
                throw e;
            } catch (SocketException e) {
                logger.error("Error connecting to " + host + " on port " + port + ". Will retry in "
                        + CONTEXT.getConfig().getSocketRetryWait() / 1000 + " seconds.", e);
                retries++;
                cause = e;

                try {
                    Thread.sleep(CONTEXT.getConfig().getSocketRetryWait());
                    continue;
                } catch (InterruptedException ie) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Sleep awoken early");
                    }
                    continue;
                }

            } catch (IOException e) {
                logger.error("Error connecting to " + host + " on port " + port + ". Will retry in "
                        + CONTEXT.getConfig().getSocketRetryWait() / 1000 + " seconds." + " reason " + e.getLocalizedMessage(), e);
                retries++;
                cause = e;

                try {
                    Thread.sleep(CONTEXT.getConfig().getSocketRetryWait());
                    continue;
                } catch (InterruptedException ie) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Sleep awoken early");
                    }
                    continue;
                }
            }

        }

        // If socket retries exceed maximum allowed, throw an exception
        if (retries >= CONTEXT.getConfig().getSocketRetries()) {
            //securityDomain.restoreSystemEnvironment();
            logger.error("Secure Socket Connect Retries Exhausted.", cause);
            throw new ConnectException("Secure socket retries exhausted");
        }

        //securityDomain.restoreSystemEnvironment();
        return socket;
    }
531978
private static SSLSocketFactory createSocketFactory(Ssl context) {
    try {
      return context.newFactory(new AlwaysTrustManager());
    } catch (Exception e) {
      throw new IllegalStateException("Fail to build SSL factory", e);
    }
  }
1059878
def create_tcp_socket (self, host):
        """"""
        port = int(self['TCPSocket'])
        sockinfo = get_sockinfo(host, port=port)
        sock = create_socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            sock.connect(sockinfo[0][4])
        except socket.error:
            sock.close()
            raise
        return sock
653580
def setup(addr, user, remote_path, local_key=None):
    """"""
    port = find_port(addr, user)

    if not port or not is_alive(addr, user):
        port = new_port()

        scp(addr, user, __file__, '~/unixpipe', local_key)

        ssh_call = ['ssh', '-fL%d:127.0.0.1:12042' % port,
                    '-o', 'ExitOnForwardFailure=yes',
                    '-o', 'ControlPath=~/.ssh/unixpipe_%%r@%%h_%d' % port,
                    '-o', 'ControlMaster=auto',
                    '%s@%s' % (user, addr,), 'python', '~/unixpipe',
                    'server', remote_path]
        if local_key:
            ssh_call.insert(1, local_key)
            ssh_call.insert(1, '-i')

        subprocess.call(ssh_call)
        # XXX Sleep is a bad way to wait for the tunnel endpoint
        time.sleep(1)

    return port
454006
private void configureSsl(SocketChannel ch) {
        SslContext sslCtx = SslContextBuilder.build();
        ChannelPipeline pipeline = ch.pipeline();
        pipeline.addLast(sslCtx.newHandler(ch.alloc()));
        // We must wait for the handshake to finish and the protocol to be negotiated before configuring
        // the HTTP/2 components of the pipeline.
        pipeline.addLast(new ApplicationProtocolNegotiationHandler("") {
            @Override
            protected void configurePipeline(ChannelHandlerContext ctx, String protocol) {
                if (ApplicationProtocolNames.HTTP_2.equals(protocol)) {
                    ChannelPipeline p = ctx.pipeline();
                    p.addLast(connectionHandler);
                    configureEndOfPipeline(p);
                    return;
                }
                ctx.close();
                throw new IllegalStateException("unknown protocol: " + protocol);
            }
        });
    }
1068976
def _create_socket(self, socket_family):
        
        sock = socket.socket(socket_family, socket.SOCK_STREAM, 0)
        sock.settimeout(self._parameters['timeout'] or None)
        if self.use_ssl:
            if not compatibility.SSL_SUPPORTED:
                raise AMQPConnectionError(
                    'Python not compiled with support for TLSv1 or higher'
                )
            sock = self._ssl_wrap_socket(sock)
        return sock
763935
def create_transport(host, connect_timeout, ssl=False):
    """"""
    if ssl:
        return SSLTransport(host, connect_timeout, ssl)
    else:
        return TCPTransport(host, connect_timeout)