How to Verify a Download Before You Run It: Check SHA-256, GPG, Sigstore, GitHub Attestations, and Windows Authenticode on Real Files, and See Which Attack Each Check Stops
Verify one real Python installer four ways, build a policy-driven Python verifier, and test it against six pretend attacks to see what each check really proves.
You just downloaded an installer, a command-line tool, or a model runtime. Before you run it, how do you know it is the file the publisher actually built, and not a copy swapped on a mirror, planted on a hacked download page, or produced by a poisoned release pipeline? This tutorial teaches you to answer that question properly. You will check one real file, the Python 3.13.14 installer for Windows, four different ways, turn those checks into a small Python tool that refuses anything you did not expect, and then try six pretend attacks to see which check stops which.
Table Of Content
- What each check proves, and what it cannot
- Prerequisites
- Step 1: Create the lab folder and install the tools
- Step 2: Download one file and the evidence that goes with it
- Four small extra files for later
- Step 3: Check the SHA-256 checksum
- Compute the hash
- Compare it with the release page
- See what a one-bit change does
- What a match does and does not tell you
- Step 4: Verify the GPG signature
- Look at the signature before you have any key
- Get the public key from somewhere you can cross-check
- Verify, and read the warning correctly
- Get the same facts in a form a program can read
- Step 5: Verify the Sigstore signature
- How keyless signing works
- Verify the installer
- Look inside the bundle
- Watch it fail in three ways
- Step 6: Check the Windows Authenticode signature
- The genuine installers
- Valid is not the same as the right publisher
- A damaged file still shows the publisher’s name
- Step 7: Put it together in a verifier that pins everything
- The design
- The shared pieces and the checksum check
- Running other programs without hanging
- The GPG check
- The Sigstore and GitHub checks
- The Authenticode check
- The policy runner and the command line
- Write the policies
- Run it
- Two things that went wrong while I built it
- Step 8: Try six pretend attacks
- Reading the table
- What the table does not show
- Step 9: Verify a GitHub artifact attestation
- Step 10: Test the verifier, then break it on purpose
- The test suite
- Plant bugs and see whether the tests notice
- Step 11: Use it on your own downloads
- What do real projects publish?
- What none of these checks can tell you
- Common mistakes
- Trusting a hash that sits next to the file
- Reading “Good signature” as “verified”
- Importing keys into your everyday keyring
- Pinning a thumbprint that changes every release
- Reading the signer name on a damaged file
- Forgetting to pin the Sigstore issuer
- Letting a typo remove a check
- Treating “weak” as “fine”
- Confirm that everything works end to end
- Where to go next
- Sources and method
The reason to learn this now is that the stories on this site keep returning to the same gap. When ASEC reported trojanized Q-Dir and DesktopOK installers, we found that every ZIP on the vendor’s download pages matched the hash posted beside it, which shows only that the page and the file agree. A poisoned LiteLLM release came out of the project’s own pipeline, and Cursor’s marketplace served a tampered extension for 11 hours. A checksum answers one question, a signature answers another, and neither answers is this software safe. Learning which check answers which question is the point of this post.
What each check proves, and what it cannot
Five checks appear in this tutorial, and they answer five different questions, so it helps to define the vocabulary first. A checksum (also called a hash or digest) is a fixed-length fingerprint computed from every byte of a file. SHA-256 gives 64 hexadecimal digits. A digital signature is a short value made with a private key; anyone who holds the matching public key can check that it was made over exactly these bytes. A GPG key has a fingerprint, 40 hexadecimal digits that identify it. Sigstore replaces long-lived keys with short-lived certificates tied to an identity, such as an e-mail address or a build workflow, and records every signing event in a public transparency log. An attestation is a signed statement about a file, for example which workflow built it. Authenticode is the code-signing format Windows uses for .exe and .dll files.
| Check | The question it answers | What you must already know or trust | What can fool it |
|---|---|---|---|
| SHA-256 checksum | Are these the same bytes the publisher listed? | The place you got the expected hash from | An attacker who controls that place and swaps the file and the hash together |
| GPG signature | Did the holder of one specific key sign these bytes? | That key’s fingerprint, learned somewhere else | A fingerprint taken from the attacker, or a stolen private key |
| Sigstore bundle | Did one specific identity sign these bytes, and was it logged? | The identity and the identity provider you pin | A compromised account or build pipeline |
| GitHub attestation | Which repository and workflow built this file? | The repository you pin | A compromised workflow or repository |
| Windows Authenticode | Is it signed by the publisher’s certificate, unchanged since signing? | The publisher name and issuing authority you pin | A stolen certificate, or a different publisher’s valid one if you pin nothing |
Read the third column again. Every check needs a fact you learned from somewhere other than the download itself. That single idea is the whole lesson, and the six pretend attacks in Step 8 show why.
Prerequisites
The lab was run on Windows 11 in Git Bash, the terminal that comes with Git for Windows. Its gpg was GnuPG 2.4.9, and it also provides curl and sha256sum. On Linux the same commands work once gnupg is installed through your package manager. On macOS you can use shasum -a 256 in place of sha256sum, though I did not run macOS. Windows PowerShell 5.1 is needed only for the Authenticode step. You need Python 3.13 (tested with 3.13.14), network access, and a few hundred megabytes of disk space. No cryptography background is assumed. You should be comfortable typing commands in a terminal.
Step 1: Create the lab folder and install the tools
Make a folder, create a virtual environment (an isolated Python installation, so these packages stay out of your system Python), and install two packages. sigstore is the Python client for Sigstore verification that python.org itself recommends, and pytest runs the tests in Step 10.
mkdir verify-lab
cd verify-lab
python -m venv .venv
source .venv/Scripts/activate
python -m pip install sigstore pytest
Check what you got. Your versions may be newer, and nothing below depends on the exact numbers.
python --version
python -m pip list --format=freeze | grep -iE "^(sigstore|pytest|cryptography)=="
gpg --version | head -1
Python 3.13.14
cryptography==50.0.2
pytest==9.2.0
sigstore==4.6.0
gpg (GnuPG) 2.4.9
The python.org page also documents a way to install Sigstore from a hash-pinned requirements file for extra assurance. I used the plain install here, which that page lists as the alternative.
Step 2: Download one file and the evidence that goes with it
You will verify the 64-bit Windows installer for Python 3.13.14. It is a good teaching file because python.org publishes four kinds of evidence for it: a SHA-256 value on the release page, a GPG signature (the .asc file), a Sigstore bundle (the .sigstore file), and an Authenticode signature inside the .exe itself. Download the installer and the two signature files into a folder named dl:
mkdir dl
curl -sSfL -o dl/python-3.13.14-amd64.exe https://www.python.org/ftp/python/3.13.14/python-3.13.14-amd64.exe
curl -sSfL -o dl/python-3.13.14-amd64.exe.asc https://www.python.org/ftp/python/3.13.14/python-3.13.14-amd64.exe.asc
curl -sSfL -o dl/python-3.13.14-amd64.exe.sigstore https://www.python.org/ftp/python/3.13.14/python-3.13.14-amd64.exe.sigstore
ls -l dl | awk '{print $5, $9}'
29225624 python-3.13.14-amd64.exe
836 python-3.13.14-amd64.exe.asc
5651 python-3.13.14-amd64.exe.sigstore
Why Python 3.13.14 and not the newest release? Python 3.14 and later are signed only with Sigstore. The python.org Sigstore page says it plainly: “Starting with Python 3.14, Sigstore is the only method of signing and verification of release artifacts.” PEP 761 gives the reason: “PGP’s design requires the maintenance and protection of long-lived private keys by trusted parties.” You can see the difference yourself by asking the server for the signature file of each series:
curl -sI https://www.python.org/ftp/python/3.13.14/python-3.13.14-amd64.exe.asc | head -1
curl -sI https://www.python.org/ftp/python/3.14.10/python-3.14.10-amd64.exe.asc | head -1
HTTP/1.1 200 OK
HTTP/1.1 404 Not Found
The 3.13.14 signature exists and the 3.14.10 one does not (the server answers 404, “not found”). The 3.13 series is the last one where you can compare GPG and Sigstore on the same file, so it is the one to learn on.
Four small extra files for later
python.org also publishes, next to each Windows release, a small JSON manifest for the Python install manager (the entries for 3.13.14 list the download address and the SHA-256 of each Windows package) and a Sigstore bundle for that manifest. They are tiny, about 15 KB and 22 KB, and they give you real signed material for the tests and attacks later: a second file and a second signer, because 3.13.14 was signed by [email protected] and 3.14.10 by [email protected]. Download both pairs now; Step 8 and Step 10 use them.
curl -sSfL -o dl/windows-3.13.14.json https://www.python.org/ftp/python/3.13.14/windows-3.13.14.json
curl -sSfL -o dl/windows-3.13.14.json.sigstore https://www.python.org/ftp/python/3.13.14/windows-3.13.14.json.sigstore
curl -sSfL -o dl/windows-3.14.10.json https://www.python.org/ftp/python/3.14.10/windows-3.14.10.json
curl -sSfL -o dl/windows-3.14.10.json.sigstore https://www.python.org/ftp/python/3.14.10/windows-3.14.10.json.sigstore
Step 3: Check the SHA-256 checksum
Compute the hash
The command reads every byte of the file and prints its SHA-256 digest. Use whichever of these matches your shell. Both print the same 64 digits, though PowerShell writes them in capital letters.
sha256sum dl/python-3.13.14-amd64.exe
c54d9b9bbb8a36e6489363ddd01139707fd781d72f1f9e90c7ec65d0061368e0 *dl/python-3.13.14-amd64.exe
Get-FileHash dl/python-3.13.14-amd64.exe -Algorithm SHA256 | Format-List Algorithm, Hash
Algorithm : SHA256
Hash : C54D9B9BBB8A36E6489363DDD01139707FD781D72F1F9E90C7EC65D0061368E0
Compare it with the release page
Open the Python 3.13.14 release page and find the row “Windows installer (64-bit)”. Its SHA-256 column shows the digest split into four groups of 16 digits: c54d9b9bbb8a36e6 489363ddd0113970 7fd781d72f1f9e90 c7ec65d0061368e0. Join the groups and compare all 64 digits with the output above. They match. Compare the whole value, not the first few characters, because a tool that checked only a prefix would be easy to fool (one of the deliberately planted bugs in Step 10 does exactly that).
See what a one-bit change does
To see why a checksum catches damage, make a copy of the installer and change one bit in the middle of it. This small script does that, and you will reuse the damaged copy in later steps.
# flip_byte.py: copy a file and change one bit, to play a corrupted or tampered download.
# Usage: python flip_byte.py SOURCE OFFSET OUTPUT
import shutil
import sys
source, offset, output = sys.argv[1], int(sys.argv[2]), sys.argv[3]
shutil.copyfile(source, output)
with open(output, "r+b") as f:
f.seek(offset)
byte = f.read(1)[0]
f.seek(offset)
f.write(bytes([byte ^ 1]))
print(f"changed one bit of byte {offset:,} in {output}")
mkdir work
python flip_byte.py dl/python-3.13.14-amd64.exe 1000000 work/flipped.exe
sha256sum work/flipped.exe
changed one bit of byte 1,000,000 in work/flipped.exe
d77a8f2b377596af6f607883e45cda1a7f887d2cf648ff983bdce91e9c405112 *work/flipped.exe
One flipped bit out of roughly 234 million (the file is 29,225,624 bytes) produced a completely different digest: 58 of the 64 hexadecimal digits changed, and 129 of the 256 underlying bits. There is no such thing as a nearly matching checksum, which is exactly what you want.
What a match does and does not tell you
A match tells you the file you hold is identical to the one the page describes. It does not tell you the page is honest. If an attacker controls the server, they can replace the file and the hash printed beside it, and the two will agree. The checksum is still worth checking, because it catches truncated and corrupted downloads. But treat it as a baseline, and read on for the checks that need a fact the server cannot rewrite.
Step 4: Verify the GPG signature
GPG (GnuPG) implements the OpenPGP standard. The publisher keeps a private key secret and publishes the matching public key. A detached signature is a small separate file, here python-3.13.14-amd64.exe.asc, made with the private key over the contents of the installer. Verifying means asking gpg whether that signature fits this file and a public key you hold.
Look at the signature before you have any key
First create a throwaway keyring. That is a folder that holds only the keys you import for this job, so keys from your everyday life cannot vouch for the signer by accident. On Linux and macOS gpg expects the keyring folder to be private to you, and the chmod line makes it so (I did not run those systems). Then ask gpg to describe the signature:
mkdir gnupg_py
chmod 700 gnupg_py
gpg --homedir gnupg_py --list-packets dl/python-3.13.14-amd64.exe.asc
gpg: keybox 'gnupg_py/pubring.kbx' created
# off=0 ctb=89 tag=2 hlen=3 plen=540
:signature packet: algo 1, keyid FC624643487034E5
version 4, created 1781103911, md5len 0, sigclass 0x00
digest algo 8, begin of digest 6d 5c
hashed subpkt 2 len 4 (sig created 2026-06-10)
subpkt 16 len 8 (issuer key ID FC624643487034E5)
(Your output will show the full path of the keyring folder where this page prints the short one.) The signature says it was made by key FC624643487034E5 on 2026-06-10. That 16-digit value is a key ID, the last 16 digits of the key’s full 40-digit fingerprint. Now try to verify with an empty keyring:
gpg --homedir gnupg_py --verify dl/python-3.13.14-amd64.exe.asc dl/python-3.13.14-amd64.exe
gpg: Signature made Wed, Jun 10, 2026 11:05:11 AM EDT
gpg: using RSA key FC624643487034E5
gpg: Can't check signature: No public key
“No public key” is the correct answer: a signature is meaningless until you have the public half of the key that made it.
Get the public key from somewhere you can cross-check
The python.org OpenPGP page lists the signers. It names Steve Dower, who signs the Windows binaries, with key ID FC62 4643 4870 34E5, which matches the signature above. His entry links to a copy of his public key on Keybase, and that link carries the full fingerprint as a query parameter: 7ed10b6531d7c8e1bc296021fc624643487034e5. So you have the key file from one host (Keybase) and the fingerprint from another (python.org). Download the key and import it into the throwaway keyring, then print its fingerprint:
curl -sSfL -o dl/stevedower.asc "https://keybase.io/stevedower/pgp_keys.asc?fingerprint=7ed10b6531d7c8e1bc296021fc624643487034e5"
gpg --homedir gnupg_py --import dl/stevedower.asc
gpg --homedir gnupg_py --fingerprint
gpg: gnupg_py/trustdb.gpg: trustdb created
gpg: key FC624643487034E5: public key "Steve Dower (Python Release Signing) <[email protected]>" imported
gpg: Total number processed: 1
gpg: imported: 1
gnupg_py/pubring.kbx
----------------------------------------------------------------------------------
pub rsa4096 2015-04-06 [SC]
7ED1 0B65 31D7 C8E1 BC29 6021 FC62 4643 4870 34E5
uid [ unknown] Steve Dower (Python Release Signing) <[email protected]>
sub rsa4096 2015-04-06 [E]
The fingerprint gpg prints, 7ED1 0B65 31D7 C8E1 BC29 6021 FC62 4643 4870 34E5, equals the one in the link. Notice also the name on the key: Steve Dower (Python Release Signing) with an address at microsoft.com, not python.org. A name or e-mail address on a key is just a label that anyone can type, which is why you pin the fingerprint and do not trust the label.
Verify, and read the warning correctly
gpg --homedir gnupg_py --verify dl/python-3.13.14-amd64.exe.asc dl/python-3.13.14-amd64.exe
gpg: Signature made Wed, Jun 10, 2026 11:05:11 AM EDT
gpg: using RSA key FC624643487034E5
gpg: Good signature from "Steve Dower (Python Release Signing) <[email protected]>" [unknown]
gpg: WARNING: This key is not certified with a trusted signature!
gpg: There is no indication that the signature belongs to the owner.
Primary key fingerprint: 7ED1 0B65 31D7 C8E1 BC29 6021 FC62 4643 4870 34E5
Two things matter in this output. “Good signature” means the signature is mathematically valid for this file and this key. And the warning, This key is not certified with a trusted signature, means gpg has no record that anyone you trust has vouched for the key. That warning is expected on a fresh keyring and does not mean something is wrong. What replaces trust in a web of signatures is your own check: the primary key fingerprint on the last line must equal the fingerprint you obtained separately.
Get the same facts in a form a program can read
Humans read the lines above. Programs should read gpg’s status output, which --status-fd 1 writes to standard output. The GnuPG documentation says that “for each signature only one of the codes GOODSIG, BADSIG, EXPSIG, EXPKEYSIG, REVKEYSIG or ERRSIG will be emitted”, and that a valid signature also produces a line starting with VALIDSIG.
gpg --homedir gnupg_py --status-fd 1 --verify dl/python-3.13.14-amd64.exe.asc dl/python-3.13.14-amd64.exe
[GNUPG:] GOODSIG FC624643487034E5 Steve Dower (Python Release Signing) <[email protected]>
[GNUPG:] VALIDSIG 7ED10B6531D7C8E1BC296021FC624643487034E5 2026-06-10 1781103911 0 4 0 1 8 00 7ED10B6531D7C8E1BC296021FC624643487034E5
The VALIDSIG line holds the fingerprint of the signing key, the signature date and time, the expiry (0 means none), the signature version (4), a reserved field, the public-key algorithm (1, which gpg prints as RSA), the hash algorithm (8, SHA-256 in OpenPGP’s numbering), the signature class, and last of all the fingerprint of the primary key. That last field matters because a signature may be made by a subkey. As the GnuPG documentation puts it, “PRIMARY-KEY-FPR is the fingerprint of the primary key or identical to the first argument.” A verifier that wants to compare against the fingerprint you pinned should read that last field, and Step 7 does.
Step 5: Verify the Sigstore signature
How keyless signing works
Sigstore signs without a long-lived private key. As the Sigstore overview describes it, a client makes a key pair, asks a certificate authority for a short-lived certificate bound to the signer’s OpenID Connect identity and the new public key, signs the file, and discards the private key. The file’s digest, the signature and the certificate go into a public, append-only transparency log called Rekor. To verify, a client checks the signature, checks that “the identity in the certificate matches an expected identity”, checks the certificate against Sigstore’s root of trust, and checks proof of inclusion in the log.
The word to underline is expected. The python.org Sigstore page says: “Verification additionally requires prior knowledge of the identity of the signer.” For CPython that identity is the release manager’s e-mail address plus the identity provider that vouched for it. The page publishes a table: releases 3.12 and 3.13 are signed by [email protected] through https://accounts.google.com, and releases 3.14 and 3.15 by [email protected] through https://github.com/login/oauth.
Verify the installer
Run the command below. You must give both the identity and the issuer, and the Sigstore client refuses to run without them.
python -m sigstore verify identity --bundle dl/python-3.13.14-amd64.exe.sigstore --cert-identity [email protected] --cert-oidc-issuer https://accounts.google.com dl/python-3.13.14-amd64.exe
OK: dl\python-3.13.14-amd64.exe
“OK” is the whole answer. One detail worth knowing when you write a tool around it: this client prints the OK line to standard error, not standard output, so a script has to look at the exit code (0 for success) and at both streams.
Look inside the bundle
A .sigstore file is a JSON document, and you can read who signed it without verifying anything. The script below prints the signer’s identity, the identity provider, the certificate’s validity window and the log entry. It also understands the second kind of bundle you will meet in Step 9, so it is longer than this step needs.
# bundle_info.py: print who signed a .sigstore bundle, without verifying anything.
# Usage: python bundle_info.py FILE.sigstore [FILE.sigstore ...]
import base64
import json
import sys
from cryptography import x509
from cryptography.x509.oid import ExtensionOID
# Fulcio OIDs (Sigstore's certificate authority writes the OIDC issuer here).
OID_ISSUER_V1 = "1.3.6.1.4.1.57264.1.1"
OID_ISSUER_V2 = "1.3.6.1.4.1.57264.1.8"
def der_utf8(raw: bytes) -> str:
"""Read one DER UTF8String (tag 0x0c, short or long length form)."""
assert raw[0] == 0x0C, "not a UTF8String"
size, start = raw[1], 2
if size & 0x80:
count = size & 0x7F
size, start = int.from_bytes(raw[2:2 + count], "big"), 2 + count
return raw[start:start + size].decode("utf-8")
def read_cert(bundle: dict) -> x509.Certificate:
material = bundle["verificationMaterial"]
if "certificate" in material:
raw = material["certificate"]["rawBytes"]
else:
raw = material["x509CertificateChain"]["certificates"][0]["rawBytes"]
return x509.load_der_x509_certificate(base64.b64decode(raw))
def describe(path: str) -> None:
with open(path, encoding="utf-8") as f:
bundle = json.load(f)
cert = read_cert(bundle)
san = cert.extensions.get_extension_for_oid(ExtensionOID.SUBJECT_ALTERNATIVE_NAME).value
names = [str(n.value) for n in san]
issuer = None
for ext in cert.extensions:
raw = ext.value.value if hasattr(ext.value, "value") else b""
if ext.oid.dotted_string == OID_ISSUER_V1:
issuer = raw.decode("utf-8") # the original extension holds the bare text
elif ext.oid.dotted_string == OID_ISSUER_V2 and issuer is None:
issuer = der_utf8(raw) # the newer one wraps the text in a DER UTF8String
msg = bundle.get("messageSignature", {})
digest = msg.get("messageDigest", {})
tlog = bundle["verificationMaterial"].get("tlogEntries", [])
print(path)
print(" media type :", bundle.get("mediaType"))
print(" signer identity :", ", ".join(names))
print(" OIDC issuer :", issuer)
print(" cert valid :", cert.not_valid_before_utc.isoformat(), "to", cert.not_valid_after_utc.isoformat())
if digest:
print(" signed digest :", base64.b64decode(digest["digest"]).hex(), f"({digest.get('algorithm')})")
print(" log entries :", len(tlog), "kind:", tlog[0]["kindVersion"]["kind"] if tlog else None)
if tlog:
print(" log index :", tlog[0].get("logIndex"), "integrated time:", tlog[0].get("integratedTime"))
envelope = bundle.get("dsseEnvelope")
if envelope: # a GitHub attestation wraps an in-toto statement
statement = json.loads(base64.b64decode(envelope["payload"]))
names = [item["name"] for item in statement.get("subject", [])]
print(" statement type :", statement.get("predicateType"))
print(" files covered :", len(names), "for example", ", ".join(names[:3]))
deps = statement.get("predicate", {}).get("buildDefinition", {}).get("resolvedDependencies", [])
if deps:
print(" source commit :", deps[0]["uri"], deps[0]["digest"].get("gitCommit"))
if __name__ == "__main__":
for p in sys.argv[1:]:
describe(p)
python bundle_info.py dl/python-3.13.14-amd64.exe.sigstore
dl/python-3.13.14-amd64.exe.sigstore
media type : application/vnd.dev.sigstore.bundle.v0.3+json
signer identity : [email protected]
OIDC issuer : https://accounts.google.com
cert valid : 2026-06-10T16:04:16+00:00 to 2026-06-10T16:14:16+00:00
signed digest : c54d9b9bbb8a36e6489363ddd01139707fd781d72f1f9e90c7ec65d0061368e0 (SHA2_256)
log entries : 1 kind: hashedrekord
log index : 1780927999 integrated time: 1781107456
Three things stand out. The identity and issuer are exactly what the python.org table says to expect. The signed digest is c54d9b9b…, the same SHA-256 you computed in Step 3, so the signature covers the same bytes the checksum describes. And the certificate was valid for ten minutes only, from 16:04:16 to 16:14:16 UTC on 2026-06-10. I ran this verification on 2026-11-29, 172 days after that certificate expired, and it still passed. The Sigstore overview explains why: “someone who downloads an artifact can confirm that the certificate was valid at the time of signing”, because the log entry records when the signing happened.
There is a second lesson in the timing. The GPG signature from Step 4 was made at 15:05:11 UTC by Steve Dower, and the Sigstore entry was logged at 16:04:16 UTC under [email protected]. Two different people vouched for the same file, 59 minutes apart, through two unrelated systems. A policy that requires both asks an attacker to defeat both.
Watch it fail in three ways
A verifier is only useful if it fails when it should. Ask the client to accept a different identity, a different issuer, and then a damaged copy of the file:
python -m sigstore verify identity --bundle dl/python-3.13.14-amd64.exe.sigstore --cert-identity [email protected] --cert-oidc-issuer https://accounts.google.com dl/python-3.13.14-amd64.exe
[hh:mm:ss] ERROR FAIL: dl\python-3.13.14-amd64.exe _cli.py:1162
ERROR Certificate's SANs do not match errors.py:43
[email protected]; actual SANs:
{'[email protected]'}
For detailed error information, run sigstore
with the `--verbose` flag.
python -m sigstore verify identity --bundle dl/python-3.13.14-amd64.exe.sigstore --cert-identity [email protected] --cert-oidc-issuer https://github.com/login/oauth dl/python-3.13.14-amd64.exe
[hh:mm:ss] ERROR FAIL: dl\python-3.13.14-amd64.exe _cli.py:1162
ERROR Certificate's OIDCIssuer does not match (got errors.py:43
'https://accounts.google.com', expected
'https://github.com/login/oauth')
For detailed error information, run sigstore
with the `--verbose` flag.
python -m sigstore verify identity --bundle dl/python-3.13.14-amd64.exe.sigstore --cert-identity [email protected] --cert-oidc-issuer https://accounts.google.com work/flipped.exe
[hh:mm:ss] ERROR FAIL: work\flipped.exe _cli.py:1162
ERROR Bundle message digest mismatch errors.py:43
For detailed error information, run sigstore
with the `--verbose` flag.
The messages name the problem: the certificate’s identities do not match the one you pinned, the issuer does not match, and the bundle’s message digest does not match the file. (In the outputs on this page I replaced the clock time at the start of each error line with [hh:mm:ss].) Pinning the issuer as well as the e-mail address matters. The address alone does not say which identity provider vouched for it, which is why the python.org table lists the provider next to each address.
Step 6: Check the Windows Authenticode signature
Windows programs carry their own signature inside the file. The signer is a code-signing certificate, issued by a certificate authority after it checks who is asking, and the signature usually includes a timestamp from a timestamp authority so it stays valid after the certificate expires. PowerShell reads it with Get-AuthenticodeSignature. This short script prints the fields that matter, and the commands also download the 3.14.10 installer so you can compare two releases:
# authenticode_info.ps1: show what Windows says about the Authenticode signature of one or more files.
# Usage: powershell -NoProfile -File authenticode_info.ps1 file1.exe file2.exe
param([Parameter(ValueFromRemainingArguments = $true)][string[]]$Paths)
foreach ($p in $Paths) {
$s = Get-AuthenticodeSignature -LiteralPath $p
"{0}" -f (Split-Path $p -Leaf)
" Status : {0}" -f $s.Status
" Signer subject : {0}" -f $s.SignerCertificate.Subject
" Signer issuer : {0}" -f $s.SignerCertificate.Issuer
" Thumbprint : {0}" -f $s.SignerCertificate.Thumbprint
" Cert validity : {0:u} to {1:u}" -f $s.SignerCertificate.NotBefore, $s.SignerCertificate.NotAfter
$ts = $s.TimeStamperCertificate
if ($ts) { " Timestamped by : {0}" -f $ts.Subject } else { " Timestamped by : (none)" }
}
curl -sSfL -o dl/python-3.14.10-amd64.exe https://www.python.org/ftp/python/3.14.10/python-3.14.10-amd64.exe
powershell -NoProfile -ExecutionPolicy Bypass -File authenticode_info.ps1 dl/python-3.13.14-amd64.exe dl/python-3.14.10-amd64.exe C:/Windows/System32/notepad.exe work/flipped.exe
python-3.13.14-amd64.exe
Status : Valid
Signer subject : CN=Python Software Foundation, O=Python Software Foundation, L=Beaverton, S=Oregon, C=US
Signer issuer : CN=Microsoft ID Verified CS EOC CA 04, O=Microsoft Corporation, C=US
Thumbprint : 9BA3C2E210C7E8296C5056515BFC0B0BBA78AC48
Cert validity : 2026-06-09 03:34:58Z to 2026-06-12 03:34:58Z
Timestamped by : CN=Microsoft Public RSA Time Stamping Authority, OU=nShield TSS ESN:A500-05E0-D947, OU=Microsoft America Operations, O=Microsoft Corporation, L=Redmond, S=Washington, C=US
python-3.14.10-amd64.exe
Status : Valid
Signer subject : CN=Python Software Foundation, O=Python Software Foundation, L=Beaverton, S=Oregon, C=US
Signer issuer : CN=Microsoft ID Verified CS EOC CA 04, O=Microsoft Corporation, C=US
Thumbprint : 6C435B1CAA2CA423A76C14A6693CD55644C8B4D6
Cert validity : 2026-10-24 03:24:25Z to 2026-10-27 03:24:25Z
Timestamped by : CN=Microsoft Public RSA Time Stamping Authority, OU=nShield TSS ESN:A500-05E0-D947, OU=Microsoft America Operations, O=Microsoft Corporation, L=Redmond, S=Washington, C=US
notepad.exe
Status : Valid
Signer subject : CN=Microsoft Windows, O=Microsoft Corporation, L=Redmond, S=Washington, C=US
Signer issuer : CN=Microsoft Windows Production PCA 2026 RSA2048-SHA256, O=Microsoft Corporation, C=US
Thumbprint : AD714D3C4B2B794A95441375C954130E9109EF4C
Cert validity : 2026-08-06 13:49:19Z to 2027-08-05 13:49:19Z
Timestamped by : CN=Microsoft Time-Stamp Service, OU=nShield TSS ESN:651A-05E0-D947, OU=Microsoft Ireland Operations Limited, O=Microsoft Corporation, L=Redmond, S=Washington, C=US
flipped.exe
Status : HashMismatch
Signer subject : CN=Python Software Foundation, O=Python Software Foundation, L=Beaverton, S=Oregon, C=US
Signer issuer : CN=Microsoft ID Verified CS EOC CA 04, O=Microsoft Corporation, C=US
Thumbprint : 9BA3C2E210C7E8296C5056515BFC0B0BBA78AC48
Cert validity : 2026-06-09 03:34:58Z to 2026-06-12 03:34:58Z
Timestamped by : CN=Microsoft Public RSA Time Stamping Authority, OU=nShield TSS ESN:A500-05E0-D947, OU=Microsoft America Operations, O=Microsoft Corporation, L=Redmond, S=Washington, C=US
Read the four results one at a time, because each teaches something different.
The genuine installers
Both Python installers report Valid, with the signer CN=Python Software Foundation, O=Python Software Foundation, L=Beaverton, S=Oregon, C=US and the issuing authority CN=Microsoft ID Verified CS EOC CA 04. Two details shape how you pin them. The certificates last only three days (2026-06-09 to 2026-06-12 for 3.13.14, and 2026-10-24 to 2026-10-27 for 3.14.10), and each has a different thumbprint. So pin the publisher’s name and the issuer, not the thumbprint, or your check will break at the next release. The 3.13.14 certificate expired months ago, yet Windows still reports Valid, because the signature carries a timestamp from a timestamp authority that was made while the certificate was still in date.
Valid is not the same as the right publisher
The third file is Windows’ own notepad.exe, and it also says Valid, signed by Microsoft Windows. If your only test were is the status Valid, a perfectly good Microsoft file would pass as a Python installer. Microsoft’s own documentation of the status values says it: Valid means “only that the signature is syntactically valid. It does not imply trust in any way.” Trust comes from comparing the signer with the publisher you expect.
A damaged file still shows the publisher’s name
The last file is the one-bit-damaged copy from Step 3. Its status is HashMismatch, which the same documentation defines as “the hash of the file does not match the hash stored along with the signature”. Yet the signer lines still show the Python Software Foundation. The name is read from the certificate stored in the file, and the damage does not change that certificate. So never read the signer name on its own. Read the status first, then the signer, and require both.
Step 7: Put it together in a verifier that pins everything
The design
You have now done four checks by hand. Doing them by hand each time invites mistakes, so you will write them down once as a policy (a small JSON file listing what you expect and where you learned it) and let a program check the download against it. The program follows four rules that come straight from the lessons above. Every layer you list must pass. A layer with a misspelled name is an error, not a skipped check. Anything that cannot be checked counts as a failure. And a policy that lists only a checksum is allowed to pass, but the program says so loudly with its own exit code. The exit codes are 0 (all listed checks passed and at least one was a signature), 1 (a check failed), 2 (the policy or the command line is wrong) and 3 (only a checksum was listed).
The shared pieces and the checksum check
The first part defines the result type and the SHA-256 check. It strips spaces from the expected value (python.org prints it in four groups), lowercases it, requires 64 hexadecimal digits, and reads the file in one-megabyte chunks so a large installer does not have to fit in memory.
"""verify_download.py: check a downloaded file against a policy you wrote yourself.
Exit codes: 0 every listed check passed and at least one signature layer was listed
1 a listed check failed
2 the policy or the command line is wrong (unknown key, missing file)
3 only a checksum was listed: it passed, but that proves very little
"""
import argparse
import hashlib
import json
import os
import re
import subprocess
import sys
import tempfile
from dataclasses import dataclass
from functools import lru_cache
from pathlib import Path
HEX64 = re.compile(r"[0-9a-f]{64}")
HEX40 = re.compile(r"[0-9A-F]{40}")
# GnuPG status words that mean "do not trust this signature", even though gpg may still say Good.
BAD_GPG = {"BADSIG", "ERRSIG", "EXPSIG", "EXPKEYSIG", "REVKEYSIG"}
LAYERS = {"sha256", "gpg", "sigstore", "github", "authenticode"}
@dataclass
class Result:
layer: str
ok: bool
detail: str
def check_sha256(path, expected):
want = re.sub(r"\s+", "", expected).lower()
if not HEX64.fullmatch(want):
return Result("sha256", False, "the expected value is not 64 hex digits")
digest = hashlib.sha256()
with open(path, "rb") as f:
for chunk in iter(lambda: f.read(1 << 20), b""):
digest.update(chunk)
got = digest.hexdigest()
return Result("sha256", got == want, f"file {got[:16]}... expected {want[:16]}...")
Running other programs without hanging
The verifier runs gpg, Sigstore and PowerShell as separate programs. The helper collects their output through temporary files instead of pipes. I learned why the hard way, and the end of this step explains it.
# verify_download.py (continued)
def _run(cmd, cwd=None):
"""Run a command and capture its output through temporary files, not pipes.
gpg may start a background gpg-agent that inherits the pipes; a pipe then never reaches
end-of-file and subprocess.run waits for the agent to exit.
"""
try:
with tempfile.TemporaryFile() as out, tempfile.TemporaryFile() as err:
done = subprocess.run(cmd, stdin=subprocess.DEVNULL, stdout=out, stderr=err, timeout=300, cwd=cwd)
out.seek(0)
err.seek(0)
return subprocess.CompletedProcess(cmd, done.returncode, out.read().decode("utf-8", "replace"), err.read().decode("utf-8", "replace"))
except (OSError, subprocess.TimeoutExpired) as exc:
return subprocess.CompletedProcess(cmd, 127, "", f"{type(exc).__name__}: {exc}")
The GPG check
This is the most careful part. It creates a fresh keyring for every call. It first reads the key file without importing it and refuses to continue unless the file holds the fingerprint you pinned. It then imports the key and verifies with the status output. It rejects the signature if any warning code appears (a bad signature, an error, an expired signature, an expired key, a revoked key), requires exactly one VALIDSIG line, and compares the primary key fingerprint, the last field, with your pin. The two small helpers above it exist because of a Windows quirk covered below.
# verify_download.py (continued)
@lru_cache(maxsize=None)
def _msys_style(gpg):
"""Git for Windows ships an MSYS build of gpg: it prints Home: /c/Users/... and reads C:/... as a relative path."""
if sys.platform != "win32":
return False
found = re.search(r"^Home:\s*(\S+)", _run([gpg, "--version"]).stdout, re.M)
return bool(found and found.group(1).startswith("/"))
def gpg_path(gpg, path):
text = Path(path).resolve().as_posix()
if _msys_style(gpg) and re.match(r"[A-Za-z]:/", text):
return "/" + text[0].lower() + text[2:]
return text
def check_gpg(path, sig, key_file, fingerprint, gpg="gpg", extra=()):
want = re.sub(r"\s+", "", fingerprint).upper()
if not HEX40.fullmatch(want):
return Result("gpg", False, "the pinned fingerprint is not 40 hex digits")
with tempfile.TemporaryDirectory() as home:
os.chmod(home, 0o700)
base = [gpg, "--homedir", gpg_path(gpg, home), "--batch", "--no-tty"]
shown = _run(base + ["--with-colons", "--show-keys", gpg_path(gpg, key_file)])
if shown.returncode != 0:
return Result("gpg", False, "cannot read the key file: " + shown.stderr.strip()[:120])
primaries, next_is_primary = [], False
for line in shown.stdout.splitlines():
fields = line.split(":")
if fields[0] == "pub":
next_is_primary = True
elif fields[0] == "fpr" and next_is_primary:
primaries.append(fields[9].upper())
next_is_primary = False
if want not in primaries:
return Result("gpg", False, "the key file does not hold the pinned key; it holds " + ", ".join(primaries))
imported = _run(base + ["--import", gpg_path(gpg, key_file)])
if imported.returncode != 0:
return Result("gpg", False, "key import failed")
verdict = _run(base + list(extra) + ["--status-fd", "1", "--verify", gpg_path(gpg, sig), gpg_path(gpg, path)])
words = [ln[9:].split() for ln in verdict.stdout.splitlines() if ln.startswith("[GNUPG:] ")]
bad = sorted({w[0] for w in words if w and w[0] in BAD_GPG})
valid = [w for w in words if w and w[0] == "VALIDSIG"]
if verdict.returncode != 0 or bad or len(valid) != 1:
return Result("gpg", False, "gpg refused the signature " + " ".join(bad or ["(no VALIDSIG)"]))
signer = valid[0][-1].upper() # the last VALIDSIG field is the primary key, even if a subkey signed
return Result("gpg", signer == want, f"signed by primary key {signer[-16:]}, pinned {want[-16:]}")
The Sigstore and GitHub checks
These call the documented command line, python -m sigstore verify, instead of the library’s internals. The command line is the interface python.org documents, so it is the one least likely to change under you. The helper turns sigstore’s wrapped log table into one readable sentence. Both checks run from the file’s own folder with a short file name, which keeps that error table from wrapping a long path across lines.
# verify_download.py (continued)
def _sigstore_result(layer, run, name, ok_detail):
# sigstore prints "OK: file" to stderr on success and a wrapped log table on failure.
if run.returncode == 0 and "OK:" in run.stdout + run.stderr:
return Result(layer, True, ok_detail)
text = re.sub(r"\[\d\d:\d\d:\d\d\]|ERROR|_cli\.py:\d+|errors\.py:\d+|For detailed error information.*$", "", " ".join(run.stderr.split()))
text = text.replace("FAIL: " + name, "")
return Result(layer, False, " ".join(text.split())[:150] or "sigstore failed")
def check_sigstore(path, bundle, identity, issuer, python=sys.executable):
path = Path(path).resolve()
cmd = [python, "-m", "sigstore", "verify", "identity", "--bundle", str(Path(bundle).resolve()),
"--cert-identity", identity, "--cert-oidc-issuer", issuer, path.name]
run = _run(cmd, cwd=path.parent) # a short file name keeps sigstore's wrapped error table readable
return _sigstore_result("sigstore", run, path.name, f"identity {identity} via {issuer}")
def check_github(path, bundle, repository, python=sys.executable):
"""A GitHub artifact attestation is a Sigstore bundle signed by a GitHub Actions workflow."""
path = Path(path).resolve()
cmd = [python, "-m", "sigstore", "verify", "github", "--bundle", str(Path(bundle).resolve()),
"--repository", repository, path.name]
run = _run(cmd, cwd=path.parent)
return _sigstore_result("github", run, path.name, f"built by a workflow in {repository}")
The Authenticode check
The PowerShell snippet returns the status, the signer and the issuer as JSON. The check passes only if the status is Valid and the signer and issuer are exactly the strings you pinned. On a system without PowerShell’s Authenticode support the check fails instead of quietly passing.
# verify_download.py (continued)
PS_SCRIPT = r"""
param($Path)
$s = Get-AuthenticodeSignature -LiteralPath $Path
[pscustomobject]@{
Status = [string]$s.Status
Subject = [string]$s.SignerCertificate.Subject
Issuer = [string]$s.SignerCertificate.Issuer
} | ConvertTo-Json -Compress
"""
def read_authenticode(path):
if sys.platform != "win32":
return None
with tempfile.TemporaryDirectory() as tmp:
script = Path(tmp) / "sig.ps1"
script.write_text(PS_SCRIPT, encoding="utf-8")
run = _run(["powershell.exe", "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", str(script), str(path)])
try:
return json.loads(run.stdout)
except ValueError:
return None
def check_authenticode(path, subject, issuer):
info = read_authenticode(path)
if info is None:
return Result("authenticode", False, "cannot read an Authenticode signature on this system")
ok = info["Status"] == "Valid" and info["Subject"] == subject and info["Issuer"] == issuer
return Result("authenticode", ok, f"status {info['Status']}, signer {info['Subject'][:60]}")
The policy runner and the command line
The last part reads the policy, rejects unknown layer names, checks that the target file exists, runs each layer you listed, and decides the exit code.
# verify_download.py (continued)
def run_policy(policy_file, target, gpg="gpg"):
policy_file = Path(policy_file)
try:
policy = json.loads(policy_file.read_text(encoding="utf-8"))
except (OSError, ValueError) as exc:
return [], 2, f"cannot read the policy: {exc}"
unknown = sorted(set(policy) - LAYERS)
if unknown or not policy:
return [], 2, "unknown or missing layers in the policy: " + (", ".join(unknown) or "(empty)")
target = Path(target)
if not target.is_file():
return [], 2, f"no such file: {target}"
here = policy_file.parent
results = []
if "sha256" in policy:
results.append(check_sha256(target, policy["sha256"]))
if "gpg" in policy:
g = policy["gpg"]
results.append(check_gpg(target, here / g["signature"], here / g["key_file"], g["fingerprint"], gpg=gpg))
if "sigstore" in policy:
s = policy["sigstore"]
results.append(check_sigstore(target, here / s["bundle"], s["identity"], s["issuer"]))
if "github" in policy:
h = policy["github"]
results.append(check_github(target, here / h["bundle"], h["repository"]))
if "authenticode" in policy:
a = policy["authenticode"]
results.append(check_authenticode(target, a["subject"], a["issuer"]))
if any(not r.ok for r in results):
return results, 1, "FAILED: do not run this file"
if all(r.layer == "sha256" for r in results):
return results, 3, "WEAK: only a checksum was checked"
return results, 0, "VERIFIED: every listed check passed"
def main(argv=None):
parser = argparse.ArgumentParser(description="Verify a download against a policy file.")
parser.add_argument("policy")
parser.add_argument("file")
parser.add_argument("--gpg", default=os.environ.get("GPG", "gpg"))
args = parser.parse_args(argv)
results, code, message = run_policy(args.policy, args.file, gpg=args.gpg)
for r in results:
print(f"{'PASS' if r.ok else 'FAIL'} {r.layer:<13}{r.detail}")
print(message)
return code
if __name__ == "__main__":
sys.exit(main())
Write the policies
Now record what you learned, and where each value came from. The checksum came from the python.org release page (Step 3). The fingerprint came from the link on the python.org OpenPGP page (Step 4), and the key file from Keybase. The Sigstore identity and issuer came from the python.org Sigstore table (Step 5). The Authenticode strings came from the output of Step 6. Paths inside a policy are relative to the policy file.
{
"sha256": "c54d9b9bbb8a36e6 489363ddd0113970 7fd781d72f1f9e90 c7ec65d0061368e0",
"gpg": {
"signature": "dl/python-3.13.14-amd64.exe.asc",
"key_file": "dl/stevedower.asc",
"fingerprint": "7ED1 0B65 31D7 C8E1 BC29 6021 FC62 4643 4870 34E5"
},
"sigstore": {
"bundle": "dl/python-3.13.14-amd64.exe.sigstore",
"identity": "[email protected]",
"issuer": "https://accounts.google.com"
},
"authenticode": {
"subject": "CN=Python Software Foundation, O=Python Software Foundation, L=Beaverton, S=Oregon, C=US",
"issuer": "CN=Microsoft ID Verified CS EOC CA 04, O=Microsoft Corporation, C=US"
}
}
For contrast, here is the weakest possible policy, with only the checksum:
{
"sha256": "c54d9b9bbb8a36e6 489363ddd0113970 7fd781d72f1f9e90 c7ec65d0061368e0"
}
Run it
First the honest download. In Git Bash you can print the exit code with echo $?, and in PowerShell with $LASTEXITCODE; the commands below add the echo for you.
python verify_download.py policy_python_3_13_14.json dl/python-3.13.14-amd64.exe
PASS sha256 file c54d9b9bbb8a36e6... expected c54d9b9bbb8a36e6...
PASS gpg signed by primary key FC624643487034E5, pinned FC624643487034E5
PASS sigstore identity [email protected] via https://accounts.google.com
PASS authenticode status Valid, signer CN=Python Software Foundation, O=Python Software Foundation,
VERIFIED: every listed check passed
exit code: 0
All four layers pass and the exit code is 0. Now the damaged copy from Step 3 against the same policy:
python verify_download.py policy_python_3_13_14.json work/flipped.exe
FAIL sha256 file d77a8f2b377596af... expected c54d9b9bbb8a36e6...
FAIL gpg gpg refused the signature BADSIG
FAIL sigstore Bundle message digest mismatch
FAIL authenticode status HashMismatch, signer CN=Python Software Foundation, O=Python Software Foundation,
FAILED: do not run this file
exit code: 1
Every layer fails, each for its own reason: the digest differs, gpg reports BADSIG, Sigstore reports a digest mismatch, and Windows reports HashMismatch. Exit code 1. Next the checksum-only policy:
python verify_download.py policy_hash_only.json dl/python-3.13.14-amd64.exe
PASS sha256 file c54d9b9bbb8a36e6... expected c54d9b9bbb8a36e6...
WEAK: only a checksum was checked
exit code: 3
The checksum passes, but the tool answers “WEAK” and exits with 3, so a script that treats only 0 as success will not accept it. Finally, a policy with one letter missing from the word sigstore. This small script makes the copy:
# make_typo_policy.py: copy the policy and misspell one layer name, to see what the verifier does with a typo.
from pathlib import Path
text = Path("policy_python_3_13_14.json").read_text(encoding="utf-8")
Path("policy_typo.json").write_text(text.replace('"sigstore"', '"sigstor"'), encoding="utf-8")
python make_typo_policy.py
python verify_download.py policy_typo.json dl/python-3.13.14-amd64.exe
unknown or missing layers in the policy: sigstor
exit code: 2
A typo does not silently drop the Sigstore check. It stops the run with exit code 2. If the tool had skipped unknown names, a misspelling would have turned a four-layer policy into a one-layer policy without a word of warning.
Two things that went wrong while I built it
The gpg that ships with Git for Windows reads C:/ paths as relative ones. It is an MSYS program: its gpg --version prints Home: /c/Users/..., and a path such as C:/Users/me/tmp passed from Python turned into a nonexistent folder under the current directory. The helper gpg_path asks gpg which style it uses and converts C:/x to /c/x only when gpg’s own Home: line starts with a slash. I tested only the Git for Windows build, not the native Windows build (Gpg4win).
A pipe held open by gpg-agent made the first test run hang for eight minutes. When gpg needs its background agent (to create a key or to sign), it starts one, and the agent inherits the pipes Python opened to capture output. A pipe does not reach end-of-file until every process holding it exits, so subprocess.run(capture_output=True) waited for an agent that never left. Capturing into temporary files fixed it, and that is why _run looks the way it does.
Step 8: Try six pretend attacks
You now have a verifier. Does it do what the table at the top promised? The script below builds six pretend downloads and runs all four layers on each. Everything the “attacker” does happens locally, with copies of the files you already hold and with throwaway keys. Nothing is sent to anyone except Sigstore’s own lookups.
"""attack_matrix.py: run the four checks against six pretend downloads and print which check stops which attack.
Needs ./dl from the download step, gpg on PATH and the lab venv (sigstore installed).
Nothing leaves this machine except sigstore's own lookups; the "attacker" files are local copies.
"""
import hashlib
import os
import shutil
import sys
import tempfile
from pathlib import Path
import verify_download as vd
HERE = Path(__file__).resolve().parent
DL = HERE / "dl"
GPG = os.environ.get("GPG", "gpg")
PAGE_SHA256 = "c54d9b9bbb8a36e6489363ddd01139707fd781d72f1f9e90c7ec65d0061368e0" # python.org release page
REAL_FPR = "7ED10B6531D7C8E1BC296021FC624643487034E5" # Steve Dower, from the python.org keys page
REAL_UID = "Steve Dower (Python Release Signing) <[email protected]>"
PSF = "CN=Python Software Foundation, O=Python Software Foundation, L=Beaverton, S=Oregon, C=US"
PSF_ISSUER = "CN=Microsoft ID Verified CS EOC CA 04, O=Microsoft Corporation, C=US"
THOMAS = ("[email protected]", "https://accounts.google.com")
def sha256_of(path):
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
def gpg_run(home, *args):
cmd = [GPG, "--homedir", vd.gpg_path(GPG, home), "--batch", "--no-tty", "--pinentry-mode", "loopback", "--passphrase", "", *args]
return vd._run(cmd)
def make_lookalike(work, signed_file):
"""A throwaway key with the real release signer's name and e-mail, and a signature made with it."""
home = work / "lookalike_home"
home.mkdir()
os.chmod(home, 0o700)
gpg_run(home, "--quick-generate-key", REAL_UID, "ed25519", "sign", "never")
listing = gpg_run(home, "--with-colons", "--list-keys").stdout
fake_fpr = [ln.split(":")[9] for ln in listing.splitlines() if ln.startswith("fpr")][0]
pub, sig = work / "lookalike.pub.asc", work / "lookalike.exe.asc"
gpg_run(home, "--armor", "--output", vd.gpg_path(GPG, pub), "--export", fake_fpr)
gpg_run(home, "--armor", "--detach-sign", "--output", vd.gpg_path(GPG, sig), vd.gpg_path(GPG, signed_file))
return home, fake_fpr, pub, sig
def cell(result):
return "pass" if result.ok else "FAIL"
def main():
real = DL / "python-3.13.14-amd64.exe"
work = Path(tempfile.mkdtemp(prefix="attacks"))
try:
damaged = work / "damaged.exe"
data = bytearray(real.read_bytes())
data[1_000_000] ^= 1 # one flipped bit in 29 million bytes
damaged.write_bytes(bytes(data))
damaged_sha = sha256_of(damaged)
home, fake_fpr, fake_pub, fake_sig = make_lookalike(work, damaged)
asc, bundle, real_key = DL / (real.name + ".asc"), DL / (real.name + ".sigstore"), DL / "stevedower.asc"
rows = []
def run_row(name, file, page_hash, gpg_sig, gpg_key, sig_bundle):
rows.append((name, [
vd.check_sha256(file, page_hash),
vd.check_gpg(file, gpg_sig, gpg_key, REAL_FPR, gpg=GPG),
vd.check_sigstore(file, sig_bundle, *THOMAS),
vd.check_authenticode(file, PSF, PSF_ISSUER),
]))
run_row("1 honest download", real, PAGE_SHA256, asc, real_key, bundle)
run_row("2 damaged in transit", damaged, PAGE_SHA256, asc, real_key, bundle)
run_row("3 server swaps file and page hash", damaged, damaged_sha, asc, real_key, bundle)
run_row("4 ... and adds a lookalike key and signature", damaged, damaged_sha, fake_sig, fake_pub, bundle)
print(f"{'pretend download':<46}{'SHA-256':<10}{'GPG pin':<10}{'Sigstore':<10}Authenticode")
for name, results in rows:
print(f"{name:<46}" + "".join(f"{cell(r):<10}" for r in results[:3]) + cell(results[3]))
print("\nwhat plain gpg says about row 4 when you import the key the server offered:")
plain_home = work / "plain_home"
plain_home.mkdir()
os.chmod(plain_home, 0o700)
base = [GPG, "--homedir", vd.gpg_path(GPG, plain_home), "--batch", "--no-tty"]
vd._run(base + ["--import", vd.gpg_path(GPG, fake_pub)])
said = vd._run(base + ["--verify", vd.gpg_path(GPG, fake_sig), vd.gpg_path(GPG, damaged)]).stderr
for line in said.splitlines():
if "Good signature" in line or "fingerprint" in line.lower() or "WARNING" in line:
print(" " + line.strip())
print(f" real fingerprint {REAL_FPR}\n lookalike {fake_fpr}")
print("what the pinned check says:", vd.check_gpg(damaged, fake_sig, fake_pub, REAL_FPR, gpg=GPG).detail)
print("\ntwo more cases, one layer each:")
manifest, hugo_bundle = DL / "windows-3.14.10.json", DL / "windows-3.14.10.json.sigstore"
valid_but_other = vd.check_sigstore(manifest, hugo_bundle, "[email protected]", "https://github.com/login/oauth")
pinned_wrong = vd.check_sigstore(manifest, hugo_bundle, *THOMAS)
print(f" genuine 3.14.10 bundle, asked who signed it: {valid_but_other.detail}")
print(f" same bundle, but you pinned the 3.13 signer : {cell(pinned_wrong)} {pinned_wrong.detail}")
notepad = Path(os.environ.get("SystemRoot", r"C:\Windows")) / "System32" / "notepad.exe"
info = vd.read_authenticode(notepad)
wrong_publisher = vd.check_authenticode(notepad, PSF, PSF_ISSUER)
print(f" notepad.exe: Windows says {info['Status']} for signer {info['Subject'][:30]}; pinned to the PSF: {cell(wrong_publisher)}")
finally:
for h in work.glob("*_home"):
vd._run(["gpgconf", "--homedir", vd.gpg_path(GPG, h), "--kill", "gpg-agent"])
shutil.rmtree(work, ignore_errors=True)
if __name__ == "__main__":
sys.exit(main())
python attack_matrix.py
pretend download SHA-256 GPG pin Sigstore Authenticode
1 honest download pass pass pass pass
2 damaged in transit FAIL FAIL FAIL FAIL
3 server swaps file and page hash pass FAIL FAIL FAIL
4 ... and adds a lookalike key and signature pass FAIL FAIL FAIL
what plain gpg says about row 4 when you import the key the server offered:
gpg: Good signature from "Steve Dower (Python Release Signing) <[email protected]>" [unknown]
gpg: WARNING: This key is not certified with a trusted signature!
Primary key fingerprint: D47B 784D FB02 5088 0C0A EE5D 6BFF E1CD 9911 C408
real fingerprint 7ED10B6531D7C8E1BC296021FC624643487034E5
lookalike D47B784DFB0250880C0AEE5D6BFFE1CD9911C408
what the pinned check says: the key file does not hold the pinned key; it holds D47B784DFB0250880C0AEE5D6BFFE1CD9911C408
two more cases, one layer each:
genuine 3.14.10 bundle, asked who signed it: identity [email protected] via https://github.com/login/oauth
same bundle, but you pinned the 3.13 signer : FAIL Certificate's OIDCIssuer does not match (got 'https://github.com/login/oauth', expected 'https://accounts.google.com')
notepad.exe: Windows says Valid for signer CN=Microsoft Windows, O=Micros; pinned to the PSF: FAIL
Reading the table
Row 1 is the honest download, and everything passes. Row 2 is damage in transit, and everything fails, which is what checksums are for. Row 3 is the important one: the attacker controls the server and replaces both the file and the hash on the page. The SHA-256 column says pass, because the file and the hash the page now shows agree, while the three layers that rely on facts the server does not control (the pinned GPG key, the pinned Sigstore identity, the pinned Windows publisher) all fail.
Row 4 goes further. The attacker also generates a key that copies the real signer’s name and e-mail address, signs the bad file, and serves the key and signature as well. The lines under the table show what plain gpg says if you import the key the server offered: it prints Good signature from "Steve Dower (Python Release Signing) <[email protected]>", the exact label of the real signer. Only the fingerprint line differs, and only a person who compared it against a fingerprint learned elsewhere would notice. The pinned check does not need a human to be careful: the key file does not hold the pinned key, so it fails.
The last two lines cover cases that fit in one layer each. A genuine bundle from a different identity verifies cryptographically, but a client that was told to expect the 3.13 signer rejects it. And notepad.exe is genuinely signed by Microsoft, so Windows says Valid, but pinned to the Python Software Foundation it fails.
What the table does not show
No row is an attacker who has stolen a signer’s account or compromised the build pipeline. Against that attacker every layer here passes, because the signature really is genuine. That limit gets its own section below.
Step 9: Verify a GitHub artifact attestation
Many projects now publish GitHub artifact attestations, some of them in place of GPG files. An attestation is a Sigstore bundle, so you already know how to read one. It is signed by the identity of the build workflow, which Sigstore’s certificate authority certifies after checking a token from GitHub Actions, and its payload is a statement about what was built. GitHub serves the attestations for a file through its API, looked up by the file’s SHA-256 digest. You can try it with a small, real example, the source tarball of jq 1.8.2 (about 2 MB). This script downloads the file, computes its digest, asks the API for the attestation, and saves the bundle:
# fetch_attestation.py: download a release file and the GitHub artifact attestation made for it.
# Usage: python fetch_attestation.py OWNER/REPO TAG ASSET OUTDIR
import hashlib
import json
import sys
import urllib.request
from pathlib import Path
repo, tag, asset, outdir = sys.argv[1:5]
out = Path(outdir)
out.mkdir(parents=True, exist_ok=True)
def fetch(url, accept="application/vnd.github+json"):
request = urllib.request.Request(url, headers={"User-Agent": "download-verification-lab", "Accept": accept})
with urllib.request.urlopen(request, timeout=60) as response:
return response.read()
data = fetch(f"https://github.com/{repo}/releases/download/{tag}/{asset}", accept="*/*")
(out / asset).write_bytes(data)
digest = hashlib.sha256(data).hexdigest()
reply = json.loads(fetch(f"https://api.github.com/repos/{repo}/attestations/sha256:{digest}"))
bundles = [item["bundle"] for item in reply["attestations"]]
bundle_path = out / f"{asset}.attestation.sigstore.json"
bundle_path.write_text(json.dumps(bundles[0]), encoding="utf-8")
print(f"downloaded {asset}: {len(data):,} bytes, sha256 {digest}")
print(f"GitHub returned {len(bundles)} attestation(s); saved the first as {bundle_path}")
python fetch_attestation.py jqlang/jq jq-1.8.2 jq-1.8.2.tar.gz dl/jq
downloaded jq-1.8.2.tar.gz: 1,959,950 bytes, sha256 71b8d6e8f5fe81f6c6d0d110e3892251f6ce76ed095abd315e26e6e1193af3af
GitHub returned 1 attestation(s); saved the first as dl\jq\jq-1.8.2.tar.gz.attestation.sigstore.json
Look inside the bundle with the same script as before:
python bundle_info.py dl/jq/jq-1.8.2.tar.gz.attestation.sigstore.json
dl/jq/jq-1.8.2.tar.gz.attestation.sigstore.json
media type : application/vnd.dev.sigstore.bundle.v0.3+json
signer identity : https://github.com/jqlang/jq/.github/workflows/ci.yml@refs/tags/jq-1.8.2
OIDC issuer : https://token.actions.githubusercontent.com
cert valid : 2026-06-20T14:10:23+00:00 to 2026-06-20T14:20:23+00:00
log entries : 1 kind: dsse
log index : 1884519155 integrated time: 1781964623
statement type : https://slsa.dev/provenance/v1
files covered : 27 for example jq-1.8.2.tar.gz, jq-1.8.2.zip, jq-linux-amd64
source commit : git+https://github.com/jqlang/jq@refs/tags/jq-1.8.2 34f7186b86743a083a589741b6cea95293524108
The signer identity is no longer a person. It is a workflow file in the jq repository at a release tag, and the issuer is GitHub’s Actions identity service. The payload is an in-toto statement (a standard envelope for claims about software) of the SLSA provenance type. It lists 27 files from this release, including the one you downloaded, and records the exact source commit. That is a claim about how the file was built, which is different from a person vouching for it.
The Sigstore client has a command for this kind of bundle, sigstore verify github, and the verifier’s github layer calls it with the repository you expect. Write the policy and run it:
{
"sha256": "71b8d6e8f5fe81f6c6d0d110e3892251f6ce76ed095abd315e26e6e1193af3af",
"github": {
"bundle": "dl/jq/jq-1.8.2.tar.gz.attestation.sigstore.json",
"repository": "jqlang/jq"
}
}
python verify_download.py policy_jq.json dl/jq/jq-1.8.2.tar.gz
PASS sha256 file 71b8d6e8f5fe81f6... expected 71b8d6e8f5fe81f6...
PASS github built by a workflow in jqlang/jq
VERIFIED: every listed check passed
exit code: 0
Now check that it rejects the wrong repository, the way an attacker’s fork would look:
python -m sigstore verify github --bundle dl/jq/jq-1.8.2.tar.gz.attestation.sigstore.json --repository someone-else/jq dl/jq/jq-1.8.2.tar.gz
[hh:mm:ss] ERROR FAIL: dl\jq\jq-1.8.2.tar.gz _cli.py:1215
ERROR Certificate's GitHubWorkflowRepository does errors.py:43
not match (got 'jqlang/jq', expected
'someone-else/jq')
For detailed error information, run sigstore
with the `--verbose` flag.
Note what the first check proved and what it did not. It proved that a workflow in jqlang/jq produced this file. It did not prove that the code in the repository is free of bugs or backdoors, and it did not prove that the workflow was not tampered with. The next sections return to that limit.
Step 10: Test the verifier, then break it on purpose
The test suite
A security tool deserves tests that try to defeat it. The suite below has 29 tests. They make throwaway GPG keys on the spot, including a look-alike key with the same name as the real signer, a key with a signing subkey, and a key that expires after one day (checked with gpg’s --faked-system-time option to jump ten days ahead). The Sigstore tests use the real python.org bundles from Step 2 and the jq bundle from Step 9. The Authenticode tests run on Windows only. Read the test names first, since each one states a rule the verifier must keep.
"""test_verify_download.py: tests for verify_download.py.
GPG tests use throwaway keys made on the spot. Sigstore tests use the real files in ./dl (set
VERIFY_LAB_DL to point elsewhere) and need network access. Authenticode tests run on Windows only.
"""
import json
import os
import shutil
import sys
import tempfile
import time
from pathlib import Path
import pytest
import verify_download as vd
GPG = os.environ.get("GPG", "gpg")
DL = Path(os.environ.get("VERIFY_LAB_DL", Path(__file__).resolve().parent / "dl"))
needs_gpg = pytest.mark.skipif(shutil.which(GPG) is None, reason="gpg is not installed")
needs_windows = pytest.mark.skipif(sys.platform != "win32", reason="Authenticode is Windows only")
needs_sigstore = pytest.mark.skipif(not (DL / "windows-3.13.14.json").exists(), reason="run the download step first")
UID = "Release Signing <[email protected]>"
THOMAS = ("[email protected]", "https://accounts.google.com")
def run_gpg(home, *args):
cmd = [GPG, "--homedir", vd.gpg_path(GPG, home), "--batch", "--no-tty",
"--pinentry-mode", "loopback", "--passphrase", "", *args]
done = vd._run(cmd)
if done.returncode != 0:
raise RuntimeError(done.stderr)
return done
def primary_fpr(home):
out = run_gpg(home, "--with-colons", "--list-keys").stdout
return [ln.split(":")[9] for ln in out.splitlines() if ln.startswith("fpr")][0]
def make_key(root, name, uid=UID, expire="never", subkey=False):
home = Path(root) / name
home.mkdir()
os.chmod(home, 0o700)
run_gpg(home, "--quick-generate-key", uid, "ed25519", "sign", expire)
fpr = primary_fpr(home)
if subkey:
run_gpg(home, "--quick-add-key", fpr, "ed25519", "sign", "never")
pub = Path(root) / f"{name}.pub.asc"
run_gpg(home, "--armor", "--output", vd.gpg_path(GPG, pub), "--export", fpr)
return home, fpr, pub
def sign(home, path, out, local_user=None):
extra = ["--local-user", local_user] if local_user else []
run_gpg(home, *extra, "--armor", "--detach-sign", "--output", vd.gpg_path(GPG, out), vd.gpg_path(GPG, path))
return out
@pytest.fixture(scope="session")
def world():
root = Path(tempfile.mkdtemp(prefix="vd"))
w = {"root": root}
if shutil.which(GPG):
w["payload"] = root / "payload.bin"
w["payload"].write_bytes(os.urandom(200_000))
w["other"] = root / "other.bin"
w["other"].write_bytes(os.urandom(200_000))
w["P"] = make_key(root, "publisher")
w["L"] = make_key(root, "lookalike") # same name and e-mail, different key
w["S"] = make_key(root, "subkeyed", subkey=True)
w["E"] = make_key(root, "expiring", expire="1d")
w["sigP"] = sign(w["P"][0], w["payload"], root / "p.asc")
w["sigL"] = sign(w["L"][0], w["payload"], root / "l.asc")
w["sigE"] = sign(w["E"][0], w["payload"], root / "e.asc")
sub_fpr = [ln.split(":")[9] for ln in run_gpg(w["S"][0], "--with-colons", "--list-keys", "--with-subkey-fingerprint").stdout.splitlines()
if ln.startswith("fpr")][-1]
w["subfpr"] = sub_fpr
w["sigS"] = sign(w["S"][0], w["payload"], root / "s.asc", local_user=sub_fpr + "!")
yield w
for home in root.iterdir():
if home.is_dir():
vd._run(["gpgconf", "--homedir", vd.gpg_path(GPG, home), "--kill", "gpg-agent"])
shutil.rmtree(root, ignore_errors=True)
def digest_of(path):
import hashlib
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
def flipped(path, offset, tmp_path):
data = bytearray(Path(path).read_bytes())
data[offset] ^= 1
out = tmp_path / ("flipped_" + Path(path).name)
out.write_bytes(bytes(data))
return out
# ---------------------------------------------------------------- SHA-256
def test_sha256_matches_and_ignores_case_and_spaces(tmp_path):
f = tmp_path / "a.bin"
f.write_bytes(b"hello")
want = digest_of(f)
spaced = " ".join(want[i:i + 16] for i in range(0, 64, 16)).upper()
assert vd.check_sha256(f, spaced).ok
def test_sha256_mismatch_and_truncated_expected_value_fail(tmp_path):
f = tmp_path / "a.bin"
f.write_bytes(b"hello")
want = digest_of(f)
assert not vd.check_sha256(f, want[:-1] + ("0" if want[-1] != "0" else "1")).ok
assert not vd.check_sha256(f, want[:16]).ok # a prefix is not a match
assert not vd.check_sha256(f, "not hex at all").ok
def test_sha256_covers_the_whole_file(tmp_path):
big = tmp_path / "big.bin"
big.write_bytes(os.urandom(3_000_000))
assert vd.check_sha256(big, digest_of(big)).ok # a reader that stopped after one megabyte would never match
data = bytearray(big.read_bytes())
data[-1] ^= 1
tail = tmp_path / "tail.bin"
tail.write_bytes(bytes(data))
assert not vd.check_sha256(tail, digest_of(big)).ok # a change in the very last byte is noticed
# ---------------------------------------------------------------- GPG
@needs_gpg
def test_gpg_good_signature_with_pinned_key_passes(world):
_, fpr, pub = world["P"]
assert vd.check_gpg(world["payload"], world["sigP"], pub, fpr, gpg=GPG).ok
@needs_gpg
def test_gpg_accepts_lowercase_fingerprint_with_spaces(world):
_, fpr, pub = world["P"]
spaced = " ".join(fpr[i:i + 4] for i in range(0, 40, 4)).lower()
assert vd.check_gpg(world["payload"], world["sigP"], pub, spaced, gpg=GPG).ok
@needs_gpg
def test_gpg_rejects_a_tampered_file(world, tmp_path):
_, fpr, pub = world["P"]
bad = flipped(world["payload"], 10, tmp_path)
result = vd.check_gpg(bad, world["sigP"], pub, fpr, gpg=GPG)
assert not result.ok and "BADSIG" in result.detail
@needs_gpg
def test_gpg_rejects_a_signature_made_for_another_file(world):
_, fpr, pub = world["P"]
assert not vd.check_gpg(world["other"], world["sigP"], pub, fpr, gpg=GPG).ok
@needs_gpg
def test_plain_gpg_calls_a_lookalike_key_a_good_signature(world):
home, _, pub = world["L"]
done = vd._run([GPG, "--homedir", vd.gpg_path(GPG, home), "--verify", vd.gpg_path(GPG, world["sigL"]), vd.gpg_path(GPG, world["payload"])])
assert done.returncode == 0
assert f'Good signature from "{UID}"' in done.stderr
@needs_gpg
def test_pin_rejects_the_lookalike_key_file(world):
_, fpr_real, _ = world["P"]
_, _, pub_fake = world["L"]
result = vd.check_gpg(world["payload"], world["sigL"], pub_fake, fpr_real, gpg=GPG)
assert not result.ok and "does not hold the pinned key" in result.detail
@needs_gpg
def test_pin_rejects_a_lookalike_signature_when_both_keys_are_in_the_file(world, tmp_path):
_, fpr_real, pub_real = world["P"]
_, _, pub_fake = world["L"]
both = tmp_path / "both.asc"
both.write_bytes(pub_real.read_bytes() + b"\n" + pub_fake.read_bytes())
result = vd.check_gpg(world["payload"], world["sigL"], both, fpr_real, gpg=GPG)
assert not result.ok and "pinned" in result.detail and "does not hold" not in result.detail
@needs_gpg
def test_pin_accepts_a_signature_made_by_a_subkey(world):
_, fpr, pub = world["S"]
assert world["subfpr"] != fpr
assert vd.check_gpg(world["payload"], world["sigS"], pub, fpr, gpg=GPG).ok
@needs_gpg
def test_expired_key_is_rejected(world):
_, fpr, pub = world["E"]
assert vd.check_gpg(world["payload"], world["sigE"], pub, fpr, gpg=GPG).ok
later = ("--faked-system-time", str(int(time.time()) + 10 * 86400))
result = vd.check_gpg(world["payload"], world["sigE"], pub, fpr, gpg=GPG, extra=later)
assert not result.ok and "EXPKEYSIG" in result.detail
@needs_gpg
def test_missing_signature_and_missing_key_file_fail(world, tmp_path):
_, fpr, pub = world["P"]
assert not vd.check_gpg(world["payload"], tmp_path / "nope.asc", pub, fpr, gpg=GPG).ok
assert not vd.check_gpg(world["payload"], world["sigP"], tmp_path / "nope.pub", fpr, gpg=GPG).ok
@needs_gpg
def test_unknown_signer_with_no_valid_signature_fails_without_crashing(world, tmp_path):
_, fpr, pub = world["P"]
garbage = tmp_path / "garbage.asc"
garbage.write_text("not a signature", encoding="utf-8")
assert not vd.check_gpg(world["payload"], garbage, pub, fpr, gpg=GPG).ok
def test_gpg_missing_binary_and_bad_fingerprint_fail_closed(tmp_path):
f = tmp_path / "a.bin"
f.write_bytes(b"x")
assert not vd.check_gpg(f, f, f, "A" * 40, gpg="no-such-gpg-binary").ok
assert not vd.check_gpg(f, f, f, "1234", gpg=GPG).ok
# ---------------------------------------------------------------- policy and exit codes
def write_policy(tmp_path, body):
p = tmp_path / "policy.json"
p.write_text(json.dumps(body), encoding="utf-8")
return p
def test_hash_only_policy_is_weak_exit_3(tmp_path):
f = tmp_path / "a.bin"
f.write_bytes(b"hello")
_, code, message = vd.run_policy(write_policy(tmp_path, {"sha256": digest_of(f)}), f)
assert code == 3 and message.startswith("WEAK")
def test_unknown_layer_name_is_a_policy_error_not_a_skipped_check(tmp_path):
f = tmp_path / "a.bin"
f.write_bytes(b"hello")
_, code, _ = vd.run_policy(write_policy(tmp_path, {"sha256": digest_of(f), "sigstor": {}}), f)
assert code == 2
def test_empty_policy_and_missing_target_are_policy_errors(tmp_path):
f = tmp_path / "a.bin"
f.write_bytes(b"hello")
assert vd.run_policy(write_policy(tmp_path, {}), f)[1] == 2
assert vd.run_policy(write_policy(tmp_path, {"sha256": "0" * 64}), tmp_path / "missing.bin")[1] == 2
assert vd.run_policy(tmp_path / "no-policy.json", f)[1] == 2
@needs_gpg
def test_two_layers_pass_exit_0_and_one_failure_fails_everything(world, tmp_path):
_, fpr, pub = world["P"]
body = {"sha256": digest_of(world["payload"]),
"gpg": {"signature": str(world["sigP"]), "key_file": str(pub), "fingerprint": fpr}}
results, code, _ = vd.run_policy(write_policy(tmp_path, body), world["payload"], gpg=GPG)
assert code == 0 and [r.layer for r in results] == ["sha256", "gpg"]
body["gpg"]["signature"] = str(world["sigL"]) # the checksum still passes, the signature does not
results, code, message = vd.run_policy(write_policy(tmp_path, body), world["payload"], gpg=GPG)
assert code == 1 and results[0].ok and not results[1].ok and message.startswith("FAILED")
def test_main_prints_one_line_per_layer(tmp_path, capsys):
f = tmp_path / "a.bin"
f.write_bytes(b"hello")
code = vd.main([str(write_policy(tmp_path, {"sha256": digest_of(f)})), str(f)])
out = capsys.readouterr().out
assert code == 3 and out.splitlines()[0].startswith("PASS sha256") and "WEAK" in out
# ---------------------------------------------------------------- Sigstore (real python.org bundles, network)
@needs_sigstore
def test_sigstore_right_identity_passes():
json_file = DL / "windows-3.13.14.json"
assert vd.check_sigstore(json_file, DL / "windows-3.13.14.json.sigstore", *THOMAS).ok
@needs_sigstore
def test_sigstore_wrong_identity_and_wrong_issuer_fail():
f, b = DL / "windows-3.13.14.json", DL / "windows-3.13.14.json.sigstore"
wrong_who = vd.check_sigstore(f, b, "[email protected]", THOMAS[1])
assert not wrong_who.ok and "SANs do not match" in wrong_who.detail
wrong_issuer = vd.check_sigstore(f, b, THOMAS[0], "https://github.com/login/oauth")
assert not wrong_issuer.ok and "OIDCIssuer" in wrong_issuer.detail
@needs_sigstore
def test_sigstore_tampered_copy_and_foreign_bundle_fail(tmp_path):
f, b = DL / "windows-3.13.14.json", DL / "windows-3.13.14.json.sigstore"
bad = flipped(f, 100, tmp_path)
assert "digest mismatch" in vd.check_sigstore(bad, b, *THOMAS).detail
foreign = vd.check_sigstore(f, DL / "windows-3.14.10.json.sigstore", "[email protected]", "https://github.com/login/oauth")
assert not foreign.ok # a valid bundle for a different file
# ---------------------------------------------------------------- GitHub attestation (real jq release, network)
JQ = DL / "jq" / "jq-1.8.2.tar.gz"
JQ_BUNDLE = DL / "jq" / "jq-1.8.2.tar.gz.attestation.sigstore.json"
needs_jq = pytest.mark.skipif(not JQ_BUNDLE.exists(), reason="run the attestation download step first")
@needs_jq
def test_github_attestation_right_repository_passes_and_wrong_repository_fails():
assert vd.check_github(JQ, JQ_BUNDLE, "jqlang/jq").ok
wrong = vd.check_github(JQ, JQ_BUNDLE, "someone-else/jq")
assert not wrong.ok and "GitHubWorkflowRepository" in wrong.detail
@needs_jq
def test_github_attestation_tampered_copy_fails(tmp_path):
bad = flipped(JQ, 500, tmp_path)
shutil.copy(JQ_BUNDLE, tmp_path / JQ_BUNDLE.name)
assert not vd.check_github(bad, tmp_path / JQ_BUNDLE.name, "jqlang/jq").ok
# ---------------------------------------------------------------- Authenticode (Windows)
NOTEPAD = Path(os.environ.get("SystemRoot", r"C:\Windows")) / "System32" / "notepad.exe"
PSF = "CN=Python Software Foundation, O=Python Software Foundation, L=Beaverton, S=Oregon, C=US"
@needs_windows
def test_authenticode_pins_subject_and_issuer_not_just_valid():
info = vd.read_authenticode(NOTEPAD)
assert info["Status"] == "Valid"
assert vd.check_authenticode(NOTEPAD, info["Subject"], info["Issuer"]).ok
other_publisher = vd.check_authenticode(NOTEPAD, PSF, info["Issuer"])
assert not other_publisher.ok and "status Valid" in other_publisher.detail
assert not vd.check_authenticode(NOTEPAD, info["Subject"], PSF_ISSUER).ok # right publisher name, wrong issuing CA
INSTALLER = DL / "python-3.13.14-amd64.exe"
PSF_ISSUER = "CN=Microsoft ID Verified CS EOC CA 04, O=Microsoft Corporation, C=US"
@needs_windows
@pytest.mark.skipif(not INSTALLER.exists(), reason="run the download step first")
def test_authenticode_real_installer_passes_and_a_flipped_copy_is_a_hash_mismatch(tmp_path):
assert vd.check_authenticode(INSTALLER, PSF, PSF_ISSUER).ok
bad = flipped(INSTALLER, 1_000_000, tmp_path)
result = vd.check_authenticode(bad, PSF, PSF_ISSUER)
assert not result.ok and "HashMismatch" in result.detail and "Python Software Foundation" in result.detail
@needs_windows
def test_authenticode_flipped_catalog_signed_copy_and_unsigned_file_fail(tmp_path):
info = vd.read_authenticode(NOTEPAD)
bad = flipped(NOTEPAD, 4096, tmp_path) # notepad.exe is catalog-signed: a damaged copy has no signature at all
assert not vd.check_authenticode(bad, info["Subject"], info["Issuer"]).ok
plain = tmp_path / "plain.txt"
plain.write_text("hello", encoding="utf-8")
assert not vd.check_authenticode(plain, info["Subject"], info["Issuer"]).ok
def test_authenticode_fails_closed_when_not_on_windows(monkeypatch, tmp_path):
monkeypatch.setattr(sys, "platform", "linux")
f = tmp_path / "a.exe"
f.write_bytes(b"MZ")
assert not vd.check_authenticode(f, PSF, "anything").ok
python -m pytest -q test_verify_download.py
............................. [100%]
29 passed in 14.44s
Plant bugs and see whether the tests notice
Passing tests prove little unless they would fail when the code is wrong. Mutation testing checks that: plant one bug at a time in a copy of the verifier, run the suite, and expect a failure each time. The script below plants 19 bugs, among them comparing only a prefix of the hash, ignoring the pinned fingerprint, comparing the subkey instead of the primary key, accepting expired keys, ignoring the pinned Sigstore identity or issuer, skipping the Authenticode subject check, and letting a failed layer not fail the run.
"""mutants.py: plant one bug at a time in verify_download.py and check that the tests notice.
Run: python mutants.py (needs the files in ./dl and network access, like the tests)
"""
import os
import re
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path
HERE = Path(__file__).resolve().parent
SOURCE = HERE / "verify_download.py"
MUTANTS = [
("sha256: compare only a 16-character prefix", 'return Result("sha256", got == want,', 'return Result("sha256", got[:16] == want[:16],'),
("sha256: compare case-sensitively", 'want = re.sub(r"\\s+", "", expected).lower()', 'want = re.sub(r"\\s+", "", expected)'),
("sha256: hash only the first megabyte", 'for chunk in iter(lambda: f.read(1 << 20), b""):', 'for chunk in [f.read(1 << 20)]:'),
("gpg: ignore the pinned fingerprint", 'return Result("gpg", signer == want,', 'return Result("gpg", True,'),
("gpg: compare the signing subkey, not the primary key", 'signer = valid[0][-1].upper()', 'signer = valid[0][1].upper()'),
("gpg: accept signatures by expired keys", 'BAD_GPG = {"BADSIG", "ERRSIG", "EXPSIG", "EXPKEYSIG", "REVKEYSIG"}', 'BAD_GPG = {"BADSIG", "ERRSIG"}'),
("gpg: skip the key-file check", 'if want not in primaries:', 'if False:'),
("gpg: do not upper-case the pinned fingerprint", 'want = re.sub(r"\\s+", "", fingerprint).upper()', 'want = re.sub(r"\\s+", "", fingerprint)'),
("sigstore: always report OK", 'if run.returncode == 0 and "OK:" in run.stdout + run.stderr:', 'if True:'),
("sigstore: ignore the identity you pinned", '"--cert-identity", identity,', '"--cert-identity", "[email protected]",'),
("sigstore: ignore the issuer you pinned", '"--cert-oidc-issuer", issuer,', '"--cert-oidc-issuer", "https://accounts.google.com",'),
("github: ignore the repository you pinned", '"--repository", repository,', '"--repository", "jqlang/jq",'),
("authenticode: do not compare the subject", 'info["Status"] == "Valid" and info["Subject"] == subject and info["Issuer"] == issuer', 'info["Status"] == "Valid" and info["Issuer"] == issuer'),
("authenticode: do not compare the issuer", 'info["Status"] == "Valid" and info["Subject"] == subject and info["Issuer"] == issuer', 'info["Status"] == "Valid" and info["Subject"] == subject'),
("authenticode: do not require status Valid", 'info["Status"] == "Valid" and info["Subject"] == subject and info["Issuer"] == issuer', 'info["Subject"] == subject and info["Issuer"] == issuer'),
("authenticode: pass when it cannot be read", 'return Result("authenticode", False, "cannot read', 'return Result("authenticode", True, "cannot read'),
("policy: a checksum-only policy is not weak", 'if all(r.layer == "sha256" for r in results):', 'if False:'),
("policy: ignore unknown layer names", 'unknown = sorted(set(policy) - LAYERS)', 'unknown = []'),
("policy: one failed layer does not fail the run", 'if any(not r.ok for r in results):', 'if all(not r.ok for r in results):'),
]
def run_tests(folder):
env = dict(os.environ, PYTHONDONTWRITEBYTECODE="1", VERIFY_LAB_DL=str(HERE / "dl"), COLUMNS="170")
cmd = [sys.executable, "-m", "pytest", "-q", "-x", "-p", "no:cacheprovider", "test_verify_download.py"]
with tempfile.TemporaryFile() as out: # files, not pipes: gpg-agent would hold a pipe open
done = subprocess.run(cmd, cwd=folder, env=env, stdin=subprocess.DEVNULL, stdout=out, stderr=subprocess.STDOUT)
out.seek(0)
text = out.read().decode("utf-8", "replace")
failed = re.findall(r"^FAILED (\S+)", text, re.M)
return done.returncode, (failed[0].split("::")[-1] if failed else "")
def main():
original = SOURCE.read_text(encoding="utf-8")
caught = 0
with tempfile.TemporaryDirectory() as tmp:
folder = Path(tmp)
shutil.copy(HERE / "test_verify_download.py", folder)
(folder / "verify_download.py").write_text(original, encoding="utf-8", newline="\n")
code, _ = run_tests(folder)
print(f"control (no bug planted): {'tests pass' if code == 0 else 'TESTS FAIL, fix this first'}")
if code != 0:
return 1
for number, (name, old, new) in enumerate(MUTANTS, 1):
assert original.count(old) == 1, f"mutant {number} does not match exactly once: {old!r}"
(folder / "verify_download.py").write_text(original.replace(old, new), encoding="utf-8", newline="\n")
code, first = run_tests(folder)
caught += code != 0
print(f"{number:>2}. {'caught ' if code != 0 else 'SURVIVED'} {name}" + (f" <- {first}" if first else ""))
print(f"{caught} of {len(MUTANTS)} planted bugs caught")
return 0 if caught == len(MUTANTS) else 1
if __name__ == "__main__":
sys.exit(main())
python mutants.py
control (no bug planted): tests pass
1. caught sha256: compare only a 16-character prefix <- test_sha256_mismatch_and_truncated_expected_value_fail
2. caught sha256: compare case-sensitively <- test_sha256_matches_and_ignores_case_and_spaces
3. caught sha256: hash only the first megabyte <- test_sha256_covers_the_whole_file
4. caught gpg: ignore the pinned fingerprint <- test_pin_rejects_a_lookalike_signature_when_both_keys_are_in_the_file
5. caught gpg: compare the signing subkey, not the primary key <- test_pin_accepts_a_signature_made_by_a_subkey
6. caught gpg: accept signatures by expired keys <- test_expired_key_is_rejected
7. caught gpg: skip the key-file check <- test_pin_rejects_the_lookalike_key_file
8. caught gpg: do not upper-case the pinned fingerprint <- test_gpg_accepts_lowercase_fingerprint_with_spaces
9. caught sigstore: always report OK <- test_sigstore_wrong_identity_and_wrong_issuer_fail
10. caught sigstore: ignore the identity you pinned <- test_sigstore_wrong_identity_and_wrong_issuer_fail
11. caught sigstore: ignore the issuer you pinned <- test_sigstore_wrong_identity_and_wrong_issuer_fail
12. caught github: ignore the repository you pinned <- test_github_attestation_right_repository_passes_and_wrong_repository_fails
13. caught authenticode: do not compare the subject <- test_authenticode_pins_subject_and_issuer_not_just_valid
14. caught authenticode: do not compare the issuer <- test_authenticode_pins_subject_and_issuer_not_just_valid
15. caught authenticode: do not require status Valid <- test_authenticode_real_installer_passes_and_a_flipped_copy_is_a_hash_mismatch
16. caught authenticode: pass when it cannot be read <- test_authenticode_fails_closed_when_not_on_windows
17. caught policy: a checksum-only policy is not weak <- test_hash_only_policy_is_weak_exit_3
18. caught policy: ignore unknown layer names <- test_unknown_layer_name_is_a_policy_error_not_a_skipped_check
19. caught policy: one failed layer does not fail the run <- test_two_layers_pass_exit_0_and_one_failure_fails_everything
19 of 19 planted bugs caught
The first time I ran it, 18 of 19 bugs were caught and one survived: the bug that hashes only the first megabyte of a file. My test had compared a 3 MB file with the digest of a different file, which never matches whether or not the code reads the whole file. A hash function that stops early never produces a false pass in that setup, only a false failure on honest files, so the test needed to check that a large honest file verifies against its own digest. The version above does, and the survivor is gone. It is a small example of the usual rule: a test that cannot fail is not testing anything.
Step 11: Use it on your own downloads
To verify a different download, repeat the same five moves, keeping the rule that every fact comes from outside the file:
1. Find the publisher’s published evidence. Look for a SHA-256 value, a signature file (.asc, .sig, .sigstore, .sigstore.json), or an attestation. The release page and the project’s security or verification documentation are the places to look.
2. Find the expected identity from a different channel than the file. For GPG that means the key fingerprint, from the project’s documentation or a link carrying the fingerprint. For Sigstore it means the identity and the issuer, as in the python.org table. For GitHub attestations it means the repository. For Authenticode it means the publisher name and issuing authority, read from a download you already trust, ideally an earlier release you verified.
3. Download the evidence next to the file into a folder of its own, and keep the folder’s name and the file’s name unchanged, since signatures are tied to contents but humans are tied to names.
4. Write a policy file like the ones above, listing every layer you have evidence for, and run the verifier. Do not run the downloaded program until the exit code is 0.
5. Save the policy. The next release of the same project will usually need only a new checksum and a new bundle, because the fingerprint, identity or publisher name stays the same. If one of those changes, treat it as news and find out why before you update the policy.
What do real projects publish?
To see how much of this you can use in practice, I looked at the latest GitHub release of 27 popular developer tools. The script below reads the release’s asset names from the public GitHub API, sorts them into kinds (checksum files, GPG signatures, other signature files, Sigstore bundles and certificates, provenance files, SBOMs), and asks the attestations endpoint whether one archive from the release has a GitHub attestation. It makes two unauthenticated requests per project, and the limit is 60 an hour, so run it once.
"""survey_releases.py: which verification files does each project attach to its latest GitHub release?
Reads asset NAMES from the public GitHub API, then asks the attestations API whether one archive from
that release has a GitHub artifact attestation. That is two unauthenticated requests per project
(the limit is 60 an hour). It cannot see signatures a project keeps on its own website or in a package manager.
"""
import json
import re
import sys
import urllib.request
REPOS = [
"BurntSushi/ripgrep", "sharkdp/fd", "sharkdp/bat", "jqlang/jq", "astral-sh/uv", "astral-sh/ruff", "cli/cli",
"junegunn/fzf", "helm/helm", "sigstore/cosign", "goreleaser/goreleaser", "caddyserver/caddy", "restic/restic",
"rclone/rclone", "syncthing/syncthing", "git-for-windows/git", "PowerShell/PowerShell", "neovim/neovim",
"nushell/nushell", "mikefarah/yq", "argoproj/argo-cd", "ollama/ollama", "ggml-org/llama.cpp",
"prometheus/prometheus", "docker/compose", "koalaman/shellcheck", "jesseduffield/lazygit",
]
KINDS = [
("checksums", re.compile(r"sha256|sha512|sha1|checksums?|shasums?|\.md5$", re.I)),
("gpg", re.compile(r"\.(asc|gpg|pgp)$", re.I)),
("sig", re.compile(r"\.sig$", re.I)),
("sigstore", re.compile(r"\.sigstore(\.json)?$|\.bundle$|\.pem$|\.crt$|\.cert$", re.I)),
("minisign", re.compile(r"\.minisig$", re.I)),
("provenance", re.compile(r"intoto|provenance|\.att$|attestation", re.I)),
("sbom", re.compile(r"sbom|\.spdx|cyclonedx|\.cdx", re.I)),
]
ARCHIVE = re.compile(r"\.(zip|tar\.gz|tgz|tar\.xz|exe|msi|deb|rpm|dmg|pkg|whl)$", re.I)
HEADERS = {"User-Agent": "download-verification-survey", "Accept": "application/vnd.github+json"}
def get(url):
try:
with urllib.request.urlopen(urllib.request.Request(url, headers=HEADERS), timeout=30) as resp:
return resp.status, json.load(resp)
except Exception as exc: # a rate limit, a 404 or no network: report it, never guess
return getattr(exc, "code", None) or type(exc).__name__, None
def main():
rows, detail = [], []
for repo in REPOS:
status, rel = get(f"https://api.github.com/repos/{repo}/releases/latest")
if rel is None:
rows.append((repo, f"error {status}", 0, {}, "?"))
continue
assets = rel.get("assets", [])
names = [a["name"] for a in assets]
found = {kind: [n for n in names if rx.search(n)] for kind, rx in KINDS}
pick = next((a for a in assets if ARCHIVE.search(a["name"]) and a.get("digest")), None)
attested = "-"
if pick is not None:
code, att = get(f"https://api.github.com/repos/{repo}/attestations/{pick['digest']}")
attested = "yes" if att and att.get("attestations") else ("?" if code not in (404, 200) else "-")
detail.append(f"{repo} {rel['tag_name']} attested-asset={pick['name'] if pick else None} -> {attested}")
for kind, hits in found.items():
if hits and kind != "checksums":
detail.append(f" {kind}: " + ", ".join(hits[:4]))
rows.append((repo, rel["tag_name"], len(names), found, attested))
head = ["checksums", "gpg", "sig", "sigstore", "minisign", "provenance", "sbom"]
print(f"{'project':<24}{'release':<16}{'files':>6} " + " ".join(f"{h[:9]:<9}" for h in head) + " attested")
for repo, tag, count, found, attested in rows:
print(f"{repo:<24}{tag[:15]:<16}{count:>6} " + " ".join(f"{('yes' if found.get(h) else '-'):<9}" for h in head) + f" {attested}")
ok = [r for r in rows if r[3] != {} or r[2] > 0]
ok = [r for r in rows if not str(r[1]).startswith("error")]
sig_kinds = ("gpg", "sig", "sigstore", "minisign", "provenance")
print(f"\n{len(ok)} projects read. Projects whose latest release lists at least one file of each kind:")
for h in head:
print(f" {h:<11}{sum(1 for r in ok if r[3].get(h)):>3}")
print(f" GitHub attestation for one archive: {sum(1 for r in ok if r[4] == 'yes')}")
anything = [r for r in ok if any(r[3].get(h) for h in sig_kinds) or r[4] == "yes"]
sums_only = [r for r in ok if r[3].get('checksums') and r not in anything]
nothing = [r for r in ok if not r[3].get('checksums') and r not in anything]
print(f" any signature, provenance file or attestation: {len(anything)}; checksums and nothing signed: {len(sums_only)}; neither: {len(nothing)}")
print(" neither:", ", ".join(r[0] for r in nothing))
with open("out/survey_detail.txt", "w", encoding="utf-8") as f:
f.write("\n".join(detail) + "\n")
if __name__ == "__main__":
sys.exit(main())
mkdir out
python survey_releases.py
project release files checksums gpg sig sigstore minisign provenanc sbom attested
BurntSushi/ripgrep 16.0.0 34 yes - - - - - - yes
sharkdp/fd v10.5.2 23 - - - - - - - yes
sharkdp/bat v0.27.0 21 - - - - - - - -
jqlang/jq jq-1.8.2 29 yes - - - - yes - yes
astral-sh/uv 0.13.10 42 yes - - - - - - yes
astral-sh/ruff 0.17.6 40 yes - - - - - - yes
cli/cli v2.106.0 22 yes - - - - - - yes
junegunn/fzf v0.75.0 28 yes - - - - - - -
helm/helm v4.3.2 36 yes yes - - - - - -
sigstore/cosign v3.1.6 83 yes - - yes - - yes yes
goreleaser/goreleaser v2.20.3 55 yes - - yes - - yes yes
caddyserver/caddy v2.11.9 129 yes - yes yes - - yes -
restic/restic v0.20.0 29 yes yes - - - - - -
rclone/rclone v1.76.0 51 yes - - - - - - -
syncthing/syncthing v2.1.7 35 yes yes - - - - - yes
git-for-windows/git v2.56.1.windows 96 - - yes - - - - yes
PowerShell/PowerShell v7.7.0 24 yes - - - - - - -
neovim/neovim v0.12.6 12 - - - - - - - -
nushell/nushell 0.117.0 16 yes - - - - - - -
mikefarah/yq v4.54.3 59 yes - - yes - - - yes
argoproj/argo-cd v3.6.3 11 yes - - - - yes yes -
ollama/ollama v0.40.19 16 yes - - - - - - -
ggml-org/llama.cpp v1.1.0 1 - - - - - - - -
prometheus/prometheus v3.16.0 37 yes - - - - - - yes
docker/compose v5.8.1 56 yes - - yes - yes yes -
koalaman/shellcheck v0.11.0 13 - - - - - - - -
jesseduffield/lazygit v0.66.3 14 yes - - - - - - -
27 projects read. Projects whose latest release lists at least one file of each kind:
checksums 21
gpg 3
sig 2
sigstore 5
minisign 0
provenance 3
sbom 5
GitHub attestation for one archive: 12
any signature, provenance file or attestation: 17; checksums and nothing signed: 6; neither: 4
neither: sharkdp/bat, neovim/neovim, ggml-org/llama.cpp, koalaman/shellcheck
The snapshot was taken on 2026-11-29. A dash means I found no such file among the release’s assets, which does not prove the project publishes nothing: some projects document signatures on their own websites or sign through a package manager, and the survey cannot see that. The attestation column checks a single archive per project. With those limits in mind, 21 of the 27 releases listed a checksum file, and 17 offered something stronger: a GPG or other signature file, a provenance file, a Sigstore bundle, or a GitHub attestation. Twelve had a GitHub attestation for the archive I probed, six listed a checksum and nothing signed that I could see, and four listed neither a checksum nor anything signed (bat, neovim, shellcheck and the llama.cpp release page). I double-checked those four, and fd, which has an attestation but no checksum file, against GitHub’s own asset lists and found no checksum-like file names. The practical reading is that a checksum is nearly always available, a stronger signal often is, and which kind you get varies by project, so your policy has to be written per project.
What none of these checks can tell you
A valid signature is not a safety certificate. It says who signed, not that the content is harmless. The LiteLLM incident is the standing example: the bad build was published by the project’s own pipeline.
The signer’s credentials can be stolen. If an attacker holds the release manager’s account, the build workflow or the signing certificate, every layer passes, because the signature is real. Our report on the Microsoft agent-framework packages on PyPI describes Wiz pointing to a compromised release-pipeline certificate in a case like that. Transparency logs make such abuse visible after the fact, because identity owners can watch the log for signing events they did not make, but they do not prevent it.
You still have to learn the fingerprint or the identity somewhere. In this tutorial the fingerprint came from python.org and the key file from Keybase. That is two hops and better than one, but a stricter reader would also compare the fingerprint with a third place, such as the signer’s own published statement.
A good signature on an old file does not mean the file is current. Verification tells you nothing about whether a newer release fixes a security flaw in the one you hold.
Verification covers the file, not what it fetches later. An installer that downloads more code at run time is outside what its own signature checked. The Python startup-hook audit and the package-name gate cover two more places where code arrives without a signature.
Common mistakes
Trusting a hash that sits next to the file
If the hash and the file come from the same server, a single compromise changes both. Row 3 of the attack table is this mistake.
Reading “Good signature” as “verified”
It means the signature fits some key in your keyring. Row 4 shows the same sentence printed for an attacker’s key. Compare the full 40-digit fingerprint with one you learned separately.
Importing keys into your everyday keyring
Keys you import once keep vouching for signatures forever. Use a throwaway keyring folder, as in Step 4, so each check starts from nothing.
Pinning a thumbprint that changes every release
The Python installers’ certificates last three days, and each release batch has its own thumbprint. Pin the publisher name and the issuing authority.
Reading the signer name on a damaged file
The Python Software Foundation’s name still appeared on the one-bit-damaged copy. Read the status before the signer.
Forgetting to pin the Sigstore issuer
Give both the identity and the issuer, and take them from the project’s documentation, not from the bundle you are checking. A bundle will always describe itself consistently.
Letting a typo remove a check
A tool that ignores unknown settings turns a misspelled layer into a missing layer. Make unknown names an error, as the verifier does.
Treating “weak” as “fine”
A checksum-only pass is not a failure, but it is also not a verification. The distinct exit code 3 exists so that a script cannot confuse the two.
Confirm that everything works end to end
From the lab folder you should now be able to do all of the following. The honest installer passes the four-layer policy with exit code 0. The damaged copy fails every layer with exit code 1. The checksum-only policy exits with 3. The misspelled policy exits with 2. The jq attestation passes for jqlang/jq and fails when you name a different repository. python -m pytest -q test_verify_download.py reports 29 passed. And the mutation script ends with every planted bug caught. If one step disagrees, go back to the output printed in that step and compare it line by line. The timestamps, the temporary paths and the random fingerprint of the look-alike key in Step 8 are the only lines expected to differ.
Where to go next
Three directions follow naturally. First, extend the policy to the other files you install regularly, and keep each policy next to your notes about where its facts came from. Second, apply the same thinking to containers and packages: our tutorial on signing a container image and its SBOM with cosign shows the signing side of Sigstore, and the one on auditing Python dependencies with SBOMs and pip-audit covers what to do when a release has already been deleted. Third, if you publish software yourself, ask what a user would need to pin to verify your release. Writing that down, with an identity or fingerprint on a page that is not the download page, is the most useful thing you can add.
Sources and method
Facts about the Python releases come from the 3.13.14 release page, the python.org Sigstore page (the identity table and the 3.14 statement), the python.org OpenPGP page (the signer list and the Keybase link) and PEP 761. Sigstore concepts and the quotation about certificate timing come from the Sigstore overview, and the command-line usage from the sigstore-python README. The status codes are described in the GnuPG DETAILS file, and the Authenticode status values in Microsoft’s SignatureStatus documentation and Get-AuthenticodeSignature page. Everything else is my own measurement.
Measurements were made on 2026-11-29 on Windows 11 with Python 3.13.14, sigstore 4.6.0, pytest 9.2.0, cryptography 50.0.2 and GnuPG 2.4.9 (the copy in Git for Windows). The Python installer files and signatures were downloaded from python.org, the key from Keybase, and the jq release file and its attestation from GitHub. The “attacker” files in Step 8 are local copies, and the look-alike key was generated on the test machine, never uploaded anywhere, and deleted afterward. The survey in the last section reads release asset names and one attestation lookup per project from the public GitHub API; it is a snapshot, and it cannot see signing that happens outside GitHub. I did not run anything on Linux or macOS, and I did not test Authenticode alternatives for those systems.








No Comment! Be the first one.