Show certificate requests for this API key

    CLI Example:

    .. code-block:: bash

        salt-run venafi.show_cert 01234567-89ab-cdef-0123-456789abcdef
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
224128
def get_certificate(self, certificate_id):
        
        api = self._get_api(iam.DeveloperApi)
        certificate = Certificate(api.get_certificate(certificate_id))
        self._extend_certificate(certificate)
        return certificate
795688
def show_input_endpoint(kwargs=None, conn=None, call=None):
    '''
    
    '''
    if call != 'function':
        raise SaltCloudSystemExit(
            'The show_input_endpoint function must be called with -f or --function.'
        )

    if kwargs is None:
        kwargs = {}

    if 'name' not in kwargs:
        raise SaltCloudSystemExit('An endpoint name must be specified as "name"')

    data = list_input_endpoints(kwargs=kwargs, call='function')
    return data.get(kwargs['name'], None)
565998
def query_certificate(self, cert_hash):
        
        try:
            cquery = self.pssl.query_cert(cert_hash)
        except Exception:
            self.error('Exception during processing with passiveSSL. '
                       'This happens if the given hash is not sha1 or contains dashes/colons etc. '
                       'Please make sure to submit a clean formatted sha1 hash.')

        # fetch_cert raises an error if no certificate was found.
        try:
            cfetch = self.pssl.fetch_cert(cert_hash, make_datetime=False)
        except Exception:
            cfetch = {}

        return {'query': cquery,
                'cert': cfetch}
657292
def query(path, method='GET', data=None, params=None, header_dict=None, decode=True):
    '''
    
    '''
    certificate_path = config.get_cloud_config_value(
        'certificate_path',
        get_configured_provider(), __opts__, search_global=False
    )
    subscription_id = salt.utils.stringutils.to_str(
        config.get_cloud_config_value(
            'subscription_id',
            get_configured_provider(), __opts__, search_global=False
        )
    )
    management_host = config.get_cloud_config_value(
        'management_host',
        get_configured_provider(),
        __opts__,
        search_global=False,
        default='management.core.windows.net'
    )
    backend = config.get_cloud_config_value(
        'backend',
        get_configured_provider(), __opts__, search_global=False
    )
    url = 'https://{management_host}/{subscription_id}/{path}'.format(
        management_host=management_host,
        subscription_id=subscription_id,
        path=path,
    )

    if header_dict is None:
        header_dict = {}

    header_dict['x-ms-version'] = '2014-06-01'

    result = salt.utils.http.query(
        url,
        method=method,
        params=params,
        data=data,
        header_dict=header_dict,
        port=443,
        text=True,
        cert=certificate_path,
        backend=backend,
        decode=decode,
        decode_type='xml',
    )
    if 'dict' in result:
        return result['dict']
    return
7389
def get_cert(zappa_instance, log=LOGGER, CA=DEFAULT_CA):
    
    out = parse_account_key()
    header = get_boulder_header(out)
    accountkey_json = json.dumps(header['jwk'], sort_keys=True, separators=(',', ':'))
    thumbprint = _b64(hashlib.sha256(accountkey_json.encode('utf8')).digest())

    # find domains
    domains = parse_csr()

    # get the certificate domains and expiration
    register_account()

    # verify each domain
    for domain in domains:
        log.info("Verifying {0}...".format(domain))

        # get new challenge
        code, result = _send_signed_request(CA + "/acme/new-authz", {
            "resource": "new-authz",
            "identifier": {"type": "dns", "value": domain},
        })
        if code != 201:
            raise ValueError("Error requesting challenges: {0} {1}".format(code, result))

        challenge = [ch for ch in json.loads(result.decode('utf8'))['challenges'] if ch['type'] == "dns-01"][0]
        token = re.sub(r"[^A-Za-z0-9_\-]", "_", challenge['token'])
        keyauthorization = "{0}.{1}".format(token, thumbprint).encode('utf-8')

        # sha256_b64
        digest = _b64(hashlib.sha256(keyauthorization).digest())

        zone_id = zappa_instance.get_hosted_zone_id_for_domain(domain)
        if not zone_id:
            raise ValueError("Could not find Zone ID for: " + domain)
        zappa_instance.set_dns_challenge_txt(zone_id, domain, digest)  # resp is unused

        print("Waiting for DNS to propagate..")

        # What's optimal here?
        # import time  # double import; import in loop; shadowed import
        time.sleep(45)

        # notify challenge are met
        code, result = _send_signed_request(challenge['uri'], {
            "resource": "challenge",
            "keyAuthorization": keyauthorization.decode('utf-8'),
        })
        if code != 202:
            raise ValueError("Error triggering challenge: {0} {1}".format(code, result))

        # wait for challenge to be verified
        verify_challenge(challenge['uri'])

        # Challenge verified, clean up R53
        zappa_instance.remove_dns_challenge_txt(zone_id, domain, digest)

    # Sign
    result = sign_certificate()
    # Encode to PEM format
    encode_certificate(result)

    return True
743681
def certs
      unless @@certs
        pattern = /-{5}BEGIN CERTIFICATE-{5}\n.*?-{5}END CERTIFICATE-{5}\n/m
        dir = @cert_directory
        certs = Dir[File.join(dir, '*.crt')].map {|f| File.read(f) }
        certs = certs.map {|c| c.scan(pattern) }.flatten
        certs.map! {|c| OpenSSL::X509::Certificate.new(c) }
        @@certs = certs.reject {|c| c.not_after < Time.now }
      end
      @@certs
    end
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
926385
def _verify_cert(self, sock: ssl.SSLSocket):
        ''''''
        # Based on tornado.iostream.SSLIOStream
        # Needed for older OpenSSL (<0.9.8f) versions
        verify_mode = self._ssl_context.verify_mode

        assert verify_mode in (ssl.CERT_NONE, ssl.CERT_REQUIRED,
                               ssl.CERT_OPTIONAL), \
            'Unknown verify mode {}'.format(verify_mode)

        if verify_mode == ssl.CERT_NONE:
            return

        cert = sock.getpeercert()

        if not cert and verify_mode == ssl.CERT_OPTIONAL:
            return

        if not cert:
            raise SSLVerificationError('No SSL certificate given')

        try:
            ssl.match_hostname(cert, self._hostname)
        except ssl.CertificateError as error:
            raise SSLVerificationError('Invalid SSL certificate') from error
141315
def get_certificate(self, **kwargs):
        
        response = self._send(http_method='GET',
                              location_id='2e0dbce7-a327-4bc0-a291-056139393f6d',
                              version='5.0-preview.1',
                              accept_media_type='application/octet-stream')
        if "callback" in kwargs:
            callback = kwargs["callback"]
        else:
            callback = None
        return self._client.stream_download(response, callback=callback)
449108
def der_cert(der_data):
    
    if isinstance(der_data, str):
        der_data = bytes(der_data, 'utf-8')
    return x509.load_der_x509_certificate(der_data, default_backend())
923079
def _query(action=None,
           command=None,
           args=None,
           method='GET',
           header_dict=None,
           data=None):
    '''
    
    '''
    vm_ = get_configured_provider()
    apikey = config.get_cloud_config_value(
        'apikey', vm_, __opts__, search_global=False
    )
    sharedsecret = config.get_cloud_config_value(
        'sharedsecret', vm_, __opts__, search_global=False
    )

    path = 'https://api.gogrid.com/api/'

    if action:
        path += action

    if command:
        path += '/{0}'.format(command)

    log.debug('GoGrid URL: %s', path)

    if not isinstance(args, dict):
        args = {}

    epoch = six.text_type(int(time.time()))
    hashtext = ''.join((apikey, sharedsecret, epoch))
    args['sig'] = salt.utils.hashutils.md5_digest(hashtext)
    args['format'] = 'json'
    args['v'] = '1.0'
    args['api_key'] = apikey

    if header_dict is None:
        header_dict = {}

    if method != 'POST':
        header_dict['Accept'] = 'application/json'

    decode = True
    if method == 'DELETE':
        decode = False

    return_content = None
    result = salt.utils.http.query(
        path,
        method,
        params=args,
        data=data,
        header_dict=header_dict,
        decode=decode,
        decode_type='json',
        text=True,
        status=True,
        opts=__opts__,
    )
    log.debug('GoGrid Response Status Code: %s', result['status'])

    return result['dict']
423114
def _get_cached_certs(cert_uri, cache):
  
  certs = cache.get(cert_uri, namespace=_CERT_NAMESPACE)
  if certs is None:
    _logger.debug('Cert cache miss for %s', cert_uri)
    try:
      result = urlfetch.fetch(cert_uri)
    except AssertionError:
      # This happens in unit tests.  Act as if we couldn't get any certs.
      return None

    if result.status_code == 200:
      certs = json.loads(result.content)
      expiration_time_seconds = _get_cert_expiration_time(result.headers)
      if expiration_time_seconds:
        cache.set(cert_uri, certs, time=expiration_time_seconds,
                  namespace=_CERT_NAMESPACE)
    else:
      _logger.error(
          'Certs not available, HTTP request returned %d', result.status_code)

  return certs
28376
def __get_request_auth(username, password):
    '''
    
    '''

    # pylint: disable=unused-argument
    def __request_auth(credentials, user_data):
        '''Callback method passed to libvirt.openAuth().

        The credentials argument is a list of credentials that libvirt
        would like to request. An element of this list is a list containing
        5 items (4 inputs, 1 output):
          - the credential type, e.g. libvirt.VIR_CRED_AUTHNAME
          - a prompt to be displayed to the user
          - a challenge
          - a default result for the request
          - a place to store the actual result for the request

        The user_data argument is currently not set in the openAuth call.
        '''
        for credential in credentials:
            if credential[0] == libvirt.VIR_CRED_AUTHNAME:
                credential[4] = username if username else \
                                __salt__['config.get']('virt:connection:auth:username', credential[3])
            elif credential[0] == libvirt.VIR_CRED_NOECHOPROMPT:
                credential[4] = password if password else \
                                __salt__['config.get']('virt:connection:auth:password', credential[3])
            else:
                log.info('Unhandled credential type: %s', credential[0])
        return 0
1089637
def cert
      @cert ||= OpenSSL::X509::Certificate.new.tap do |c|
        c.subject = c.issuer = OpenSSL::X509::Name.parse(cert_subject)
        c.not_before = Time.now
        c.not_after = Time.now + 365 * 24 * 60 * 60
        c.public_key = cert_key
        c.serial = 0x1
        c.version = 0x0
        c.sign cert_key, ::U2F::DIGEST.new
      end
    end
837864
def list_certs(keychain="/Library/Keychains/System.keychain"):
    '''
    
    '''
    cmd = 'security find-certificate -a {0} | grep -o "alis".*\\" | ' \
          'grep -o \'\\"[-A-Za-z0-9.:() ]*\\"\''.format(_quote(keychain))
    out = __salt__['cmd.run'](cmd, python_shell=True)
    return out.replace('"', '').split('\n')
1074344
def check_key_cert_match(keyfile, certfile):
    
    key_modulus = subprocess.check_output(
        'openssl rsa -noout -modulus -in {}'.format(keyfile),
        shell=True)
    cert_modulus = subprocess.check_output(
        'openssl x509 -noout -modulus -in {}'.format(certfile),
        shell=True)
    return key_modulus == cert_modulus