A defender's verification workflow in Python: perceptual hashing, error level analysis and EXIF checks on your own files, C2PA concepts, time zone traps, the Wayback Machine API, checking claims against your logs, source grading and calibrated verification notes.
A screenshot appears on a forum claiming that your customer database was exported last Tuesday. A press release with your logo announces a merger nobody approved. A colleague forwards a "phishing report" with an image of a login page. Before the security or communications team acts, someone has to answer a narrow question: is this claim true, and how sure are we? This tutorial builds that capability in Python: a repeatable verification workflow, image checks on files you generate yourself, time zone discipline, web archives, comparison with your own logs, source grading, and a written verification note with calibrated confidence.
Everything here is OSINT for defenders. You verify claims, content and sources that concern your own organisation, with authorisation from whoever owns the incident. You do not investigate, locate, profile or identify private individuals. If a claim was posted by a person, the question is whether the claim holds, not who the person is. Geolocating people, face recognition, tracking accounts across platforms and unmasking authors are out of scope and, in most organisations, outside any lawful basis under the GDPR (AVG in the Netherlands). When a case genuinely needs attribution of a person, it goes to legal counsel or law enforcement.
Data minimisation applies to verification too. Store the claim, the content and your evidence. Do not collect profiles of the people who shared it.
The examples were run on Python 3.13 on Windows with the latest stable releases at the time of writing: Django 5.2.20 (the LTS line), Pillow 13.0.0, ImageHash 4.3.2 (which pulls in NumPy 2.5.5, SciPy 1.18.1 and PyWavelets 1.10.0), and requests 2.34.2. On Windows, zoneinfo needs the tzdata package, which Django already installs.
python -m venv .venv
.venv\Scripts\activate
pip install "Django>=5.2,<6.0" "Pillow>=13.0,<14.0" "ImageHash>=4.3.2,<5.0" "requests>=2.34,<3.0"
Fact-checkers converge on the same five questions, usually attributed to the First Draft verification framework. Adapted to a defender's case file they are:
| Question | What you look for | Typical evidence |
|---|---|---|
| Provenance | Is this the original, or a copy of a copy? | Earliest version found, near-duplicate hashes, metadata |
| Source | Who first published it and what is their track record? | First-seen URL and time, source grade |
| Date | When was the content created, and does that match the claim? | EXIF times with offsets, archive snapshots, server logs |
| Location | Which system or page does the content claim to show? | UI version, hostnames, menu items, your own change history |
| Motivation | Why would someone publish this now? | Context: extortion attempt, competitor, satire, honest mistake |
"Location" here means the location of the claim inside your estate, such as which admin panel or which release of your product a screenshot shows. It never means the physical location of a person.
Two rules keep the workflow honest. First, preserve before you analyse: capture the content and hash it before anyone edits, crops or annotates it. Second, write down at least two competing hypotheses on day one (for example "a real export happened" and "an older or edited screenshot is being reused"), and look for evidence that would distinguish them rather than evidence that confirms your favourite.
To practise without touching anyone else's material, generate a synthetic "original" and four derivatives: a resized re-share with metadata stripped, a crop, an edited version with a pasted "LEAKED" banner, and an unrelated image.
"""Generate a synthetic 'original' image plus derivatives to test against."""
from pathlib import Path
from PIL import Image, ImageDraw
OUT = Path("samples")
OUT.mkdir(exist_ok=True)
def base_image() -> Image.Image:
img = Image.new("RGB", (800, 500), "white")
d = ImageDraw.Draw(img)
for x in range(800): # horizontal gradient so the hash has structure
d.line([(x, 0), (x, 499)], fill=(x * 255 // 800, 120, 255 - x * 255 // 800))
d.rectangle([60, 60, 360, 220], fill=(20, 20, 20))
d.ellipse([480, 200, 740, 440], fill=(240, 240, 240))
d.text((80, 120), "myproject dashboard", fill="white")
return img
img = base_image()
exif = Image.Exif()
exif[0x0131] = "myproject-capture 1.0" # Software
exif[0x0132] = "2026:11:20 09:14:03" # DateTime (IFD0)
exif_ifd = exif.get_ifd(0x8769)
exif_ifd[0x9003] = "2026:11:20 09:14:03" # DateTimeOriginal
exif_ifd[0x9011] = "+01:00" # OffsetTimeOriginal
img.save(OUT / "original.jpg", quality=92, exif=exif)
# 1. Re-shared copy: resized and recompressed, metadata stripped
img.resize((400, 250)).save(OUT / "reshared.jpg", quality=70)
# 2. Cropped copy
img.crop((40, 40, 760, 470)).save(OUT / "cropped.jpg", quality=85)
# 3. Edited copy: a fake "LEAKED" banner pasted in, saved once more
edited = Image.open(OUT / "original.jpg").copy()
ImageDraw.Draw(edited).rectangle([420, 40, 760, 150], fill=(200, 0, 0))
ImageDraw.Draw(edited).text((450, 80), "LEAKED: customers.csv", fill="white")
ex2 = Image.Exif()
ex2[0x0131] = "PhotoEditor 9.2"
ex2[0x0132] = "2026:11:21 22:40:10"
ex2.get_ifd(0x8769)[0x9003] = "2026:11:20 09:14:03"
edited.save(OUT / "edited.jpg", quality=92, exif=ex2)
# 4. Unrelated image
other = Image.new("RGB", (800, 500), (30, 90, 30))
ImageDraw.Draw(other).polygon([(0, 500), (400, 50), (800, 500)], fill=(200, 200, 60))
other.save(OUT / "unrelated.jpg", quality=90)
print(sorted(p.name for p in OUT.iterdir()))
A cryptographic hash such as SHA-256 changes completely when one byte changes, so it only proves exact identity. A perceptual hash summarises what the image looks like, so a resized or recompressed copy lands close to the original. The difference between two ImageHash objects is the Hamming distance between 64-bit hashes.
from pathlib import Path
from PIL import Image
import imagehash
reference = Path("samples/original.jpg")
ref_p = imagehash.phash(Image.open(reference))
ref_d = imagehash.dhash(Image.open(reference))
print(f"reference phash={ref_p}")
for path in sorted(Path("samples").glob("*.jpg")):
with Image.open(path) as im:
p, d = imagehash.phash(im), imagehash.dhash(im)
dp, dd = ref_p - p, ref_d - d # Hamming distance, 0..64
verdict = "near-duplicate" if dp <= 10 else "review" if dp <= 20 else "different"
print(f"{path.name:14} phash_dist={dp:2} dhash_dist={dd:2} {verdict}")
reference phash=b53b4a86c6e44be2
cropped.jpg phash_dist=10 dhash_dist= 4 near-duplicate
edited.jpg phash_dist=12 dhash_dist= 6 review
original.jpg phash_dist= 0 dhash_dist= 0 near-duplicate
reshared.jpg phash_dist= 2 dhash_dist= 2 near-duplicate
unrelated.jpg phash_dist=26 dhash_dist=25 different
The re-share is plainly the same picture. The crop sits right on the threshold, and the edited copy lands in "review" because the banner changed a visible part of the frame. That is the honest behaviour of perceptual hashes: they surface candidates, they do not decide. Calibrate thresholds on your own material and always compare the pair by eye. In a real case you hash your own published images and screenshots, then find which original the circulating image was derived from.
Error level analysis (ELA) re-saves a JPEG at a known quality and measures how much each pixel changes. Areas that were already compressed several times change little; an area pasted in later and compressed fewer times may change more.
import io
from PIL import Image, ImageChops, ImageStat
def ela(path: str, quality: int = 90) -> Image.Image:
"""Resave at a known quality and return the per-pixel difference."""
original = Image.open(path).convert("RGB")
buf = io.BytesIO()
original.save(buf, "JPEG", quality=quality)
buf.seek(0)
resaved = Image.open(buf)
return ImageChops.difference(original, resaved)
def region_means(diff: Image.Image, boxes: dict[str, tuple]) -> dict[str, float]:
return {name: round(sum(ImageStat.Stat(diff.crop(box)).mean) / 3, 2)
for name, box in boxes.items()}
boxes = {"banner": (420, 40, 760, 150), "dark_panel": (60, 60, 360, 220),
"gradient": (100, 300, 400, 480)}
for name in ("original.jpg", "edited.jpg"):
diff = ela(f"samples/{name}")
print(name, region_means(diff, boxes))
diff.point(lambda v: min(255, v * 20)).save(f"samples/ela_{name}.png")
original.jpg {'banner': 0.27, 'dark_panel': 0.28, 'gradient': 0.21}
edited.jpg {'banner': 0.55, 'dark_panel': 0.27, 'gradient': 0.21}
In the edited file the banner region has roughly double the error level of the untouched regions, while the original is flat. This is a textbook result on a textbook sample. On real content ELA is weak evidence: text and sharp edges naturally show higher error, and a platform that recompresses the image evens the levels out. Treat ELA as a pointer to where to look, never as "proof of manipulation".
Metadata is easy to forge and routinely stripped, so the useful question is not "what does EXIF say" but "is it internally consistent and consistent with the claim".
from datetime import datetime, timedelta, timezone
from PIL import Image
TAGS = {0x0131: "Software", 0x0132: "DateTime"}
EXIF_TAGS = {0x9003: "DateTimeOriginal", 0x9011: "OffsetTimeOriginal"}
def read_exif(path: str) -> dict[str, str]:
exif = Image.open(path).getexif()
out = {name: exif[tag] for tag, name in TAGS.items() if tag in exif}
sub = exif.get_ifd(0x8769)
out |= {name: sub[tag] for tag, name in EXIF_TAGS.items() if tag in sub}
return out
def check(path: str, claimed_utc: datetime) -> list[str]:
meta, notes = read_exif(path), []
if not meta:
return ["no EXIF: common after re-sharing, proves nothing either way"]
taken = meta.get("DateTimeOriginal")
modified = meta.get("DateTime")
if taken and modified and modified != taken:
notes.append(f"modified {modified} differs from taken {taken}")
if "Software" in meta:
notes.append(f"software tag: {meta['Software']}")
offset = meta.get("OffsetTimeOriginal")
if taken and offset:
sign = 1 if offset[0] == "+" else -1
hh, mm = map(int, offset[1:].split(":"))
tz = timezone(sign * timedelta(hours=hh, minutes=mm))
utc = datetime.strptime(taken, "%Y:%m:%d %H:%M:%S").replace(tzinfo=tz)
delta = (utc - claimed_utc).total_seconds() / 60
notes.append(f"taken {utc.astimezone(timezone.utc):%Y-%m-%d %H:%M}Z, "
f"{delta:+.0f} min vs claim")
elif taken:
notes.append("no offset tag: local time of unknown zone")
return notes
claim = datetime(2026, 11, 20, 8, 14, tzinfo=timezone.utc)
for name in ("original.jpg", "edited.jpg", "reshared.jpg"):
print(name, read_exif(f"samples/{name}"))
for note in check(f"samples/{name}", claim):
print(" -", note)
original.jpg {'Software': 'myproject-capture 1.0', 'DateTime': '2026:11:20 09:14:03', 'DateTimeOriginal': '2026:11:20 09:14:03', 'OffsetTimeOriginal': '+01:00'}
- software tag: myproject-capture 1.0
- taken 2026-11-20 08:14Z, +0 min vs claim
edited.jpg {'Software': 'PhotoEditor 9.2', 'DateTime': '2026:11:21 22:40:10', 'DateTimeOriginal': '2026:11:20 09:14:03'}
- modified 2026:11:21 22:40:10 differs from taken 2026:11:20 09:14:03
- software tag: PhotoEditor 9.2
- no offset tag: local time of unknown zone
reshared.jpg {}
- no EXIF: common after re-sharing, proves nothing either way
The edited file reveals itself through an editing tool in the Software tag and a modification time 37 hours after capture. The re-shared file has no metadata at all, which is the normal state of images that passed through chat apps and social platforms. Absence of metadata is not a red flag, and presence of plausible metadata is not proof of authenticity, because every field can be written by anyone. GPS tags in photos of people are personal data and outside this workflow.
The C2PA standard (Coalition for Content Provenance and Authenticity), shown to users as Content Credentials, attaches a cryptographically signed manifest to a file. The manifest records who signed it, which tool produced it and which edits were applied, and it can chain earlier manifests as ingredients. A valid signature tells you that the signer vouches for that history and that the bytes have not changed since signing. It does not tell you that the scene was real or that the signer is honest.
The asymmetry matters for defenders. A valid manifest from a known signer is positive evidence. A missing manifest proves nothing, because most devices and platforms still strip or never add one. Your own organisation benefits most by signing what it publishes (press images, official statements), so that a forged press release is conspicuous by the absence of the credentials your genuine releases always carry. The c2pa-python package (0.39.1 at the time of writing) can read and validate manifests if you want to automate this step.
Many verification errors are time errors: a screenshot shows a local clock, logs are in UTC, and somebody compares them in their head. Convert everything to UTC at the moment you record it, and keep the original string next to the conversion.
Daylight saving time adds two traps. In spring one local hour does not exist; in autumn one local hour occurs twice. Python's zoneinfo handles both, but only if you ask it, through the fold attribute.
from datetime import datetime, timezone
from zoneinfo import ZoneInfo
AMS = ZoneInfo("Europe/Amsterdam")
def to_utc(local: datetime) -> datetime:
"""Convert a naive local time, flagging gaps and ambiguous times."""
early = local.replace(tzinfo=AMS, fold=0)
late = local.replace(tzinfo=AMS, fold=1)
if early.utcoffset() != late.utcoffset():
# round-trip test: a time inside the spring gap does not survive it
back = early.astimezone(timezone.utc).astimezone(AMS).replace(tzinfo=None)
kind = "NONEXISTENT (spring gap)" if back != local else "AMBIGUOUS (autumn fold)"
print(f"{local} {kind}: {early.astimezone(timezone.utc):%H:%M}Z "
f"or {late.astimezone(timezone.utc):%H:%M}Z")
return early.astimezone(timezone.utc)
for text in ("2026-11-20 09:14", "2026-03-29 02:30", "2026-10-25 02:30",
"2026-07-01 09:14"):
local = datetime.fromisoformat(text)
print(f"{text} local -> {to_utc(local):%Y-%m-%d %H:%M}Z")
2026-11-20 09:14 local -> 2026-11-20 08:14Z
2026-03-29 02:30:00 NONEXISTENT (spring gap): 01:30Z or 00:30Z
2026-03-29 02:30 local -> 2026-03-29 01:30Z
2026-10-25 02:30:00 AMBIGUOUS (autumn fold): 00:30Z or 01:30Z
2026-10-25 02:30 local -> 2026-10-25 00:30Z
2026-07-01 09:14 local -> 2026-07-01 07:14Z
If a claim depends on a time inside a gap or fold, record both possible UTC values and say which one your conclusion uses. Fixed offsets such as +01:00 are safe to convert; zone names such as "CET" in a screenshot are ambiguous and should be resolved to an IANA zone like Europe/Amsterdam before use.
Your strongest evidence is usually inside your own estate. The screenshot claims that the admin account exported /export/customers.csv at 09:14 local time on 20 November, which is 08:14 UTC. The access log is JSON lines in UTC.
"""Test a screenshot's claims against our own access log (UTC, JSON lines)."""
import json
from datetime import datetime, timedelta, timezone
from pathlib import Path
LOG = Path("access.jsonl")
LOG.write_text("\n".join(json.dumps(e) for e in [
{"ts": "2026-11-20T08:13:51Z", "user": "svc-report", "path": "/export/orders.csv",
"status": 200, "bytes": 18234},
{"ts": "2026-11-20T08:14:02Z", "user": "admin", "path": "/export/customers.csv",
"status": 403, "bytes": 0},
{"ts": "2026-11-20T08:20:40Z", "user": "admin", "path": "/dashboard",
"status": 200, "bytes": 5120},
]) + "\n")
claim = {"user": "admin", "path": "/export/customers.csv",
"at": datetime(2026, 11, 20, 8, 14, tzinfo=timezone.utc)}
window = timedelta(minutes=10)
hits = []
for line in LOG.read_text().splitlines():
e = json.loads(line)
ts = datetime.fromisoformat(e["ts"])
if abs(ts - claim["at"]) <= window and e["path"] == claim["path"]:
hits.append(e)
if not hits:
print("no matching request in window: claim unsupported by our logs")
for e in hits:
ok = e["status"] == 200 and e["bytes"] > 0
print(f"{e['ts']} {e['user']} {e['path']} -> {e['status']}, {e['bytes']} bytes")
print(" supports claim" if ok else " contradicts claim: request was refused")
2026-11-20T08:14:02Z admin /export/customers.csv -> 403, 0 bytes
contradicts claim: request was refused
The request happened, but it was refused with a 403 and returned no bytes. That contradicts the claim of a successful export at that moment. It does not prove that no data left by another path, so the note says "very unlikely" rather than "false".
When a claim says "your site said X on date Y", the Internet Archive often has an independent copy. The availability API returns the snapshot closest to a timestamp. It is a free public service: identify your client, keep the call rate low and cache results.
import time
import requests
API = "https://archive.org/wayback/available"
session = requests.Session()
session.headers["User-Agent"] = "verification-tutorial/1.0 (defensive research)"
def closest_snapshot(url: str, timestamp: str) -> dict | None:
"""Return the archived snapshot closest to timestamp (YYYYMMDDhhmmss)."""
resp = session.get(API, params={"url": url, "timestamp": timestamp}, timeout=20)
resp.raise_for_status()
return resp.json().get("archived_snapshots", {}).get("closest")
for ts in ("20130101", "20260101"):
snap = closest_snapshot("example.com", ts)
if snap:
print(ts, "->", snap["timestamp"], snap["status"], snap["url"])
else:
print(ts, "-> no snapshot")
time.sleep(2) # be polite: this is a free public service
20130101 -> 20130729212510 200 http://web.archive.org/web/20130729212510/http://www.example.com/
20260101 -> 20260102000115 200 http://web.archive.org/web/20260102000115/http://www.example.com/
Read the returned timestamp, not the one you asked for: the "closest" snapshot to 1 January 2013 is from July 2013. Absence of a snapshot means the archive did not crawl that page, not that the page did not exist.
The Internet Archive's Save Page Now feature (web.archive.org/save/) creates a public, third-party snapshot of a URL on request. The snapshot is public, so never submit pages containing personal data or leaked material. For most internal cases, a local capture with a hash and a UTC timestamp is the right default.
import hashlib
import json
from datetime import datetime, timezone
from pathlib import Path
import requests
EVIDENCE = Path("evidence")
EVIDENCE.mkdir(exist_ok=True)
def capture(url: str, case: str) -> dict:
resp = requests.get(url, timeout=20,
headers={"User-Agent": "verification-tutorial/1.0"})
body = resp.content
digest = hashlib.sha256(body).hexdigest()
(EVIDENCE / f"{digest}.bin").write_bytes(body)
record = {
"case": case, "url": url, "final_url": resp.url,
"status": resp.status_code,
"retrieved_utc": datetime.now(timezone.utc).isoformat(timespec="seconds"),
"sha256": digest, "bytes": len(body),
"server_date": resp.headers.get("Date"),
}
with (EVIDENCE / "manifest.jsonl").open("a", encoding="utf-8") as fh:
fh.write(json.dumps(record) + "\n")
return record
print(json.dumps(capture("https://example.com/", "VC-2026-014"), indent=2))
{
"case": "VC-2026-014",
"url": "https://example.com/",
"final_url": "https://example.com/",
"status": 200,
"retrieved_utc": "2026-12-05T16:21:17+00:00",
"sha256": "25ddf2c883e0d1958ea971d279a7e4f0fd446724ee3db7db19dadabd4a62e484",
"bytes": 577,
"server_date": "Sat, 05 Dec 2026 16:21:16 GMT"
}
The server's Date header gives a second time source, and the append-only manifest starts a chain of custody.
Fact-checkers do not study a source page closely to decide whether to trust it; they leave it and read what independent sources say about it (lateral reading, a term from Stanford's History Education Group). For a fake press release: does the story appear on your own newsroom page, on the wire services you actually use, in your investor relations channel? When was the hosting domain registered? A claim that exists only in one place, from a source with no history, is weak however professional it looks.
The Admiralty system, still used in intelligence work, grades two things separately: source reliability from A (completely reliable) to F (cannot be judged), and information credibility from 1 (confirmed by other sources) to 6 (truth cannot be judged). A new anonymous account posting a screenshot is F6 at intake; that is not an insult, it is an honest starting point.
Teams under pressure want a specific answer. Counter this structurally. List competing hypotheses and score each piece of evidence against all of them (a light version of Analysis of Competing Hypotheses). Ask "what would I expect to see if I were wrong?" and go and look for it. For high-impact cases, have a second analyst review the evidence before reading your reasoning.
Sherman Kent's "words of estimative probability" and the US ICD 203 standard tie words to numeric ranges, so that "likely" means the same to every reader. A small Django model makes those choices explicit and refuses to close a case without alternatives.
from django.conf import settings
from django.db import models
class Estimate(models.TextChoices):
ALMOST_NO_CHANCE = "01-05", "Almost no chance (1-5%)"
VERY_UNLIKELY = "05-20", "Very unlikely (5-20%)"
UNLIKELY = "20-45", "Unlikely (20-45%)"
ROUGHLY_EVEN = "45-55", "Roughly even chance (45-55%)"
LIKELY = "55-80", "Likely (55-80%)"
VERY_LIKELY = "80-95", "Very likely (80-95%)"
ALMOST_CERTAIN = "95-99", "Almost certain (95-99%)"
class VerificationCase(models.Model):
reference = models.CharField(max_length=20, unique=True) # VC-2026-014
claim = models.TextField() # the claim, quoted exactly
first_seen_url = models.URLField(blank=True)
first_seen_at = models.DateTimeField() # stored in UTC (USE_TZ=True)
source_grade = models.CharField(max_length=1, default="F") # A-F
info_grade = models.PositiveSmallIntegerField(default=6) # 1-6
estimate = models.CharField(max_length=5, choices=Estimate.choices, blank=True)
assessment = models.TextField(blank=True)
alternatives = models.TextField(blank=True) # hypotheses considered
analyst = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)
closed_at = models.DateTimeField(null=True, blank=True)
def admiralty(self) -> str:
return f"{self.source_grade}{self.info_grade}"
def can_close(self) -> bool:
return bool(self.estimate and self.assessment and self.alternatives)
from django.contrib.auth import get_user_model
from django.test import TestCase
from django.utils import timezone
from .models import Estimate, VerificationCase
class VerificationCaseTests(TestCase):
def setUp(self):
self.user = get_user_model().objects.create_user("analyst")
def test_cannot_close_without_alternatives(self):
case = VerificationCase.objects.create(
reference="VC-2026-014", claim="Customer export leaked",
first_seen_at=timezone.now(), analyst=self.user,
estimate=Estimate.VERY_UNLIKELY, assessment="Log shows 403.")
self.assertFalse(case.can_close())
case.alternatives = "Real leak via other path; edited old screenshot"
self.assertTrue(case.can_close())
self.assertEqual(case.admiralty(), "F6")
python manage.py test verification
Found 1 test(s).
...
Ran 1 test in 0.001s
OK
Keep two scales apart: the probability that the claim is true (the estimate) and your confidence in that judgement (high, moderate, low, based on the quality and quantity of evidence). "Very unlikely, moderate confidence" is a precise and useful sentence.
A verification note should fit on one page and be readable without the case file:
VC-2026-014 Claimed export of customer data
Claim (verbatim): "Admin exported customers.csv on 20 Nov 09:14"
Bottom line: Very unlikely (5-20%) that this export succeeded. Moderate confidence.
Key evidence:
1. Access log: request at 08:14:02Z returned 403, 0 bytes.
2. Image: near-duplicate of our own dashboard capture; editor in Software tag,
modified 37 h after capture; ELA consistent with a pasted banner (weak).
3. Source graded F6; claim not found in any independent source.
Alternatives considered: export via another endpoint (DB audit log checked, none);
stale credentials (password rotated 2026-11-01).
Gaps: backup access logs not yet reviewed.
Next review: 2026-12-08, or earlier if new material appears.
Notice what is absent: any speculation about who posted it.
near_dupes.py to index a folder of your own published images in SQLite and return the five closest matches for a new file, with both pHash and dHash distances.to_utc raise an exception for nonexistent local times instead of guessing, and write tests for the spring gap and the autumn fold.Hypothesis model linked to VerificationCase with an evidence score per hypothesis, and block closing a case with fewer than two hypotheses.Found a mistake in this tutorial? Let us know and we will fix it.