Request SSL Cert.
350285
public function withSSLCert($sslCert, $sslKey)
    {
        $this->sslCert = $sslCert;
        $this->sslKey = $sslKey;

        return $this;
    }
71167
def cli(env, identifier):
    """"""

    manager = SoftLayer.SSLManager(env.client)
    certificate = manager.get_certificate(identifier)

    write_cert(certificate['commonName'] + '.crt', certificate['certificate'])
    write_cert(certificate['commonName'] + '.key', certificate['privateKey'])

    if 'intermediateCertificate' in certificate:
        write_cert(certificate['commonName'] + '.icc',
                   certificate['intermediateCertificate'])

    if 'certificateSigningRequest' in certificate:
        write_cert(certificate['commonName'] + '.csr',
                   certificate['certificateSigningRequest'])
324467
def show_cert(id_):
    '''
    
    '''
    data = __utils__['http.query'](
        '{0}/certificaterequests/{1}/certificate'.format(_base_url(), id_),
        params={
            'format': 'PEM',
            'chainOrder': 'ROOT_FIRST'
        },
        status=True,
        text=True,
        header_dict={'tppl-api-key': _api_key()},
    )
    status = data['status']
    if six.text_type(status).startswith('4') or six.text_type(status).startswith('5'):
        raise CommandExecutionError(
            'There was an API error: {0}'.format(data['error'])
        )
    data = data.get('body', '')
    csr_data = __utils__['http.query'](
        '{0}/certificaterequests/{1}'.format(_base_url(), id_),
        status=True,
        decode=True,
        decode_type='json',
        header_dict={'tppl-api-key': _api_key()},
    )
    status = csr_data['status']
    if six.text_type(status).startswith('4') or six.text_type(status).startswith('5'):
        raise CommandExecutionError(
            'There was an API error: {0}'.format(csr_data['error'])
        )
    csr_data = csr_data.get('dict', {})
    certs = _parse_certs(data)
    dns_name = ''
    for item in csr_data['certificateName'].split(','):
        if item.startswith('cn='):
            dns_name = item.split('=')[1]
    #certs['CSR Data'] = csr_data

    cache = salt.cache.Cache(__opts__, syspaths.CACHE_DIR)
    domain_data = cache.fetch('venafi/domains', dns_name)
    if domain_data is None:
        domain_data = {}
    certs['private_key'] = domain_data.get('private_key')
    domain_data.update(certs)
    cache.store('venafi/domains', dns_name, domain_data)

    certs['request_id'] = id_
    return certs
1091292
def SSLCertificates(self):
        
        url = self._url + "/SSLCertificate"
        params = {"f" : "json"}
        return self._post(url=url,
                          param_dict=params,
                          proxy_url=self._proxy_url,
                          proxy_port=self._proxy_port)
72854
def getCert(certHost=vos.vos.SERVER, certfile=None,
            certQuery="/cred/proxyCert?daysValid=",daysValid=2):
    """"""

    if certfile is None:
        certfile = os.path.join(os.getenv("HOME","/tmp"),".ssl/cadcproxy.pem")

    dirname = os.path.dirname(certfile)
    try:
        os.makedirs(dirname)
    except OSError as e:
        if os.path.isdir(dirname):
            pass
        elif e.errno == 20 or e.errno == 17:
            sys.stderr.write(str(e)+": %s \n" % dirname)
            sys.stderr.write("Expected %s to be a directory.\n" % ( dirname))
            sys.exit(e.errno)
        else:
            raise e
    
    # Example taken from voidspace.org.uk
    # create a password manager
    password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()

    (username, passwd) = getUserPassword(host=certHost)

    # Add the username and password.
    # If we knew the realm, we could use it instead of ``None``.
    top_level_url = "http://"+certHost
    password_mgr.add_password(None, top_level_url, username, passwd)
    
    handler = urllib2.HTTPBasicAuthHandler(password_mgr)
    
    # create "opener" (OpenerDirector instance)
    opener = urllib2.build_opener(handler)
    
    # Install the opener.   
    urllib2.install_opener(opener)

    # Now all calls to urllib2.urlopen use our opener.
    url="http://"+certHost+certQuery+str(daysValid)
    r= urllib2.urlopen(url)
    w= file(certfile,'w')
    while True:
        buf=r.read()
        if not buf:
            break
        w.write(buf)
    w.close()
    r.close()
    return
1254370
def certs(self):
        """"""
        return dict([(a, e) for a, e in self.entries.items()
                     if isinstance(e, TrustedCertEntry)])
277955
def ssl_required(allow_non_ssl=False):
    
    def wrapper(view_func):
        def _checkssl(request, *args, **kwargs):
            # allow_non_ssl=True lets non-https requests to come
            # through to this view (and hence not redirect)
            if hasattr(settings, 'SSL_ENABLED') and settings.SSL_ENABLED \
                    and not request.is_secure() and not allow_non_ssl:
                return HttpResponseRedirect(
                    request.build_absolute_uri().replace('http://', 'https://'))
            return view_func(request, *args, **kwargs)

        return _checkssl
    return wrapper
905508
def get_ssl(database):
    

    # Set available keys per engine
    if database['engine'] == 'postgresql':
        keys = ['sslmode', 'sslcert', 'sslkey',
                'sslrootcert', 'sslcrl', 'sslcompression']
    else:
        keys = ['ssl_ca', 'ssl_capath', 'ssl_cert', 'ssl_key',
                'ssl_cipher', 'ssl_check_hostname']

    # Loop thru keys
    ssl = {}
    for key in keys:
        value = database.get(key, None)
        if value is not None:
            ssl[key] = value

    return ssl
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)
1366647
def InitHttp(api_endpoint=None,
             page_size=None,
             auth=None,
             proxies=None,
             verify=None,
             cert=None,
             trust_env=True):
  """"""

  connector = http_connector.HttpConnector(
      api_endpoint=api_endpoint,
      page_size=page_size,
      auth=auth,
      proxies=proxies,
      verify=verify,
      cert=cert,
      trust_env=trust_env)

  return GrrApi(connector=connector)
1275961
def get_certificate
      uri = URI.parse(URI.escape(@host))
      options = { use_ssl: true, verify_mode: OpenSSL::SSL::VERIFY_NONE }
      Net::HTTP.start(uri.host, uri.port, options) do |http|
        http.peer_cert
      end
    end
273167
def ssl?
      @env[Merb::Const::UPCASE_HTTPS] == 'on' || @env[Merb::Const::HTTP_X_FORWARDED_PROTO] == Merb::Const::HTTPS
    end
353022
def _get_certificate(cert_url):
    """"""
    global _cache

    if cert_url in _cache:
        cert = _cache[cert_url]
        if cert.has_expired():
            _cache = {}
        else:
            return cert

    url = urlparse(cert_url)
    host = url.netloc.lower()
    path = posixpath.normpath(url.path)

    # Sanity check location so we don't get some random person's cert.
    if url.scheme != 'https' or \
       host not in ['s3.amazonaws.com', 's3.amazonaws.com:443'] or \
       not path.startswith('/echo.api/'):
        log.error('invalid cert location %s', cert_url)
        return

    resp = urlopen(cert_url)
    if resp.getcode() != 200:
        log.error('failed to download certificate')
        return

    cert = crypto.load_certificate(crypto.FILETYPE_PEM, resp.read())

    if cert.has_expired() or cert.get_subject().CN != 'echo-api.amazon.com':
        log.error('certificate expired or invalid')
        return

    _cache[cert_url] = cert
    return cert
187946
def run(self):
        """"""
        self._listening_sock, self._address = (
            bind_domain_socket(self._address)
            if self._uds_path
            else bind_tcp_socket(self._address))

        if self._ssl:
            certfile = os.path.join(os.path.dirname(__file__), 'server.pem')
            self._listening_sock = _ssl.wrap_socket(
                self._listening_sock,
                certfile=certfile,
                server_side=True)
        self._accept_thread = threading.Thread(target=self._accept_loop)
        self._accept_thread.daemon = True
        self._accept_thread.start()
        return self.port
981352
def request(self, method, url, **kwargs):
        """"""
        if not url.startswith('https'):
            url = '{}{}'.format(self.args.tc_api_path, url)
        return super(TcExSession, self).request(method, url, **kwargs)
1353287
def connect(self):
        """"""
        try:
            context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
            if self.config['no_ssl_verify']:
                requests.packages.urllib3.disable_warnings()
                context.verify_mode = ssl.CERT_NONE
                self.si = SmartConnectNoSSL(
                    host=self.config['server'],
                    user=self.config['username'],
                    pwd=self.config['password'],
                    port=int(self.config['port']),
                    certFile=None,
                    keyFile=None,
                )
            else:
                self.si = SmartConnect(
                    host=self.config['server'],
                    user=self.config['username'],
                    pwd=self.config['password'],
                    port=int(self.config['port']),
                    sslContext=context,
                    certFile=None,
                    keyFile=None,
                )
        except Exception as e:
            print('Unable to connect to vsphere server.')
            print(e)
            sys.exit(1)

        # add a clean up routine
        atexit.register(Disconnect, self.si)

        self.content = self.si.RetrieveContent()
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'])