Beispiel #1
0
  def test_create_signature_with_expired_key(self):
    """Test signing with expired key raises gpg CommandError. """
    with self.assertRaises(CommandError) as ctx:
      create_signature(b"livestock", keyid=self.expired_key_keyid,
          homedir=self.gnupg_home)

    expected = "returned non-zero exit status '2'"
    self.assertTrue(expected in str(ctx.exception), "{} not in {}".format(
        expected, ctx.exception))
    def test_gpg_functions(self):
        """Signing, key export and util functions must raise on missing gpg. """
        with self.assertRaises(UnsupportedLibraryError) as ctx:
            create_signature('bar')
        self.assertEqual(NO_GPG_MSG, str(ctx.exception))

        with self.assertRaises(UnsupportedLibraryError) as ctx:
            export_pubkey('f00')
        self.assertEqual(NO_GPG_MSG, str(ctx.exception))

        with self.assertRaises(UnsupportedLibraryError) as ctx:
            get_version()
        self.assertEqual(NO_GPG_MSG, str(ctx.exception))
Beispiel #3
0
  def test_gpg_sign_and_verify_object_with_default_key(self):
    """Create a signature using the default key on the keyring """

    test_data = b'test_data'
    wrong_data = b'something malicious'

    signature = create_signature(test_data, homedir=self.gnupg_home)
    key_data = export_pubkey(self.default_keyid, homedir=self.gnupg_home)

    self.assertTrue(verify_signature(signature, key_data, test_data))
    self.assertFalse(verify_signature(signature, key_data, wrong_data))
Beispiel #4
0
  def test_gpg_sign_and_verify_object_default_keyring(self):
    """Sign/verify using keyring from envvar. """

    test_data = b'test_data'

    gnupg_home_backup = os.environ.get("GNUPGHOME")
    os.environ["GNUPGHOME"] = self.gnupg_home

    signature = create_signature(test_data, keyid=self.default_keyid)
    key_data = export_pubkey(self.default_keyid)
    self.assertTrue(verify_signature(signature, key_data, test_data))

    # Reset GNUPGHOME
    if gnupg_home_backup:
      os.environ["GNUPGHOME"] = gnupg_home_backup
    else:
      del os.environ["GNUPGHOME"]
def sign_via_gpg(data_to_sign, gpg_key_fingerprint, include_fingerprint=False):
    """
    <Purpose>

        This is an alternative to the conda_content_trust.common.PrivateKey.sign() method, for
        use with OpenPGP keys, allowing us to use protected keys in YubiKeys
        (which provide an OpenPGP interface) to sign data.

        The signature is not simply over data_to_sign, as is the case with the
        PrivateKey.sign() function, but over an expanded payload with
        metadata about the signature to be signed, as specified by the OpenPGP
        standard (RFC 4880).  See data_to_sign and Security Note below.

        This process is nominally deterministic, but varies with the precise
        time, since there is a timestamp added by GPG into the signed payload.
        Nonetheless, this process does not depend at any point on the ability
        to generate random data (unlike key generation).

        This function requires securesystemslib, which is otherwise an optional
        dependency.

    <Arguments>

        data_to_sign
            The raw bytes of interest that will be signed by GPG.  Note that
            pursuant to the OpenPGP standard, GPG will add to this data:
            specifically, it includes metadata about the signature that is
            about to be made into the data that will be signed.  We do not care
            about that metadata, and we do not want to burden signature
            verification with its processing, so we essentially ignore it.
            This should have negligible security impact, but for more
            information, see "A note on security" below.


        gpg_key_fingerprint
            This is a (fairly) unique identifier for an OpenPGP key pair.
            Also Known as a "long" GPG keyid, a GPG fingerprint is
            40-hex-character string representing 20 bytes of raw data, the
            SHA-1 hash of a collection of the GPG key's properties.
            Internally, GPG uses the key fingerprint to identify keys the
            client knows of.

            Note that an OpenPGP public key is a larger object identified by a
            fingerprint.  GPG public keys include two things, from our
            perspective:

             - the raw bytes of the actual cryptographic key
               (in our case the 32-byte value referred to as "q" for an ed25519
               public key)

             - lots of data that is totally extraneous to us, including a
               timestamp, some representations of relationships with other keys
               (subkeys, signed-by lists, etc.), Superman's real name
               (see also https://bit.ly/38GcaGj), potential key revocations,
               etc.
               We do not care about this extra data because we are using the
               OpenPGP standard not for its key-to-key semantics or any element
               of its Public Key Infrastructure features (revocation, vouching
               for other keys, key relationships, etc.), but simply as a means
               of asking YubiKeys to sign data for us, with ed25519 keys whose
               raw public key value ("q") we know to expect.


    <Returns>
        Returns a dictionary representing a GPG signature.  This is similar to
        but not *quite* the same as
        securesystemslib.formats.GPG_SIGNATURE_SCHEMA (which uses 'keyid'
        as the key for the fingerprint, instead of 'gpg_key_fingerprint').

        Specifically, this looks like:
            {'gpg_key_fingerprint': <gpg key fingerprint>,
            'other_headers':       <extra data mandated in OpenPGP signatures>,
            'signature':        <ed25519 signature, 64 bytes as 128 hex chars>}


        This is unlike conda_content_trust.signing.sign(), which simply returns 64 bytes of raw
        ed25519 signature.


    <Security Note>

        A note on the security implications of this treatment of OpenPGP
        signatures:

        TL;DR:
            It is NOT easier for an attacker to find a collision; however, it
            IS easier, IF an attacker CAN find a collision, to do so in a way
            that presents a specific, arbitrary payload.

        Note that pursuant to the OpenPGP standard, GPG will add to the data we
        ask it to sign (data_to_sign) before signing it. Specifically, GPG will
        add, to the payload-to-be-signed, OpenPGP metadata about the signature
        it is about to create.  We do not care about that metadata, and we do
        not want to burden signature verification with its processing (that is,
        we do not want to use GPG to verify these signatures; conda will do
        that with simpler code).  As a result, we will ignore this data when
        parsing the signed payload.  This will mean that there will be many
        different messages that have the same meaning to us:

            signed:
                <some raw data we send to GPG: 'ABCDEF...'>
                <some data GPG adds in: '123456...'>

            Since we will not be processing the '123456...' above, '654321...'
            would have the same effect: as long as the signature is verified,
            we don't care what's in that portion of the payload.

        Since there are many, many payloads that mean the same thing to us, an
        attacker has a vast space of options all with the same meaning to us in
        which to search for (effectively) a useful SHA256 hash collision to
        find different data that says something *specific* and still
        *succeeds* in signature verification using the same signature.
        While that is not ideal, it is difficult enough simply to find a SHA256
        collision that this is acceptable.
    """
    if not SSLIB_AVAILABLE:
        # TODO✅: Consider a missing-optional-dependency exception class.
        raise Exception(
            'sign_via_gpg requires the securesystemslib library, which '
            'appears to be unavailable.')

    # Argument validation
    checkformat_gpg_fingerprint(gpg_key_fingerprint)
    checkformat_byteslike(data_to_sign)

    # try:
    #     full_gpg_pubkey = gpg_funcs.export_pubkey(gpg_key_fingerprint)
    # except securesystemslib.gpg.exceptions.KeyNotFoundError as e:
    #     raise Exception( # TODO✅: Consider an appropriate error class.
    #             'The GPG application reported that it is not aware of a key '
    #             'with the fingerprint provided ("' + str(gpg_key_fingerprint) +
    #             '").  You may need to import the given key.')

    sig = gpg_funcs.create_signature(data_to_sign, gpg_key_fingerprint)

    # # 💣💥 Debug only.
    # # 💣💥 Debug only.
    # assert gpg_funcs.verify_signature(sig, full_gpg_pubkey, data_to_sign)

    # securesystemslib.gpg makes use of the GPG key fingerprint.  We don't
    # care about that as much -- we want to use the raw ed25519 public key
    # value to refer to the key in a manner consistent with the way we refer to
    # non-GPG (non-OpenPGP) keys.
    keyval = fetch_keyval_from_gpg(gpg_key_fingerprint)

    # ssl gpg sigs look like this:
    #
    #   {'keyid': <gpg key fingerprint>,
    #    'other_headers': <extra data mandated in OpenPGP signatures>,
    #    'signature': <actual ed25519 signature, 64 bytes as 128 hex chars>}
    #
    # We want to store the real public key instead of just the gpg key
    # fingerprint, so we add that, and we'll rename keyid to
    # gpg_key_fingerprint.  That gives us:
    #
    #   {'gpg_key_fingerprint': <gpg key fingerprint>,
    #    'other_headers': <extra data mandated in OpenPGP signatures>,
    #    'signature': <actual ed25519 signature, 64 bytes as 128 hex chars>}
    #
    # sig['key'] = keyval  # q, the 32-byte raw ed25519 public key value, expressed as 64 hex characters

    # The OpenPGP Fingerprint of the OpenPGP key used to sign.  This is not
    # required for verification, but it's useful for debugging and for
    # root keyholder convenience.  So it's optional.
    if include_fingerprint:
        sig['see_also'] = sig[
            'keyid']  # strictly not needed, useful for debugging; 20-byte sha1 gpg key identifier per OpenPGP spec, expressed as 40 hex characters

    del sig['keyid']

    return sig
def sign_via_gpg(data_to_sign, gpg_key_fingerprint):
    """
    <Purpose>

        This is an alternative to the car.authenticate.sign() function, for use
        with OpenPGP keys, allowing us to use protected keys in YubiKeys (which
        provide an OpenPGP interface) to sign data.

        The signature is not simply over data_to_sign, as is the case with the
        car.authenticate.sign() function, but over an expanded payload with
        metadata about the signature to be signed, as specified by the OpenPGP
        standard (RFC 4880).  See data_to_sign and Security Note below.

        This process is nominally deterministic, but varies with the precise
        time, since there is a timestamp added by GPG into the signed payload.
        Nonetheless, this process does not depend at any point on the ability
        to generate random data (unlike key generation).

        This function requires securesystemslib, which is otherwise an optional
        dependency.

    <Arguments>

        data_to_sign
            The raw bytes of interest that will be signed by GPG.  Note that
            pursuant to the OpenPGP standard, GPG will add to this data:
            specifically, it includes metadata about the signature that is
            about to be made into the data that will be signed.  We do not care
            about that metadata, and we do not want to burden signature
            verification with its processing, so we essentially ignore it.
            This should have negligible security impact, but for more
            information, see "A note on security" below.


        gpg_key_fingerprint
            This is a (fairly) unique identifier for an OpenPGP key pair.
            Also Known as a "long" GPG keyid, a GPG fingerprint is
            40-hex-character string representing 20 bytes of raw data, the
            SHA-1 hash of a collection of the GPG key's properties.
            Internally, GPG uses the key fingerprint to identify keys the
            client knows of.

            Note that an OpenPGP public key is a larger object identified by a
            fingerprint.  GPG keys include two things, from our perspective:

             - the raw bytes of the actual cryptographic key
               (in our case the 32-byte value "q" for an ed25519 public key)

             - lots of data that is totally extraneous to us, including a
               timestamp, some representations of relationships with other keys
               (subkeys, signed-by lists, etc.), potential revocations, etc...)
               We do not care about this extra data because we are using the
               OpenPGP standard not for its key-to-key semantics or any element
               of its Public Key Infrastructure features (revocation, vouching
               for other keys, key relationships, etc.), but simply as a means
               of asking YubiKeys to sign data for us, with ed25519 keys whose
               raw public key value ("q") we know to expect.


    <Returns>
        Returns two values:
          - a dictionary representing a GPG signature, conforming to
            securesystemslib.formats.GPG_SIGNATURE_SCHEMA, and
          - a gpg public key object, a dictionary conforming to
            securesystemslib.formats.GPG_ED25519_PUBKEY_SCHEMA.

        This is unlike sign(), which returns 64 bytes of raw ed25519 signature.


    <Security Note>

        A note on the security implications of this treatment of OpenPGP
        signatures:

        TL;DR:
            It is NOT easier for an attacker to find a collision; however, it
            IS easier, IF an attacker CAN find a collision, to do so in a way
            that presents a specific, arbitrary payload.

        Note that pursuant to the OpenPGP standard, GPG will add to the data we
        ask it to sign (data_to_sign) before signing it. Specifically, GPG will
        add, to the payload-to-be-signed, OpenPGP metadata about the signature
        it is about to create.  We do not care about that metadata, and we do
        not want to burden signature verification with its processing (that is,
        we do not want to use GPG to verify these signatures; conda will do
        that with simpler code).  As a result, we will ignore this data when
        parsing the signed payload.  This will mean that there will be many
        different messages that have the same meaning to us:

            signed:
                <some raw data we send to GPG: 'ABCDEF...'>
                <some data GPG adds in: '123456...'>

            Since we will not be processing the '123456...' above, '654321...'
            would have the same effect: as long as the signature is verified,
            we don't care what's in that portion of the payload.

        Since there are many, many payloads that mean the same thing to us, an
        attacker has a vast space of options all with the same meaning to us in
        which to search for (effectively) a useful SHA256 hash collision to
        find different data that says something *specific* and still
        *succeeds* in signature verification using the same signature.
        While that is not ideal, it is difficult enough simply to find a SHA256
        collision that this is acceptable.
    """
    if not SSLIB_AVAILABLE:
        # TODO✅: Consider a missing-optional-dependency exception class.
        raise Exception(
                'sign_via_gpg requires the securesystemslib library, which '
                'appears to be unavailable.')

    sig = gpg_funcs.create_signature(data_to_sign, gpg_key_fingerprint)
    full_gpg_pubkey = gpg_funcs.export_pubkey(gpg_key_fingerprint)

    # 💣💥 Debug only.
    # 💣💥 Debug only.
    assert gpg_funcs.verify_signature(sig, full_gpg_pubkey, data_to_sign)

    return sig, full_gpg_pubkey