Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,17 @@ All versions prior to 0.9.0 are untracked.

## [Unreleased]

### Removed

* Removed Ed25519 signing certificate verification support and the weak
Ed25519 public key checks added in 4.6.0.

### Changed

* Signing certificates with unsupported key algorithms, key types (such as
Ed25519 or RSA), or EC curves (anything other than `secp256r1`, `secp384r1`,
and `secp521r1`) now fail verification with a descriptive `VerificationError`.

## [4.6.0]

### Added
Expand Down
66 changes: 0 additions & 66 deletions sigstore/_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,68 +61,6 @@
"""


# Field prime for Curve25519 / edwards25519.
_ED25519_P = 2**255 - 19

# The edwards25519 curve constant d = -121665 / 121666 (RFC 8032, section 5.1).
_ED25519_D = -121665 * pow(121666, -1, _ED25519_P) % _ED25519_P

# The y-coordinates of the eight edwards25519 points of small order (1, 2, 4
# and 8). Each y below covers both signs of x.
_ED25519_SMALL_ORDER_Y = frozenset(
{
0,
1,
_ED25519_P - 1,
int.from_bytes(
bytes.fromhex(
"26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05"
),
"little",
),
int.from_bytes(
bytes.fromhex(
"c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a"
),
"little",
),
}
)


def _is_weak_ed25519_key(key: ed25519.Ed25519PublicKey) -> bool:
"""
Returns `True` if `key` is a non-canonical, small-order or off-curve
Ed25519 point encoding, which no legitimate Ed25519 keypair produces.
"""
raw = key.public_bytes(serialization.Encoding.Raw, serialization.PublicFormat.Raw)
# The top bit of the encoding is the sign of x; the rest is y.
y = int.from_bytes(raw, "little") & ((1 << 255) - 1)
# y >= p is a non-canonical alias of y - p. Every point with x = 0 has
# y in {1, p - 1}, so a set sign bit on those is caught by the y check too.
if y >= _ED25519_P or y in _ED25519_SMALL_ORDER_Y:
return True

# The point is on the curve only if x^2 = (y^2 - 1) / (d * y^2 + 1) has a
# square root (Euler's criterion). The denominator is never zero, and the
# numerator is zero only for y = +-1, which is excluded above.
p, d = _ED25519_P, _ED25519_D
x2 = (y * y - 1) * pow(d * y * y + 1, -1, p) % p
return pow(x2, (p - 1) // 2, p) != 1


def _check_public_key(key: PublicKey) -> None:
"""
Rejects Ed25519 public keys with a non-canonical, small-order or off-curve
encoding. Other key types are accepted unchanged.
"""
if isinstance(key, ed25519.Ed25519PublicKey) and _is_weak_ed25519_key(key):
raise VerificationError(
"invalid Ed25519 public key: non-canonical, small-order or "
"off-curve encoding"
)


def load_pem_public_key(
key_pem: bytes,
*,
Expand All @@ -146,8 +84,6 @@ def load_pem_public_key(
if not isinstance(key, types):
raise VerificationError(f"invalid key format: not one of {types}")

_check_public_key(key)

return key


Expand All @@ -172,8 +108,6 @@ def load_der_public_key(
if not isinstance(key, types):
raise VerificationError(f"invalid key format: not one of {types}")

_check_public_key(key)

return key


Expand Down
19 changes: 8 additions & 11 deletions sigstore/dsse/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@

from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import ec, ed25519
from cryptography.hazmat.primitives.asymmetric import ec
from pydantic import BaseModel, ConfigDict, Field, RootModel, StrictStr, ValidationError
from sigstore_models.common.v1 import HashAlgorithm
from sigstore_models.intoto import Envelope as _Envelope
Expand Down Expand Up @@ -284,9 +284,7 @@ def _sign(key: ec.EllipticCurvePrivateKey, stmt: Statement) -> Envelope:
)


def _verify(
key: ec.EllipticCurvePublicKey | ed25519.Ed25519PublicKey, evp: Envelope
) -> bytes:
def _verify(key: ec.EllipticCurvePublicKey, evp: Envelope) -> bytes:
"""
Verify the given in-toto `Envelope`, returning the verified inner payload.

Expand All @@ -300,16 +298,15 @@ def _verify(
if nsigs != 1:
raise VerificationError(f"DSSE: exactly 1 signature allowed, got {nsigs}")

if not isinstance(key, ec.EllipticCurvePublicKey):
raise VerificationError(
f"DSSE: unsupported key type: {type(key).__name__} (only ECDSA is supported)"
)

signature = evp._inner.signatures[0].sig

try:
if isinstance(key, ed25519.Ed25519PublicKey):
# Ed25519 signs the PAE directly, with no separate hash.
key.verify(signature, pae)
elif isinstance(key, ec.EllipticCurvePublicKey):
key.verify(signature, pae, ec.ECDSA(hashes.SHA256()))
else:
raise VerificationError(f"DSSE: unsupported key type: {type(key).__name__}")
key.verify(signature, pae, ec.ECDSA(hashes.SHA256()))
except InvalidSignature:
raise VerificationError("DSSE: invalid signature")

Expand Down
81 changes: 32 additions & 49 deletions sigstore/verify/verifier.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,13 @@
from __future__ import annotations

import base64
import hashlib
import logging
from collections.abc import Callable
from datetime import UTC, datetime

import rekor_types
from cryptography.exceptions import InvalidSignature
from cryptography.exceptions import InvalidSignature, UnsupportedAlgorithm
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import ec, ed25519
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.x509 import (
Certificate,
ExtendedKeyUsage,
Expand Down Expand Up @@ -59,7 +57,7 @@
)
from sigstore._internal.timestamp import TimestampSource, TimestampVerificationResult
from sigstore._internal.trust import KeyringPurpose
from sigstore._utils import _check_public_key, base64_encode_pem_cert, sha256_digest
from sigstore._utils import base64_encode_pem_cert, sha256_digest
from sigstore.errors import CertValidationError, VerificationError
from sigstore.hashes import Hashed
from sigstore.models import Bundle, ClientTrustConfig, TrustedRoot
Expand Down Expand Up @@ -480,21 +478,11 @@ def verify_artifact(
# (7): verify that the signature was signed by the public key in the signing certificate.
signing_key = _get_signing_key(bundle)
try:
if isinstance(signing_key, ed25519.Ed25519PublicKey):
# Ed25519 signs the message itself rather than a digest of it,
# so it can only be verified against the full input.
if not isinstance(input_, bytes):
raise VerificationError(
"Ed25519 signatures can only be verified against the "
"full input, not a prehashed digest"
)
signing_key.verify(bundle_signature.signature, input_)
else:
signing_key.verify(
bundle_signature.signature,
hashed_input.digest,
ec.ECDSA(hashed_input._as_prehashed()),
)
signing_key.verify(
bundle_signature.signature,
hashed_input.digest,
ec.ECDSA(hashed_input._as_prehashed()),
)
except InvalidSignature:
raise VerificationError("Signature is invalid for input")

Expand All @@ -518,21 +506,32 @@ def verify_artifact(
)


def _get_signing_key(
bundle: Bundle,
) -> ec.EllipticCurvePublicKey | ed25519.Ed25519PublicKey:
_SUPPORTED_EC_CURVES = (ec.SECP256R1, ec.SECP384R1, ec.SECP521R1)


def _get_signing_key(bundle: Bundle) -> ec.EllipticCurvePublicKey:
"""
Return the bundle's signing certificate's public key, if it is of a type
that can verify the bundle's signature.
Return the bundle's signing certificate's public key, if it is a supported
ECDSA key.
"""
signing_key = bundle.signing_certificate.public_key()
if not isinstance(
signing_key, (ec.EllipticCurvePublicKey, ed25519.Ed25519PublicKey)
):
try:
signing_key = bundle.signing_certificate.public_key()
except UnsupportedAlgorithm as exc:
raise VerificationError(
f"Unsupported signing certificate key algorithm: {exc} "
"(only ECDSA secp256r1, secp384r1, and secp521r1 are supported)"
) from exc

if not isinstance(signing_key, ec.EllipticCurvePublicKey):
raise VerificationError(
f"unsupported signing certificate key type: {type(signing_key).__name__}"
f"Unsupported signing certificate key type: {type(signing_key).__name__} "
"(only ECDSA secp256r1, secp384r1, and secp521r1 are supported)"
)
if not isinstance(signing_key.curve, _SUPPORTED_EC_CURVES):
raise VerificationError(
f"Unsupported signing certificate EC curve: {signing_key.curve.name} "
"(only secp256r1, secp384r1, and secp521r1 are supported)"
)
_check_public_key(signing_key)
return signing_key


Expand Down Expand Up @@ -621,7 +620,7 @@ def _validate_hashedrekord_v002_dsse_entry_body(bundle: Bundle) -> None:
)

expected_verifier = _v2_verifier_from_certificate(bundle.signing_certificate)
algorithm, hash_func = _v2_prehash(expected_verifier)
algorithm, hash_func = _get_prehash(expected_verifier.key_details)
pae_digest = hash_func(envelope.pae()).digest()

expected_body = v2.entry.Entry(
Expand Down Expand Up @@ -658,9 +657,6 @@ def _validate_hashedrekord_v002_entry_body(
raise VerificationError(
"invalid hashedrekord log entry: missing message signature"
)
expected_verifier = _v2_verifier_from_certificate(bundle.signing_certificate)
# Rejects signing algorithms that can't be recorded as hashedrekord entries.
_v2_prehash(expected_verifier)
v2_expected_body = v2.entry.Entry(
kind=entry._inner.kind_version.kind,
api_version=entry._inner.kind_version.version,
Expand All @@ -672,7 +668,7 @@ def _validate_hashedrekord_v002_entry_body(
),
signature=v2.verifier.Signature(
content=base64.b64encode(bundle._inner.message_signature.signature),
verifier=expected_verifier,
verifier=_v2_verifier_from_certificate(bundle.signing_certificate),
),
)
),
Expand All @@ -684,19 +680,6 @@ def _validate_hashedrekord_v002_entry_body(
)


def _v2_prehash(
verifier: v2.verifier.Verifier,
) -> tuple[v1.HashAlgorithm, Callable[[bytes], hashlib._Hash]]:
"""
Return the externalized hash function for a Rekor v2 verifier's signing
algorithm, or raise `VerificationError` if it has none (pure Ed25519).
"""
try:
return _get_prehash(verifier.key_details)
except ValueError as exc:
raise VerificationError(str(exc)) from exc


def _v2_verifier_from_certificate(certificate: Certificate) -> v2.verifier.Verifier:
"""
Return a Rekor v2 Verifier for the signing certificate.
Expand Down
54 changes: 0 additions & 54 deletions test/unit/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,60 +128,6 @@ def _signing_bundle(name: str) -> tuple[Path, Bundle]:
return _signing_bundle


# Ed25519 public key encodings that `_utils._check_public_key` must reject.
# The first group are encodings of the eight small-order points, including
# non-canonical aliases and x = 0 encodings with the sign bit set.
_ED25519_SMALL_ORDER_KEYS = [
"0000000000000000000000000000000000000000000000000000000000000000",
"0000000000000000000000000000000000000000000000000000000000000080",
"0100000000000000000000000000000000000000000000000000000000000000",
"0100000000000000000000000000000000000000000000000000000000000080",
"26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05",
"26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85",
"c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a",
"c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa",
"ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",
"ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
"edffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",
"edffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
"eeffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",
"eeffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
]

# Every encoding whose y-coordinate is not reduced modulo p, with either sign.
_ED25519_P = 2**255 - 19
_ED25519_NON_CANONICAL_KEYS = [
(y | (sign << 255)).to_bytes(32, "little").hex()
for y in range(_ED25519_P, 2**255)
for sign in (0, 1)
]

# Canonical encodings whose y-coordinate has no matching x on the curve.
_ED25519_OFF_CURVE_KEYS = [
"0200000000000000000000000000000000000000000000000000000000000000",
"0200000000000000000000000000000000000000000000000000000000000080",
"0700000000000000000000000000000000000000000000000000000000000000",
# y = p - 2
"ebffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",
]

WEAK_ED25519_KEYS = list(
dict.fromkeys(
_ED25519_SMALL_ORDER_KEYS
+ _ED25519_NON_CANONICAL_KEYS
+ _ED25519_OFF_CURVE_KEYS
)
)


@pytest.fixture(params=WEAK_ED25519_KEYS)
def weak_ed25519_key(request) -> bytes:
"""
A raw 32-byte Ed25519 public key that should be rejected.
"""
return bytes.fromhex(request.param)


@pytest.fixture
def null_policy():
class NullPolicy:
Expand Down
23 changes: 19 additions & 4 deletions test/unit/test_dsse.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
import json

import pytest
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives.asymmetric import ed25519, rsa

from sigstore import dsse
from sigstore.dsse import Error, InvalidEnvelope
Expand Down Expand Up @@ -111,7 +111,20 @@ def test_malformed_statement_reports_why(self):
assert "digest" in str(exc.value)


def test_verify_unsupported_key_type():
@pytest.mark.parametrize(
("key", "expected_name"),
[
(
rsa.generate_private_key(public_exponent=65537, key_size=2048).public_key(),
"RSAPublicKey",
),
(
ed25519.Ed25519PrivateKey.generate().public_key(),
"Ed25519PublicKey",
),
],
)
def test_verify_unsupported_key_type(key, expected_name):
evp = dsse.Envelope._from_json(
json.dumps(
{
Expand All @@ -121,7 +134,9 @@ def test_verify_unsupported_key_type():
}
)
)
key = rsa.generate_private_key(public_exponent=65537, key_size=2048).public_key()

with pytest.raises(VerificationError, match="DSSE: unsupported key type"):
with pytest.raises(
VerificationError,
match=f"DSSE: unsupported key type: {expected_name} \\(only ECDSA is supported\\)",
):
dsse._verify(key, evp) # type: ignore[arg-type]
Loading
Loading