TODO: Is there a better place for this ssl setup work and constant defns
11224
private void setupSSL(ReadDeploymentResults readDepl) {
        SslType sslType = readDepl.deployment.getSsl();
        m_config.m_sslEnable = m_config.m_sslEnable || (sslType != null && sslType.isEnabled());
        if (m_config.m_sslEnable) {
            try {
                hostLog.info("SSL enabled for HTTP. Please point browser to HTTPS URL.");
                m_config.m_sslExternal = m_config.m_sslExternal || (sslType != null && sslType.isExternal());
                m_config.m_sslDR = m_config.m_sslDR || (sslType != null && sslType.isDr());
                m_config.m_sslInternal = m_config.m_sslInternal || (sslType != null && sslType.isInternal());
                boolean setSslBuilder = m_config.m_sslExternal || m_config.m_sslDR || m_config.m_sslInternal;
                setupSslContextCreators(sslType, setSslBuilder);
                if (m_config.m_sslExternal) {
                    hostLog.info("SSL enabled for admin and client port. Please enable SSL on client.");
                }
                if (m_config.m_sslDR) {
                    hostLog.info("SSL enabled for DR port. Please enable SSL on consumer clusters' DR connections.");
                }
                if (m_config.m_sslInternal) {
                    hostLog.info("SSL enabled for internal inter-node communication.");
                }
                CipherExecutor.SERVER.startup();
            } catch (Exception e) {
                VoltDB.crashLocalVoltDB("Unable to configure SSL", true, e);
            }
        }
    }
24921
def multiline
      message = []
      message << _('Could not connect via HTTPS to %{uri}') % { uri: @uri }
      message << _('  Unable to verify the SSL certificate')
      message << _('    The certificate may not be signed by a valid CA')
      message << _('    The CA bundle included with OpenSSL may not be valid or up to date')
      message.join("\n")
    end
1133544
private SSLSocketFactory setUpSSLContext() throws NoSuchAlgorithmException, KeyManagementException {
        SSLContext ctx = SSLContext.getInstance("SSL");
        ctx.init(null, new TrustManager[] { createPromptingTrustManager() }, null);
        return ctx.getSocketFactory();
    }
216077
private SSLContext buildSSLContext() {
        String keyANDkeystorePassword = configuration.getSslKeyPassword() == null ? configuration.getSslPassword() : configuration.getSslKeyPassword();
        return buildSSLContext(configuration.getSslKeystore(), configuration.getSslKeystoreType(),
                keyANDkeystorePassword, keyANDkeystorePassword,
                configuration.getSslKeyAlias(),
                configuration.getTrustStore(), configuration.getTrustStoreType(),
                configuration.getTrustStorePassword(),
                configuration.isValidateCerts(), configuration.getCrlPath(),
                null,
                configuration.isValidatePeerCerts(), configuration.isEnableCRLDP(), configuration.isEnableOCSP(),
                configuration.getOcspResponderURL(),
                configuration.getSslKeystoreProvider(),
                configuration.getSslTrustStoreProvider(),
                configuration.getSslProvider());
    }
1102261
def create_ssl_context():
        """"""
        ssl_context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
        ssl_context.check_hostname = False
        ssl_context.verify_mode = ssl.CERT_NONE
        return ssl_context
193935
function (url) {
        url = _.trimStart(url);
        var pathVariables,
            p = {
                raw: url
            };

        // extract the protocol
        p.protocol = _.get(url.match(regexes.extractProtocol), GET_1);
        _.isString(p.protocol) && (url = url.substr(p.protocol.length + 3)); // remove that damn protocol from url

        // extract the host
        p.host = _.get(url.match(regexes.extractHost), GET_1);

        // if host exists there are a lot you can extract from it
        if (_.isString(p.host)) {
            url = url.substr(p.host.length); // remove host from url

            if ((p.auth = _.get(p.host.match(regexes.extractHostAuth), GET_1))) {
                p.host = p.host.substr(p.auth.length + 1); // remove auth from host
                p.auth = p.auth.split(AUTH_SEPARATOR);
                p.auth = {
                    user: p.auth[0],
                    password: p.auth[1]
                };
            }

            // extract the port from the host
            p.port = _.get(p.host.match(regexes.extractPort), GET_1);
            p.port && (p.host = p.host.substring(0, p.host.length - p.port.length - 1)); // remove port from url

            p.host = _.trim(p.host, DOMAIN_SEPARATOR).split(regexes.splitDomain); // split host by subdomains
        }

        // extract the path
        p.path = _.get(url.match(regexes.extractPath), GET_0);
        if (_.isString(p.path)) {
            url = url.substr(p.path.length);
            p.path && (p.path = p.path.replace(regexes.trimPath, MATCH_1)); // remove leading slash for valid path
            // if path is blank string, we set it to undefined, if '/' then single blank string array
            p.path = p.path ? (p.path === PATH_SEPARATOR ? [E] : p.path.split(PATH_SEPARATOR)) : undefined;
        }

        // extract the query string
        p.query = _.get(url.match(regexes.extractQuery), GET_1);
        _.isString(p.query) && ((url = url.substr(p.query.length + 1)), (p.query = QueryParam.parse(p.query)));

        // extract the hash
        p.hash = _.get(url.match(regexes.extractSearch), GET_1);

        // extract path variables
        pathVariables = _.transform(p.path, function (res, segment) {
            // check if the segment has path variable prefix followed by the variable name.
            if (_.startsWith(segment, PATH_VARIABLE_IDENTIFIER) && segment !== PATH_VARIABLE_IDENTIFIER) {
                res.push({ key: segment.slice(1) }); // remove path variable prefix.
            }
        }, []);
        p.variable = pathVariables.length ? pathVariables : undefined;

        return p;
    }
1301534
function (cert, cb) {
    var infoObject = {},
        subjectElements = [],
        err;

  	var openssl = spawn('openssl', ['req', '-noout', '-subject', '-nameopt', 'RFC2253']);

    // Catch stderr
    openssl.stderr.on('data', function (out) {
      err = new Error(out);

      // Callback and return array
  		return cb(err, infoObject);
    });

    openssl.stdout.on('data', function (out) {
      var data = out.toString();

      // Put each line into an array
      var lineArray = data.split('\n');

      // Filter out empty ones
      lineArray = lineArray.filter(function(n){ return n !== undefined && n !== '' });

      /* Construct infoObject */

      // Certificate
      infoObject.certificate = cert;

      // Subject
      infoObject.subject = {};
      // Split by "/" prefix
      subjectElements = lineArray[0].replace('subject=', '').split(',');
      // For each elements
      for (var iS = 0; iS < subjectElements.length; iS++) {
        // Split keys and values by "=" separator
        var subjectKeyValue = subjectElements[iS].split('=');
        infoObject.subject[subjectKeyValue[0]] = subjectKeyValue[1];
      }

      // Callback and return array
  		return cb(err, infoObject);
  	});

  	openssl.stdin.write(cert);
  	openssl.stdin.end();
  }
733459
private static SslHandler configureSslHandler(SslHandler sslHandler) {
        // Set endpoint identification algorithm so that JDK's default X509TrustManager implementation
        // performs host name checks. Without this, the X509TrustManager implementation will never raise
        // a CertificateException even if the domain name or IP address mismatches.
        final SSLEngine engine = sslHandler.engine();
        final SSLParameters params = engine.getSSLParameters();
        params.setEndpointIdentificationAlgorithm("HTTPS");
        engine.setSSLParameters(params);
        return sslHandler;
    }
356001
def nginx_web_ssl_config(self):
        

        dt = [self.nginx_web_dir, self.nginx_ssl_dir]
        return nginx_conf_string.simple_ssl_web_conf.format(dt=dt)
795228
def _helper(
        self,
        host=None,
        port=None,
        debug=False,
        ssl=None,
        sock=None,
        workers=1,
        loop=None,
        protocol=HttpProtocol,
        backlog=100,
        stop_event=None,
        register_sys_signals=True,
        run_async=False,
        auto_reload=False,
    ):
        """"""
        if isinstance(ssl, dict):
            # try common aliaseses
            cert = ssl.get("cert") or ssl.get("certificate")
            key = ssl.get("key") or ssl.get("keyfile")
            if cert is None or key is None:
                raise ValueError("SSLContext or certificate and key required.")
            context = create_default_context(purpose=Purpose.CLIENT_AUTH)
            context.load_cert_chain(cert, keyfile=key)
            ssl = context
        if stop_event is not None:
            if debug:
                warnings.simplefilter("default")
            warnings.warn(
                "stop_event will be removed from future versions.",
                DeprecationWarning,
            )

        self.error_handler.debug = debug
        self.debug = debug

        server_settings = {
            "protocol": protocol,
            "request_class": self.request_class,
            "is_request_stream": self.is_request_stream,
            "router": self.router,
            "host": host,
            "port": port,
            "sock": sock,
            "ssl": ssl,
            "app": self,
            "signal": Signal(),
            "debug": debug,
            "request_handler": self.handle_request,
            "error_handler": self.error_handler,
            "request_timeout": self.config.REQUEST_TIMEOUT,
            "response_timeout": self.config.RESPONSE_TIMEOUT,
            "keep_alive_timeout": self.config.KEEP_ALIVE_TIMEOUT,
            "request_max_size": self.config.REQUEST_MAX_SIZE,
            "request_buffer_queue_size": self.config.REQUEST_BUFFER_QUEUE_SIZE,
            "keep_alive": self.config.KEEP_ALIVE,
            "loop": loop,
            "register_sys_signals": register_sys_signals,
            "backlog": backlog,
            "access_log": self.config.ACCESS_LOG,
            "websocket_max_size": self.config.WEBSOCKET_MAX_SIZE,
            "websocket_max_queue": self.config.WEBSOCKET_MAX_QUEUE,
            "websocket_read_limit": self.config.WEBSOCKET_READ_LIMIT,
            "websocket_write_limit": self.config.WEBSOCKET_WRITE_LIMIT,
            "graceful_shutdown_timeout": self.config.GRACEFUL_SHUTDOWN_TIMEOUT,
        }

        # -------------------------------------------- #
        # Register start/stop events
        # -------------------------------------------- #

        for event_name, settings_name, reverse in (
            ("before_server_start", "before_start", False),
            ("after_server_start", "after_start", False),
            ("before_server_stop", "before_stop", True),
            ("after_server_stop", "after_stop", True),
        ):
            listeners = self.listeners[event_name].copy()
            if reverse:
                listeners.reverse()
            # Prepend sanic to the arguments when listeners are triggered
            listeners = [partial(listener, self) for listener in listeners]
            server_settings[settings_name] = listeners

        if self.configure_logging and debug:
            logger.setLevel(logging.DEBUG)

        if (
            self.config.LOGO
            and os.environ.get("SANIC_SERVER_RUNNING") != "true"
        ):
            logger.debug(
                self.config.LOGO
                if isinstance(self.config.LOGO, str)
                else BASE_LOGO
            )

        if run_async:
            server_settings["run_async"] = True

        # Serve
        if host and port and os.environ.get("SANIC_SERVER_RUNNING") != "true":
            proto = "http"
            if ssl is not None:
                proto = "https"
            logger.info("Goin' Fast @ {}://{}:{}".format(proto, host, port))

        return server_settings
500684
def use_ssl=(flag)
      flag = (flag ? true : false)
      raise IOError, "use_ssl value changed, but session already started" \
          if started? and @use_ssl != flag
      if flag and not @ssl_context
        @ssl_context = OpenSSL::SSL::SSLContext.new
      end
      @use_ssl = flag
    end
120365
def localSslFixup(host, sslContext):
    
    if not sslContext and host in ['localhost', '127.0.0.1', '::1']:
        import ssl
        if hasattr(ssl, '_create_unverified_context'):
            sslContext = ssl._create_unverified_context()
    return sslContext
652011
static CloseableHttpClient buildHttpClient(
      boolean insecureMode, File ocspCacheFile, boolean useOcspCacheServer)
  {
    // set timeout so that we don't wait forever.
    // Setup the default configuration for all requests on this client
    DefaultRequestConfig =
        RequestConfig.custom()
            .setConnectTimeout(DEFAULT_CONNECTION_TIMEOUT)
            .setConnectionRequestTimeout(DEFAULT_CONNECTION_TIMEOUT)
            .setSocketTimeout(DEFAULT_HTTP_CLIENT_SOCKET_TIMEOUT)
            .build();

    TrustManager[] trustManagers = null;
    if (!insecureMode)
    {
      // A custom TrustManager is required only if insecureMode is disabled,
      // which is by default in the production. insecureMode can be enabled
      // 1) OCSP service is down for reasons, 2) PowerMock test tht doesn't
      // care OCSP checks.
      TrustManager[] tm = {
          new SFTrustManager(ocspCacheFile, useOcspCacheServer)};
      trustManagers = tm;
    }
    try
    {
      Registry<ConnectionSocketFactory> registry =
          RegistryBuilder.<ConnectionSocketFactory>create()
              .register("https",
                        new SFSSLConnectionSocketFactory(trustManagers, socksProxyDisabled))
              .register("http",
                        new SFConnectionSocketFactory())
              .build();

      // Build a connection manager with enough connections
      connectionManager = new PoolingHttpClientConnectionManager(registry);
      connectionManager.setMaxTotal(DEFAULT_MAX_CONNECTIONS);
      connectionManager.setDefaultMaxPerRoute(DEFAULT_MAX_CONNECTIONS_PER_ROUTE);

      if (useProxy)
      {
        // use the custom proxy properties
        HttpHost proxy = new HttpHost(proxyHost, proxyPort);
        Credentials credentials =
            new UsernamePasswordCredentials(proxyUser, proxyPassword);
        AuthScope authScope = new AuthScope(proxyHost, proxyPort);
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(authScope, credentials);
        SdkProxyRoutePlanner sdkProxyRoutePlanner = new SdkProxyRoutePlanner(
            proxyHost, proxyPort, nonProxyHosts
        );
        httpClient =
            HttpClientBuilder.create()
                .setDefaultRequestConfig(DefaultRequestConfig)
                .setConnectionManager(connectionManager)
                // Support JVM proxy settings
                .useSystemProperties()
                .setRedirectStrategy(new DefaultRedirectStrategy())
                .setUserAgent("-")     // needed for Okta
                .disableCookieManagement() // SNOW-39748
                .setProxy(proxy)
                .setDefaultCredentialsProvider(credentialsProvider)
                .setRoutePlanner(sdkProxyRoutePlanner)
                .build();
      }
      else
      {
        httpClient =
            HttpClientBuilder.create()
                .setDefaultRequestConfig(DefaultRequestConfig)
                .setConnectionManager(connectionManager)
                // Support JVM proxy settings
                .useSystemProperties()
                .setRedirectStrategy(new DefaultRedirectStrategy())
                .setUserAgent("-")     // needed for Okta
                .disableCookieManagement() // SNOW-39748
                .build();
      }
      return httpClient;
    }
    catch (NoSuchAlgorithmException | KeyManagementException ex)
    {
      throw new SSLInitializationException(ex.getMessage(), ex);
    }
  }
1301084
function () {
    // Create request options from parsed source URL
    var options = url.parse(this.source, false);

    // Add on some defaults
    extend(options, {
      method: 'get',
      headers: {
        host: options.host,
        accept: 'image/*'
      }
    });

    // Determine https/http from source URL
    var library = options.protocol === 'https:' ? https : http;

    // Setup the request and its event binds
    this.request = library.request(options);
    this.request.on('response', this.onResponse.bind(this));
    this.request.on('error', this.onError.bind(this));
    this.request.setTimeout(5000, this.onTimeout.bind(this));

    // Start the download
    this.startTime = new Date().getTime();
    this.request.end();
  }
1060005
function createHttps() {
    if (typeof options.https === 'undefined') {
      log('https | no options.https; no server');
      return onListen('https');
    }

    var ssl  = options.https,
        port = !isNaN(ssl.port) ? +ssl.port : 443,  // accepts string or number
        timeout = options.timeout || ssl.timeout,
        server,
        args;

    var finalHttpsOptions = assign({}, ssl, {
      //
      // Load default SSL key, cert and ca(s).
      //
      key: normalizePEMContent(ssl.root, ssl.key),
      cert: normalizeCertContent(ssl.root, ssl.cert, ssl.key),
      ca: normalizeCA(ssl.root, ssl.ca),
      //
      // Properly expose ciphers for an A+ SSL rating:
      // https://certsimple.com/blog/a-plus-node-js-ssl
      //
      ciphers: normalizeCiphers(ssl.ciphers),
      honorCipherOrder: !!ssl.honorCipherOrder,
      //
      // Protect against the POODLE attack by disabling SSLv3
      // @see http://googleonlinesecurity.blogspot.nl/2014/10/this-poodle-bites-exploiting-ssl-30.html
      //
      secureProtocol: 'SSLv23_method',
      secureOptions: secureOptions
    });

    if (ssl.sni && !finalHttpsOptions.SNICallback) {
      finalHttpsOptions.SNICallback = getSNIHandler(ssl)
    }

    log('https | listening on %d', port);
    server = https.createServer(finalHttpsOptions, ssl.handler || handler);

    if (typeof timeout === 'number') server.setTimeout(timeout);
    args = [server, port];
    if (ssl.host) {
      args.push(ssl.host);
    }

    args.push(function listener(err) { onListen('https', err, this); });
    connected.apply(null, args);
  }
1263354
function HttpsProxyAgent (opts) {
  if (!(this instanceof HttpsProxyAgent)) return new HttpsProxyAgent(opts);
  if ('string' == typeof opts) opts = url.parse(opts);
  if (!opts) throw new Error('an HTTP(S) proxy server `host` and `port` must be specified!');
  debug('creating new HttpsProxyAgent instance: %o', opts);
  Agent.call(this, connect);

  var proxy = extend({}, opts);

  // if `true`, then connect to the proxy server over TLS. defaults to `false`.
  this.secureProxy = proxy.protocol ? /^https:?$/i.test(proxy.protocol) : false;

  // prefer `hostname` over `host`, and set the `port` if needed
  proxy.host = proxy.hostname || proxy.host;
  proxy.port = +proxy.port || (this.secureProxy ? 443 : 80);

  if (proxy.host && proxy.path) {
    // if both a `host` and `path` are specified then it's most likely the
    // result of a `url.parse()` call... we need to remove the `path` portion so
    // that `net.connect()` doesn't attempt to open that as a unix socket file.
    delete proxy.path;
    delete proxy.pathname;
  }

  this.proxy = proxy;
}
875577
def _init_ssl(self):
        

        if not have_openssl:
            raise ImportError('SSL sockets have been disabled due to missing requirement: pyopenssl.')

        try:
            ctx = SSL.Context(SSL.TLSv1_METHOD)

            if isinstance(self.ssl_key, crypto.PKey):
                ctx.use_privatekey(self.ssl_key)
            else:
                ctx.use_privatekey_file(self.ssl_key)

            if isinstance(self.ssl_certificate, crypto.X509):
                ctx.use_certificate(self.ssl_certificate)
            else:
                ctx.use_certificate_file(self.ssl_certificate)

            if isinstance(self.ssl_ca, crypto.X509):
                store = ctx.get_cert_store()
                store.add_cert(self.ssl_ca)
            else:
                ctx.load_verify_locations(self.ssl_ca, None)

            verify_method = SSL.VERIFY_PEER
            if (self._ssl_allow_self_signed):
                verify_method = SSL.VERIFY_NONE

            ctx.set_verify(verify_method, self._verify_ssl_callback)

            self._device = SSL.Connection(ctx, self._device)

        except SSL.Error as err:
            raise CommError('Error setting up SSL connection.', err)