Python gnupg.GPG Examples

The following are 30 code examples of gnupg.GPG(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module gnupg , or try the search function .
Example #1
Source File: fs.py    From edx-analytics-pipeline with GNU Affero General Public License v3.0 7 votes vote down vote up
def decrypt_file(encrypted_filename, decrypted_filename, key_filename='insecure_secret.key'):
    """
    Decrypts an encrypted file.

    Arguments:
        encrypted_filename (str): The full path to the PGP encrypted file.
        decrypted_filename (str): The full path of the the file to write the decrypted data to.
        key_filename (str): The name of the key file to use to decrypt the data. It should correspond to one of the
            keys found in the gpg-keys directory.

    """
    gpg_home_dir = tempfile.mkdtemp()
    try:
        gpg = gnupg.GPG(gnupghome=gpg_home_dir)
        gpg.encoding = 'utf-8'
        with open(os.path.join('gpg-keys', key_filename), 'r') as key_file:
            gpg.import_keys(key_file.read())

        with open(encrypted_filename, 'r') as encrypted_file:
            gpg.decrypt_file(encrypted_file, output=decrypted_filename)
    finally:
        shutil.rmtree(gpg_home_dir) 
Example #2
Source File: gpg.py    From passpy with GNU General Public License v3.0 7 votes vote down vote up
def _reencrypt_key(path, gpg, gpg_recipients):
    """Reencrypt a single key.

    Gets called from :func:`passpy.gpg._reencrypt_path`.

    :param str path: The path to a gpg encrypted file.

    :param gpg: The gpg object.
    :type gpg: :class:`gnupg.GPG`

    :param list gpg_recipients: The list of GPG Ids to encrypt the key
        with.

    """
    with open(path, 'rb') as key_file:
        key_data = gpg.decrypt_file(key_file).data
    key_data_enc = gpg.encrypt(key_data, gpg_recipients).data
    with open(path, 'wb') as key_file:
        key_file.write(key_data_enc) 
Example #3
Source File: profile.py    From OpenBazaar-Server with MIT License 7 votes vote down vote up
def add_pgp_key(self, public_key, signature, guid):
        """
        Adds a pgp public key to the profile. The user must have submitted a
        valid signature covering the guid otherwise the key will not be added to
        the profile.
        """
        gpg = gnupg.GPG()
        gpg.import_keys(public_key)
        if gpg.verify(signature) and guid in signature:
            p = self.profile.PublicKey()
            p.public_key = public_key
            p.signature = signature
            self.profile.pgp_key.MergeFrom(p)
            self.db.profile.set_proto(self.profile.SerializeToString())
            return True
        else:
            return False 
Example #4
Source File: repository.py    From margaritashotgun with MIT License 7 votes vote down vote up
def prompt_for_install(self):
        """
        Prompt user to install untrusted repo signing key
        """
        print(self.key_info)
        repo_key_url = "{0}/{1}".format(self.url, self.repo_signing_key)
        print(("warning: Repository key untrusted \n"
               "Importing GPG key 0x{0}:\n"
               "  Userid: \"{1}\"\n"
               "  From  : {2}".format(self.key_info['fingerprint'],
                                      self.key_info['uids'][0],
                                      repo_key_url)))
        response = prompt(u'Is this ok: [y/N] ')
        if response == 'y':
            self.install_key(self.raw_key)
            return True
        else:
            return False 
Example #5
Source File: gpg.py    From passpy with GNU General Public License v3.0 6 votes vote down vote up
def read_key(path, gpg_bin, gpg_opts):
    """Read and decrypt a single key file.

    :param str path: The path to the key to decrypt.

    :param str gpg_bin: The path to the gpg binary.

    :param list gpg_opts: The options for gpg.

    :rtype: str
    :returns: The unencrypted content of the file at `path`.

    """
    gpg = GPG(gpgbinary=gpg_bin, options=gpg_opts)
    with open(path, 'rb') as key_file:
        return str(gpg.decrypt_file(key_file)) 
Example #6
Source File: gpg.py    From passpy with GNU General Public License v3.0 6 votes vote down vote up
def write_key(path, key_data, gpg_bin, gpg_opts):
    """Encrypt and write a single key file.

    :param str path: The path to the key to decrypt.

    :param str gpg_bin: The path to the gpg binary.

    :param list gpg_opts: The options for gpg.

    """
    gpg = GPG(gpgbinary=gpg_bin, options=gpg_opts)
    gpg_recipients = _get_gpg_recipients(path)
    # pass always ends it's files with an endline
    if not key_data.endswith('\n'):
        key_data += '\n'
    key_data_enc = gpg.encrypt(key_data, gpg_recipients).data
    with open(path, 'wb') as key_file:
        key_file.write(key_data_enc) 
Example #7
Source File: repo.py    From TagBot with MIT License 6 votes vote down vote up
def configure_gpg(self, key: str, password: Optional[str]) -> None:
        """Configure the repo to sign tags with GPG."""
        home = os.environ["GNUPGHOME"] = mkdtemp(prefix="tagbot_gpg_")
        os.chmod(home, S_IREAD | S_IWRITE | S_IEXEC)
        logger.debug(f"Set GNUPGHOME to {home}")
        gpg = GPG(gnupghome=home, use_agent=True)
        # For some reason, this doesn't require the password even though the CLI does.
        import_result = gpg.import_keys(self._maybe_b64(key))
        if import_result.sec_imported != 1:
            logger.warning(import_result.stderr)
            raise Abort("Importing key failed")
        key_id = import_result.fingerprints[0]
        logger.debug(f"GPG key ID: {key_id}")
        if password:
            # Sign some dummy data to put our password into the GPG agent,
            # so that we don't need to supply the password when we create a tag.
            sign_result = gpg.sign("test", passphrase=password)
            if sign_result.status != "signature created":
                logger.warning(sign_result.stderr)
                raise Abort("Testing GPG key failed")
        self._git.config("user.signingKey", key_id)
        self._git.config("tag.gpgSign", "true") 
Example #8
Source File: network.py    From OpenBazaar-Server with MIT License 6 votes vote down vote up
def get_profile(self, node_to_ask):
        """
        Downloads the profile from the given node. If the images do not already
        exist in cache, it will download and cache them before returning the profile.
        """

        def get_result(result):
            try:
                verify_key = nacl.signing.VerifyKey(node_to_ask.pubkey)
                verify_key.verify(result[1][0], result[1][1])
                p = objects.Profile()
                p.ParseFromString(result[1][0])
                if p.pgp_key.public_key:
                    gpg = gnupg.GPG()
                    gpg.import_keys(p.pgp_key.publicKey)
                    if not gpg.verify(p.pgp_key.signature) or \
                                    node_to_ask.id.encode('hex') not in p.pgp_key.signature:
                        p.ClearField("pgp_key")
                if not os.path.isfile(os.path.join(DATA_FOLDER, 'cache', p.avatar_hash.encode("hex"))):
                    self.get_image(node_to_ask, p.avatar_hash)
                if not os.path.isfile(os.path.join(DATA_FOLDER, 'cache', p.header_hash.encode("hex"))):
                    self.get_image(node_to_ask, p.header_hash)
                self.cache(result[1][0], node_to_ask.id.encode("hex") + ".profile")
                return p
            except Exception:
                return None

        if node_to_ask.ip is None:
            return defer.succeed(None)
        self.log.info("fetching profile from %s" % node_to_ask)
        d = self.protocol.callGetProfile(node_to_ask)
        return d.addCallback(get_result) 
Example #9
Source File: importotp.py    From privacyidea with GNU Affero General Public License v3.0 6 votes vote down vote up
def get_publickeys(self):
        """
        This returns the public GPG key to be displayed in the Import Dialog.
        The administrator can send this public key to his token vendor and
        the token vendor can use this public key to encrypt the token import
        file.
        :return: a dictionary of public keys with fingerprint
        """
        public_keys = {}
        if path.isdir(self.gnupg_home):
            keys = self.gpg.list_keys(secret=True)
        else:
            keys = []
            log.warning(u"Directory {} does not exists!".format(self.gnupg_home))

        for key in keys:
            ascii_armored_public_key = self.gpg.export_keys(key.get("keyid"))
            public_keys[key.get("keyid")] = {"armor": ascii_armored_public_key,
                                             "fingerprint": key.get(
                                                 "fingerprint")}
        return public_keys 
Example #10
Source File: decrypt_eval_data.py    From callisto-core with GNU Affero General Public License v3.0 6 votes vote down vote up
def _decrypt(self):
        decrypted_eval_data = []
        for row in EvalRow.objects.all():
            decrypted_row = {
                "pk": row.pk,
                "user": row.user_identifier,
                "record": row.record_identifier,
                "action": row.action,
                "timestamp": row.timestamp.__str__(),
            }
            gpg = gnupg.GPG()
            gpg.import_keys(settings.CALLISTO_EVAL_PRIVATE_KEY)
            decrypted_eval_row = six.text_type(gpg.decrypt(six.binary_type(row.row)))
            if decrypted_eval_row:
                decrypted_row.update(json.loads(decrypted_eval_row))
            decrypted_eval_data.append(decrypted_row)
        return decrypted_eval_data 
Example #11
Source File: test_security.py    From packit with MIT License 6 votes vote down vote up
def test_check_signature_of_commit_key_not_found():
    gpg_flexmock = flexmock(GPG)

    # No key present
    gpg_flexmock.should_receive("list_keys").and_return(flexmock(fingerprints=[]))

    # No key received
    gpg_flexmock.should_receive("recv_keys").and_return(flexmock(fingerprints=[]))

    # Signature cannot be checked
    repo_mock = flexmock(git=flexmock().should_receive("show").and_return("E").mock())

    verifier = CommitVerifier()
    with pytest.raises(PackitException) as ex:
        verifier.check_signature_of_commit(
            commit=flexmock(hexsha="abcd", repo=repo_mock),
            possible_key_fingerprints=["a"],
        )
    assert "Cannot receive" in str(ex)


# This could possibly but unlikely fail if all the default key servers are down. 
Example #12
Source File: api.py    From callisto-core with GNU Affero General Public License v3.0 5 votes vote down vote up
def _encrypt_file(self, file_data, public_key):
        gpg = gnupg.GPG()
        imported_keys = gpg.import_keys(public_key)
        return gpg.encrypt(
            file_data, imported_keys.fingerprints[0], armor=True, always_trust=True
        ).data

    # send cycle 
Example #13
Source File: updates.py    From core with GNU General Public License v3.0 5 votes vote down vote up
def check_updates():
    """Check for updates from arkOS repo server."""
    updates = []
    gpg = gnupg.GPG()
    server = config.get("general", "repo_server")
    current = config.get("updates", "current_update")
    # Fetch updates from registry server
    api_url = "https://{0}/api/v1/updates/{1}"
    data = api(api_url.format(server, str(current)), crit=True)
    for x in data["updates"]:
        ustr, u = str(x["tasks"]), json.loads(x["tasks"])
        # Get the update signature and test it
        sig_url = "https://{0}/api/v1/signatures/{1}"
        sig = api(sig_url.format(server, x["id"]), returns="raw", crit=True)
        with open("/tmp/{0}.sig".format(x["id"]), "w") as f:
            f.write(sig)
        v = gpg.verify_data("/tmp/{0}.sig".format(x["id"]), ustr)
        if v.trust_level is None:
            err_str = "Update {0} signature verification failed"
            logger.error("Updates", err_str.format(x["id"]))
            break
        else:
            data = {"id": x["id"], "name": x["name"], "date": x["date"],
                    "info": x["info"], "tasks": u}
            updates.append(data)
    storage.updates = {x.id: x for x in updates}
    return updates 
Example #14
Source File: model_helpers.py    From callisto-core with GNU Affero General Public License v3.0 5 votes vote down vote up
def gpg_encrypt_data(data, key):
    data_string = json.dumps(data)
    gpg = gnupg.GPG()
    imported_keys = gpg.import_keys(key)
    encrypted = gpg.encrypt(
        data_string, imported_keys.fingerprints[0], armor=True, always_trust=True
    )
    return encrypted.data 
Example #15
Source File: submit_debug_info.py    From st2 with Apache License 2.0 5 votes vote down vote up
def encrypt_archive(self, archive_file_path):
        """
        Encrypt archive with debugging information using our public key.

        :param archive_file_path: Path to the non-encrypted tarball file.
        :type archive_file_path: ``str``

        :return: Path to the encrypted archive.
        :rtype: ``str``
        """
        try:
            assert archive_file_path.endswith('.tar.gz')

            LOG.info('Encrypting tarball...')
            gpg = gnupg.GPG(verbose=self.debug)

            # Import our public key
            import_result = gpg.import_keys(self.gpg_key)
            # pylint: disable=no-member
            assert import_result.count == 1

            encrypted_archive_output_file_name = os.path.basename(archive_file_path) + '.asc'
            encrypted_archive_output_file_path = os.path.join('/tmp',
                                                              encrypted_archive_output_file_name)
            with open(archive_file_path, 'rb') as fp:
                gpg.encrypt_file(file=fp,
                                 recipients=self.gpg_key_fingerprint,
                                 always_trust=True,
                                 output=encrypted_archive_output_file_path)
            return encrypted_archive_output_file_path
        except Exception as e:
            LOG.exception('Failed to encrypt archive', exc_info=True)
            raise e 
Example #16
Source File: test_encrypt.py    From edx-analytics-pipeline with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_decrypted_data(self, input_file, key_file_target):
        """Decrypts contents of input, and writes to output file object open for writing."""
        with make_temp_directory(prefix="decrypt") as temp_dir:
            # Use temp directory to hold gpg keys.
            gpg_instance = gnupg.GPG(gnupghome=temp_dir)
            _import_key_files(gpg_instance, [key_file_target])
            decrypted_data = gpg_instance.decrypt_file(input_file, always_trust=True)
            return decrypted_data 
Example #17
Source File: encrypt.py    From edx-analytics-pipeline with GNU Affero General Public License v3.0 5 votes vote down vote up
def _import_key_files(gpg_instance, key_file_targets, hadoop_counter_incr_func=DEFAULT_HADOOP_COUNTER_FUNC):
    """
    Load key-file targets into the GPG instance.

    This writes files in the home directory of the instance.
    """
    for key_file_target in key_file_targets:
        log.info("Importing keyfile from %s", key_file_target.path)
        import_result = gpg_instance.import_keys(get_key_from_target(key_file_target))

        for key_fingerprint in import_result.fingerprints:
            pub_keys = gpg_instance.list_keys()
            for test_key in pub_keys:
                if test_key["fingerprint"] == key_fingerprint:
                    if len(test_key["expires"]) > 0:
                        current_time = datetime.datetime.now()
                        next_week = current_time + datetime.timedelta(days=7)
                        key_expire = datetime.datetime.fromtimestamp(int(test_key["expires"]))

                        if current_time > key_expire:
                            # Ignore this error for now because a more serious and appropriate IOException will be
                            # generated when the key is used for encryption
                            log.error("Error key with fingerprint: '%s' and recipient '%s' has expired!!!",
                                      key_fingerprint, test_key["uids"])
                            for recipient in test_key["uids"]:
                                # Luigi requires that hadoop counter names be ascii-encoded, not unicode.
                                hadoop_counter_incr_func("GPG Key for {} has expired".format(recipient.encode("ascii", "replace")))
                                hadoop_counter_incr_func("Keys expired")
                        elif next_week > key_expire:
                            log.info("Warning key with fingerprint: " +
                                     "'%s' and recipient '%s' will expire in the next week",
                                     key_fingerprint, test_key["uids"])
                            for recipient in test_key["uids"]:
                                # Luigi requires that hadoop counter names be ascii-encoded, not unicode.
                                hadoop_counter_incr_func("GPG Key for {} is near expiry".format(recipient.encode("ascii", "replace")))
                                hadoop_counter_incr_func("Keys expiring") 
Example #18
Source File: encrypt.py    From edx-analytics-pipeline with GNU Affero General Public License v3.0 5 votes vote down vote up
def make_encrypted_file(output_file, key_file_targets, recipients=None, progress=None, dir=None,
                        hadoop_counter_incr_func=DEFAULT_HADOOP_COUNTER_FUNC):
    """
    Creates a file object to be written to, whose contents will afterwards be encrypted.

    Parameters:
        output_file:  a file object, opened for writing.
        key_file_targets: a list of luigi.Target objects defining the gpg public key files to be loaded.
        recipients:  an optional list of recipients to be loaded.  If not specified, uses all loaded keys.
        progress:  a function that is called periodically as progress is made.
        hadoop_counter_incr_func:  A callback to a function that can generate MR counters so that non-critical GPG
            messages can be promoted to a visible section of the MR run log.
    """
    with make_temp_directory(prefix="encrypt", dir=dir) as temp_dir:
        # Use temp directory to hold gpg keys.
        gpg = gnupg.GPG(gnupghome=temp_dir)
        gpg.encoding = 'utf-8'
        _import_key_files(gpg_instance=gpg, key_file_targets=key_file_targets,
                          hadoop_counter_incr_func=hadoop_counter_incr_func)

        # Create a temp file to contain the unencrypted output, in the same temp directory.
        with tempfile.NamedTemporaryFile(dir=temp_dir, delete=False) as temp_input_file:
            temp_input_filepath = temp_input_file.name
            log.info('Writing data to temporary file: %s', temp_input_filepath)
            yield temp_input_file

        # Encryption produces a second file in the same temp directory.
        temp_encrypted_filepath = "{filepath}.gpg".format(filepath=temp_input_filepath)
        if recipients is None:
            recipients = [key['keyid'] for key in gpg.list_keys()]
        with open(temp_input_filepath, 'r') as temp_input_file:
            _encrypt_file(gpg, temp_input_file, temp_encrypted_filepath, recipients)
        with open(temp_encrypted_filepath) as temp_encrypted_file:
            copy_file_to_file(temp_encrypted_file, output_file, progress) 
Example #19
Source File: test_database_export.py    From edx-analytics-pipeline with GNU Affero General Public License v3.0 5 votes vote down vote up
def validate_exporter_output(self, org_id, exported_filename):
        """
        Preconditions: A complete data package has been uploaded to S3.
        External Effect: Downloads the complete data package, decompresses it, decrypts it and then compares it to the
            static expected output ignoring the ordering of the records in both files.

        Downloads s3://<exporter_output_bucket>/<output_prefix><org_id>-<year>-<month>-<day>.zip to <temporary_dir>/work/validation/.

        """
        today = datetime.datetime.utcnow().strftime('%Y-%m-%d')
        bucket = ScalableS3Client().s3.get_bucket(self.config.get('exporter_output_bucket'))
        export_id = '{org}-{date}'.format(org=org_id, date=today)
        filename = export_id + '.zip'
        key = bucket.lookup(self.output_prefix + filename)
        if key is None:
            self.fail(
                'Expected output from legacy exporter not found. Url = s3://{bucket}/{pre}{filename}'.format(
                    bucket=self.config.get('exporter_output_bucket'),
                    pre=self.output_prefix,
                    filename=filename
                )
            )
        exporter_archive_path = os.path.join(self.validation_dir, filename)
        key.get_contents_to_filename(exporter_archive_path)

        shell.run(['unzip', exporter_archive_path, '-d', self.validation_dir])

        gpg = gnupg.GPG(gnupghome=self.gpg_dir)
        with open(os.path.join('gpg-keys', 'insecure_secret.key'), 'r') as key_file:
            gpg.import_keys(key_file.read())

        exported_file_path = os.path.join(self.validation_dir, exported_filename)
        with open(os.path.join(self.validation_dir, export_id, exported_filename + '.gpg'), 'r') as encrypted_file:
            gpg.decrypt_file(encrypted_file, output=exported_file_path)

        sorted_filename = exported_file_path + '.sorted'
        shell.run(['sort', '-o', sorted_filename, exported_file_path])

        expected_output_path = os.path.join(self.data_dir, 'output', exported_filename + '.sorted')
        shell.run(['diff', sorted_filename, expected_output_path]) 
Example #20
Source File: gpgit.py    From gpgit with MIT License 5 votes vote down vote up
def substep2(self):
        """Key generation"""
        # Generate RSA key command
        # https://www.gnupg.org/documentation/manuals/gnupg/Unattended-GPG-key-generation.html
        input_data = """
        Key-Type: RSA
        Key-Length: 4096
        Key-Usage: cert sign auth
        Subkey-Type: RSA
        Subkey-Length: 4096
        Subkey-Usage: encrypt
        Name-Real: {0}
        Name-Email: {1}
        Expire-Date: 1y
        Preferences: SHA512 SHA384 SHA256 AES256 AES192 AES ZLIB BZIP2 ZIP Uncompressed
        %ask-passphrase
        %commit
        """.format(self.config['username'], self.config['email'])

        # Execute GPG key generation command
        self.verbose('We need to generate a lot of random bytes. It is a good idea to perform')
        self.verbose('some other action (type on the keyboard, move the mouse, utilize the')
        self.verbose('disks) during the prime generation; this gives the random number')
        self.verbose('generator a better chance to gain enough entropy.')
        self.config['fingerprint'] = str(self.gpg.gen_key(input_data))
        self.verbose('Key generation finished. You new fingerprint is: {}' \
                     .format(self.config['fingerprint'])) 
Example #21
Source File: gpgit.py    From gpgit with MIT License 5 votes vote down vote up
def __init__(self, config, gpg):
        # Params
        self.config = config
        self.gpg = gpg

        # Initialize parent
        Step.__init__(self, 'Generate a new GPG key',
                      Substep('Strong, unique, secret passphrase', self.substep1),
                      Substep('Key generation', self.substep2)) 
Example #22
Source File: generate_keys.py    From satellite with GNU General Public License v3.0 5 votes vote down vote up
def main():
    """Generate GPG Keys
    """
    parser = argparse.ArgumentParser(
        description='Generates GPG keys',
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument('-g', '--gnupghome', default=".gnupg",
                        help='GnuPG home directory')
    parser.add_argument('-v', '--verbose', action='store_true', default=False,
                        help="Verbose mode")
    args        = parser.parse_args()

    name_real    = input("User name represented by the key: ")
    name_comment = input("Comment to attach to the user name: ")
    name_email   = input("E-mail address: ")

    if (not os.path.exists(args.gnupghome)):
        os.mkdir(args.gnupghome)

    # GPG object
    gpg = gnupg.GPG(verbose = args.verbose, gnupghome = args.gnupghome)

    # Password
    gpg_password = getpass.getpass(prompt='Please enter the passphrase to '
                                   'protect your new key: ')

    # Generate key
    key_params = gpg.gen_key_input(key_type = "RSA", key_length = 1024,
                                   name_real = name_real,
                                   name_comment = name_comment,
                                   name_email = name_email,
                                   passphrase = gpg_password)
    key        = gpg.gen_key(key_params)

    # Export
    public_key  = gpg.export_keys(key.fingerprint)
    private_key = gpg.export_keys(key.fingerprint, True,
                                  passphrase = gpg_password)

    print("Keys generated succesfully at {}".format(
        os.path.abspath(args.gnupghome))) 
Example #23
Source File: gpgit.py    From gpgit with MIT License 5 votes vote down vote up
def __init__(self, config, gpg):
        # Params
        self.config = config
        self.gpg = gpg

        # Initialize parent
        Step.__init__(self, 'Publish your GPG key',
                      Substep('Send GPG key to a key server', self.substep1),
                      Substep('Publish full fingerprint', self.substep2),
                      Substep('Associate GPG key with Github', self.substep3)) 
Example #24
Source File: gpgit.py    From gpgit with MIT License 5 votes vote down vote up
def analyze(self):
        """Analyze: Publish your GPG key"""
        # Add publish note
        if self.config['fingerprint'] is None:
            self.setstatus(2, 'TODO', 'Please publish the full GPG fingerprint on the project page')
        else:
            self.setstatus(2, 'NOTE', 'Please publish the full GPG fingerprint on the project page')

        # Check Github GPG key
        if self.config['github'] is True:
            # TODO Will associate your GPG key with Github
            self.setstatus(3, 'NOTE', 'Please associate your GPG key with Github')
        else:
            self.setstatus(3, 'OK', 'No Github repository used')

        # Only check if a fingerprint was specified
        if self.config['fingerprint'] is not None:
            # Check key on keyserver
            try:
                with time_limit(10):
                    # TODO cannot catch error for unknown GPG key as its run in a separat thread
                    key = self.gpg.recv_keys(self.config['keyserver'], self.config['fingerprint'])
            except TimeoutException:
                return 'Keyserver timed out. Please try again alter.'

            # Found key on keyserver
            if self.config['fingerprint'] in key.fingerprints:
                self.setstatus(1, 'OK', 'Key already published on {}' \
                               .format(self.config['keyserver']))
                return

        # Upload key to keyserver
        self.setstatus(1, 'TODO', 'Publishing key on {}'.format(self.config['keyserver'])) 
Example #25
Source File: gpgit.py    From gpgit with MIT License 5 votes vote down vote up
def substep1(self):
        """Send GPG key to a key server"""
        self.verbose('Publishing key {}'.format(self.config['fingerprint']))
        self.gpg.send_keys(self.config['keyserver'], self.config['fingerprint']) 
Example #26
Source File: gpgit.py    From gpgit with MIT License 5 votes vote down vote up
def __init__(self, config, repo):
        # Params
        self.config = config
        self.repo = repo

        # Initialize parent
        Step.__init__(self, 'Use Git with GPG',
                      Substep('Configure Git GPG key', self.substep1),
                      Substep('Enable commit signing', self.substep2),
                      Substep('Create signed Git tag', self.substep3)) 
Example #27
Source File: gpgit.py    From gpgit with MIT License 5 votes vote down vote up
def analyze(self):
        """Analyze: Use Git with GPG"""
        # Check if Git was already configured with a different key
        if self.config['fingerprint'] is None or self.config['signingkey'] != self.config['fingerprint']:
            self.config['config_level'] = 'global'
            self.setstatus(1, 'TODO', 'Configuring {} Git GPG key' \
                           .format(self.config['config_level']))
        else:
            self.setstatus(1, 'OK', 'Git already configured with your GPG key')

        # Check commit signing
        if self.config['gpgsign'] and self.config['gpgsign'].lower() == 'true':
            self.setstatus(2, 'OK', 'Commit signing already enabled')
        else:
            self.setstatus(2, 'TODO', 'Enabling {} commit signing' \
                           .format(self.config['config_level']))

        # Refresh tags
        try:
            self.repo.remotes.origin.fetch('--tags')
        except git.exc.GitCommandError:
            return 'Error fetching remote tags.'

        # Check if tag was already created
        tag = self.repo.tag('refs/tags/' + self.config['tag'])
        if tag in self.repo.tags:
            # Verify signature
            try:
                self.repo.create_tag(self.config['tag'], verify=True, ref=None)
            except git.exc.GitCommandError:
                if hasattr(tag.tag, 'message') \
                        and '-----BEGIN PGP SIGNATURE-----' in tag.tag.message:
                    return 'Invalid signature for tag ' + self.config['tag']
                self.setstatus(3, 'TODO', 'Signing existing tag: {}'.format(self.config['tag']))
            else:
                self.setstatus(3, 'OK', 'Good signature for existing tag: {}' \
                               .format(self.config['tag']))
        else:
            self.setstatus(3, 'TODO', 'Creating signed tag {} and pushing it to the remote Git' \
                           .format(self.config['tag'])) 
Example #28
Source File: gpgit.py    From gpgit with MIT License 5 votes vote down vote up
def substep1(self):
        """Configure Git GPG key"""
        # Configure Git signingkey settings
        with self.repo.config_writer(config_level=self.config['config_level']) as cfgwriter:
            cfgwriter.set("user", "signingkey", self.config['fingerprint']) 
Example #29
Source File: gpgit.py    From gpgit with MIT License 5 votes vote down vote up
def substep2(self):
        """Sign the archive"""
        # Check all compression option tar files
        filename = self.config['project'] + '-' + self.config['tag']
        for tar in self.config['tar']:
            # Get tar filename
            tarfile = filename + '.tar.' + tar
            tarfilepath = os.path.join(self.config['output'], tarfile)

            # Get signature filename from setting
            if self.config['armor']:
                sigfilepath = tarfilepath + '.asc'
            else:
                sigfilepath = tarfilepath + '.sig'

            # Check if signature is existant
            if not os.path.isfile(sigfilepath):
                # Sign tar file
                with open(tarfilepath, 'rb') as tarstream:
                    self.verbose('Creating {}'.format(sigfilepath))
                    signed_data = self.gpg.sign_file(
                        tarstream,
                        keyid=self.config['fingerprint'],
                        binary=not bool(self.config['armor']),
                        detach=True,
                        output=sigfilepath,
                        # extra_args --digest-algo algoname https://github.com/vsajip/python-gnupg/pull/4#issuecomment-312203310
                        #digest_algo='SHA512' #TODO v 2.x GPG module
                        )
                    if signed_data.fingerprint != self.config['fingerprint']:
                        return 'Signing data failed'
                    # TODO https://tools.ietf.org/html/rfc4880#section-9.4
                    #print(signed_data.hash_algo) -> 8 -> SHA256 
Example #30
Source File: gpgit.py    From gpgit with MIT License 5 votes vote down vote up
def __init__(self, tag, config):
        # Create module instances and helpers
        self.gpg = gnupg.GPG()
        self.repo = None
        self.assets = []

        # Config via parameters
        self.config = {
            'tag': tag,
            'message': None,
            'output': None,
            'git_dir': os.getcwd(),
            'github': False,
            'prerelease': False,
        }

        # Overwrite every default value if passed in via parameter
        for param in self.config:
            if param in config:
                self.config[param] = config[param]

        # Load configuration
        self.load_git_config()
        self.load_default_config()

        # Create array fo steps to analyse and run
        self.step1 = Step1(self.config, self.gpg)
        self.step2 = Step2(self.config, self.gpg)
        self.step3 = Step3(self.config, self.repo)
        self.step4 = Step4(self.config, self.gpg, self.repo, self.assets)
        self.step5 = Step5(self.config, self.assets)
        self.steps = [self.step1, self.step2, self.step3, self.step4, self.step5]