trust a new PGP key related to a apt-repository
967993
def apt_add_key(keyid, keyserver='keyserver.ubuntu.com', log=False):
    
    if log:
        log_green(
            'trusting keyid %s from %s' % (keyid, keyserver)
        )
    with settings(hide('warnings', 'running', 'stdout')):
        sudo('apt-key adv --keyserver %s --recv %s' % (keyserver, keyid))
    return True
904240
def install_PMK(self):
        """"""
        self.pmk = PBKDF2HMAC(
            algorithm=hashes.SHA1(),
            length=32,
            salt=self.ssid.encode(),
            iterations=4096,
            backend=default_backend(),
        ).derive(self.passphrase.encode())
1361835
def init_gpg(self):
        
        if self.gpg_verify:
            logger.debug("gpg verification enabled, initializing gpg")
            gpg_home = os.path.expanduser('~/.gnupg')
            self.gpg = gnupg.GPG(gnupghome=gpg_home)
            self.key_path, self.key_info = self.get_signing_key()
            logger.debug("{0} {1}".format(self.key_path, self.key_info))
            self.check_signing_key()
1156336
def _key_from_req(req):
    """"""
    if hasattr(req, 'key'):
        # from pkg_resources, such as installed dists for pip-sync
        key = req.key
    else:
        # from packaging, such as install requirements from requirements.txt
        key = req.name

    key = key.replace('_', '-').lower()
    return key
1175621
def import_keybase(useropt):
    """"""
    public_key = None
    u_bits = useropt.split(':')
    username = u_bits[0]
    if len(u_bits) == 1:
        public_key = cryptorito.key_from_keybase(username)
    else:
        fingerprint = u_bits[1]
        public_key = cryptorito.key_from_keybase(username, fingerprint)

    if cryptorito.has_gpg_key(public_key['fingerprint']):
        sys.exit(2)

    cryptorito.import_gpg_key(public_key['bundle'].encode('ascii'))
    sys.exit(0)
235146
def pkginfo(name, version, arch, repoid, install_date=None, install_date_time_t=None):
    '''
    
    '''
    pkginfo_tuple = collections.namedtuple(
        'PkgInfo',
        ('name', 'version', 'arch', 'repoid', 'install_date',
         'install_date_time_t')
    )
    return pkginfo_tuple(name, version, arch, repoid, install_date,
                         install_date_time_t)
1066568
def import_public_key(line):
    """"""
    log.debug('loading SSH public key: %r', line)
    file_type, base64blob, name = line.split()
    blob = base64.b64decode(base64blob)
    result = parse_pubkey(blob)
    result['name'] = name.encode('utf-8')
    assert result['type'] == file_type.encode('ascii')
    log.debug('loaded %s public key: %s', file_type, result['fingerprint'])
    return result
924628
function _rawGithubUrl (resolvedPackageRoot) {
  var { packageJson, relativeFile } = resolvedPackageRoot
  const orgRepo = _githubOrgRepo(packageJson && packageJson.repository && packageJson.repository.url)
  if (orgRepo) {
    return `https://raw.githubusercontent.com/${orgRepo}/v${packageJson.version}/${relativeFile}`
  }
}
161075
def keypair_add(name, pubfile=None, pubkey=None, profile=None, **kwargs):
    '''
    
    '''
    conn = _auth(profile, **kwargs)
    return conn.keypair_add(
        name,
        pubfile,
        pubkey
    )
945513
def install_package(self, client, package):
        """"""
        install_cmd = "{sudo} '{install} {package}'".format(
            sudo=self.get_sudo_exec_wrapper(),
            install=self.get_install_cmd(),
            package=package
        )

        try:
            out = ipa_utils.execute_ssh_command(
                client,
                install_cmd
            )
        except Exception as error:
            raise IpaDistroException(
                'An error occurred installing package {package} '
                'on instance: {error}'.format(
                    package=package,
                    error=error
                )
            )
        else:
            return out
1222770
def verify_pubkey_sig(self, message, sig):
        '''
        
        '''
        if self.opts['master_sign_key_name']:
            path = os.path.join(self.opts['pki_dir'],
                                self.opts['master_sign_key_name'] + '.pub')

            if os.path.isfile(path):
                res = verify_signature(path,
                                       message,
                                       binascii.a2b_base64(sig))
            else:
                log.error(
                    'Verification public key %s does not exist. You need to '
                    'copy it from the master to the minions pki directory',
                    os.path.basename(path)
                )
                return False
            if res:
                log.debug(
                    'Successfully verified signature of master public key '
                    'with verification public key %s',
                    self.opts['master_sign_key_name'] + '.pub'
                )
                return True
            else:
                log.debug('Failed to verify signature of public key')
                return False
        else:
            log.error(
                'Failed to verify the signature of the message because the '
                'verification key-pairs name is not defined. Please make '
                'sure that master_sign_key_name is defined.'
            )
            return False
569825
def connect(self):
        """"""
        log.critical('NEVER USE THIS CODE FOR REAL-LIFE USE-CASES!!!')
        log.critical('ONLY FOR DEBUGGING AND TESTING!!!')
        # The code below uses HARD-CODED secret key - and should be used ONLY
        # for GnuPG integration tests (e.g. when no real device is available).
        # pylint: disable=attribute-defined-outside-init
        self.secexp = 1
        self.sk = ecdsa.SigningKey.from_secret_exponent(
            secexp=self.secexp, curve=ecdsa.curves.NIST256p, hashfunc=hashlib.sha256)
        self.vk = self.sk.get_verifying_key()
        return self
901711
def apt_upgrade(options=None, fatal=False, dist=False):
    """"""
    if options is None:
        options = ['--option=Dpkg::Options::=--force-confold']

    cmd = ['apt-get', '--assume-yes']
    cmd.extend(options)
    if dist:
        cmd.append('dist-upgrade')
    else:
        cmd.append('upgrade')
    log("Upgrading with options: {}".format(options))
    _run_apt_command(cmd, fatal)
755996
def install_from_repo(pkgname, plugin_type, install_path, register_func):
    """"""
    rsession = requests.Session()
    rsession.mount("https://", HTTPAdapter(max_retries=3))

    logger.debug("trying to install %s from online repo", pkgname)
    pkgurl = "{}/{}s/{}.zip".format(defs.GITHUB_RAW, plugin_type, pkgname)
    try:
        logger.debug("Requesting HTTP HEAD: %s", pkgurl)
        r = rsession.head(pkgurl)
        r.raise_for_status()
        total_size = int(r.headers.get("content-length", 0))
        pkgsize = _sizeof_fmt(total_size)
        with click.progressbar(length=total_size, label="Downloading {} {} ({}).."
                               .format(plugin_type, pkgname, pkgsize)) as bar:
            r = rsession.get(pkgurl, stream=True)
            with tempfile.NamedTemporaryFile(delete=False) as f:
                downloaded_bytes = 0
                for chunk in r.iter_content(chunk_size=1):  # TODO: Consider increasing to reduce cycles
                    if chunk:
                        f.write(chunk)
                        downloaded_bytes += len(chunk)
                        bar.update(downloaded_bytes)
        return install_from_zip(f.name, install_path, register_func, delete_after_install=True)
    except requests.exceptions.HTTPError as exc:
        logger.debug(str(exc))
        raise exceptions.PluginNotFoundInOnlineRepo(pkgname)
    except requests.exceptions.ConnectionError as exc:
        logger.debug(str(exc))
        raise exceptions.PluginRepoConnectionError()
75403
def import_gpg_key(key):
    """"""
    if not key:
        raise CryptoritoError('Invalid GPG Key')

    key_fd, key_filename = mkstemp("cryptorito-gpg-import")
    key_handle = os.fdopen(key_fd, 'w')

    key_handle.write(polite_string(key))
    key_handle.close()
    cmd = flatten([gnupg_bin(), gnupg_home(), "--import", key_filename])
    output = stderr_output(cmd)
    msg = 'gpg: Total number processed: 1'
    output_bits = polite_string(output).split('\n')
    return len([line for line in output_bits if line == msg]) == 1
136711
def _verify_install(desired, new_pkgs, ignore_epoch=False, new_caps=None):
    '''
    
    '''
    ok = []
    failed = []
    if not new_caps:
        new_caps = dict()
    for pkgname, pkgver in desired.items():
        # FreeBSD pkg supports `openjdk` and `java/openjdk7` package names.
        # Homebrew for Mac OSX does something similar with tap names
        # prefixing package names, separated with a slash.
        has_origin = '/' in pkgname

        if __grains__['os'] == 'FreeBSD' and has_origin:
            cver = [k for k, v in six.iteritems(new_pkgs) if v['origin'] == pkgname]
        elif __grains__['os'] == 'MacOS' and has_origin:
            cver = new_pkgs.get(pkgname, new_pkgs.get(pkgname.split('/')[-1]))
        elif __grains__['os'] == 'OpenBSD':
            cver = new_pkgs.get(pkgname.split('%')[0])
        elif __grains__['os_family'] == 'Debian':
            cver = new_pkgs.get(pkgname.split('=')[0])
        else:
            cver = new_pkgs.get(pkgname)
            if not cver and pkgname in new_caps:
                cver = new_pkgs.get(new_caps.get(pkgname)[0])

        if not cver:
            failed.append(pkgname)
            continue
        elif pkgver == 'latest':
            ok.append(pkgname)
            continue
        elif not __salt__['pkg_resource.version_clean'](pkgver):
            ok.append(pkgname)
            continue
        elif pkgver.endswith("*") and cver[0].startswith(pkgver[:-1]):
            ok.append(pkgname)
            continue
        if _fulfills_version_string(cver, pkgver, ignore_epoch=ignore_epoch):
            ok.append(pkgname)
        else:
            failed.append(pkgname)
    return ok, failed
1254864
def _preflight_check(desired, fromrepo, **kwargs):
    '''
    
    '''
    if 'pkg.check_db' not in __salt__:
        return {}
    ret = {'suggest': {}, 'no_suggest': []}
    pkginfo = __salt__['pkg.check_db'](
        *list(desired.keys()), fromrepo=fromrepo, **kwargs
    )
    for pkgname in pkginfo:
        if pkginfo[pkgname]['found'] is False:
            if pkginfo[pkgname]['suggestions']:
                ret['suggest'][pkgname] = pkginfo[pkgname]['suggestions']
            else:
                ret['no_suggest'].append(pkgname)
    return ret