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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,14 @@ All notable changes to unseenet-watchman are listed here. The format follows

## [Unreleased]

### Added

- **Deceptive link cards** (#27, UN-RFC 0059 section 11; needs unseenet with `fetch_card`,
unseenet#797): with `cards = true`, the page behind a post's link card is read over Tor
and the post reported as phishing when the card's title has nothing in common with the
page's title, description or site name. Never for short titles, pages without a title,
or cookie walls and challenges; each link read once a day at most. Off by default.

## [0.1.0] - 2026-10-29

**The first stable release, on unseenet 0.6** (`unseenet>=0.6.1,<0.7`; 0.6.1 because its
Expand Down
13 changes: 13 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,19 @@ non-commercial use. The lists, their answer codes and test points are in the
config (`[[zone]]`), so a list that changes is a config change, not a release.
`check` shows which lists answer before it checks a text.

### Deceptive link cards

A post can carry a preview of a link, a link card
([UN-RFC 0059](https://unseenet.org/spec/un-rfc-0059/)), whose title and
description are the poster's. With `cards = true` the watchman reads the
linked page over Tor itself (without its picture) and reports the post as
**phishing** when the card's title has nothing in common with the page: not a
word of four letters or more of the page's title, description or site name.
Careful on purpose: a card title of under three words, a page that gives no
title, or a cookie wall, captcha or error page instead of the page is never
reported. Each link is read once a day at most. Off by default - each card is
a fetch over Tor.

## How it works

- **Built on the core.** An ordinary Unseenet client on
Expand Down
76 changes: 76 additions & 0 deletions src/unseenet_watchman/cards.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
"""Deceptive link cards (watchman#27, UN-RFC 0059 section 11).

A link card's title and description are the poster's: a card can claim to be a bank's
login page while its link goes somewhere else - the domain is always shown from the link,
but the title is what people read. With ``cards = true`` the watchman makes its own card
for the link, over Tor, and reports a post (reason ``phishing``: a scam or fake link)
whose card's title has nothing in common with the page: not a word of the page's title,
description or site name.

Careful by design: pages change their titles, answer Tor with a cookie wall or a
challenge, or give no title - none of that is reported. Only a card title of at least three words, against a page
that answered with a title of its own, sharing no word of four letters or more. The
picture is not compared (a picture says nothing a program can read reliably). Each link
is fetched once a day at most.
"""

from __future__ import annotations

import re
import time

MIN_WORDS = 3 # a shorter card title is not judged
PAGE_TTL = 24 * 3600 # a page's card is kept this long
_WORD = re.compile(r"[^\W\d_]{4,}")
# what a page says when it is not answering Tor with itself: a wall, not the page
WALLS = frozenset({"cookie", "cookies", "consent", "captcha", "moment", "attention", "access",
"denied", "blocked", "robot", "robots", "verify", "verifying", "cloudflare",
"forbidden", "error", "found", "unavailable", "security", "checking",
"challenge", "privacy", "samtykke", "adgang", "fejl"})


def words(text: str) -> set[str]:
"""The words of four letters or more, folded: what two titles can share."""
return {w.casefold() for w in _WORD.findall(text or "")}


def deceptive(card_title: str, page_title: str, page_desc: str = "", page_site: str = "") -> bool:
"""True when a card's title has nothing in common with its page - and only when
there is enough on both sides to tell."""
said, page = words(card_title), words(page_title)
if len(said) < MIN_WORDS or len(page) < 2 or page & WALLS:
return False
return not said & words(" ".join((page_title, page_desc, page_site)))


class Pages:
"""The pages behind cards, made with ``fetch(url)`` (a coroutine giving an object with
``title``, ``desc`` and ``site``, or raising) and kept a day."""

def __init__(self, fetch, log=print):
self.fetch, self.log = fetch, log
self._cache: dict[str, tuple[float, object | None]] = {}

async def page(self, url: str):
hit = self._cache.get(url)
if hit and time.time() - hit[0] < PAGE_TTL:
return hit[1]
try:
got = await self.fetch(url)
except Exception as exc: # noqa: BLE001 - an unreachable page is no finding
self.log(f"card page not read: {url}: {exc}")
got = None
self._cache[url] = (time.time(), got)
return got


async def check(m, pages: Pages) -> str | None:
"""Why a post's card is deceptive (the report's note), or None."""
card = getattr(m, "card", None)
if card is None or not card.url:
return None
page = await pages.page(card.url)
if page is None or not deceptive(card.title, page.title, page.desc, page.site):
return None
return (f"link card says {card.title[:60]!r}, its page {card.domain} says "
f"{page.title[:60]!r}")
1 change: 1 addition & 0 deletions src/unseenet_watchman/runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ def load_config(path: str | Path) -> Config:
allow_domains=frozenset(d.lower() for d in r.get("allow_domains", []))),
zones=_zones(d["zone"]) if "zone" in d else None,
labels=bool(w.get("labels", False)),
cards=bool(w.get("cards", False)),
label_rules=labels.Rules(min_hits=int(d.get("labels", {}).get("min_hits", 2)),
short_words=int(d.get("labels", {}).get("short_words", 8))),
ripen_to=int(w["ripen_to"]) if "ripen_to" in w else None)
Expand Down
24 changes: 22 additions & 2 deletions src/unseenet_watchman/watch.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
from unseenet.core.groups import KIND_REACTION, is_key_bound
from unseenet.core.reports import MAX_ENTRIES

from . import decide, dupes, labelling, uris
from . import cards, decide, dupes, labelling, uris
from .labels import Rules as LabelRules
from .dnsbl import Lookups, Zone
from .state import State
Expand Down Expand Up @@ -61,6 +61,7 @@ class Config:
rules: decide.Rules = field(default_factory=decide.Rules)
zones: list[Zone] | None = None
labels: bool = False # also a labeller (UN-RFC 0053): profanity
cards: bool = False # compare link cards with their pages over Tor (#27)
label_rules: LabelRules = field(default_factory=LabelRules)
ripen_to: int | None = None # the issuers' level (#21); else UNSEENET_RIPEN_TO, else 3

Expand Down Expand Up @@ -126,6 +127,11 @@ async def check_post(m, lookups: Lookups, st: State, cfg: Config, now: float) ->
break
if found:
break
pages = getattr(lookups, "card_pages", None)
if cfg.cards and pages is not None and not found:
why = await cards.check(m, pages) # UN-RFC 0059 section 11
if why:
found.append(decide.Finding(m.message_id, m.group, m.author_key, "phishing", why))
fp = dupes.fingerprint(m.body)
if fp is not None:
e = dupes.Entry(fp, m.message_id, m.group, m.author_key, now)
Expand Down Expand Up @@ -361,4 +367,18 @@ def socks() -> tuple[str, int]:
async def resolve(q: str, doh: str):
host, port = socks()
return await doh_resolve_retry(q, host, port, doh)
return Lookups(zones, resolve, log=log, resolvers=doh_list(cfg.doh))
lk = Lookups(zones, resolve, log=log, resolvers=doh_list(cfg.doh))
if cfg.cards:
lk.card_pages = cards.Pages(_page_fetch(socks), log=log)
return lk


def _page_fetch(socks):
"""A link card's page made over Tor, without its picture (core ``fetch_card``)."""
async def fetch(url: str):
from unseenet.client.session import fetch_card
host, port = socks()
if host not in ("127.0.0.1", "localhost", "::1"):
raise OSError("pages are read only through a local Tor")
return await fetch_card(url, port, picture=False)
return fetch
78 changes: 78 additions & 0 deletions tests/test_cards.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
"""watchman#27: deceptive link cards (UN-RFC 0059 section 11) - a card whose title has
nothing in common with its page is reported as phishing; anything less certain is not."""
import asyncio
import time
from types import SimpleNamespace

import pytest

from unseenet_watchman import cards, dnsbl, watch
from unseenet_watchman.state import State

from test_watch import cfg, msg

card_mod = pytest.importorskip("unseenet.core.cards")
BANK = "https://danske-bank-login.example/x"


def _card(url, title):
return card_mod.Card(url=url, title=title)


@pytest.mark.parametrize("card,page,odd", [
("Log ind på Netbank - Danske Bank", "Cheap watches and pills online", True),
("Ansat i politiet snød Fleggaard: Nu er han dømt",
"Ansat i politiet snød Fleggaard - nu er han dømt | B.T.", False), # the same
("Breaking: famous actor dies", "Cookie consent", False), # a wall, not the page
("Breaking: famous actor dies", "Just a moment...", False),
("Breaking: famous actor dies", "Buy followers cheap today", True),
("Nyt fra kommunen", "Kommunen informerer om vejarbejde", False), # a word shared
("Hej", "Cheap watches and pills online", False), # too short
("Log ind på Netbank - Danske Bank", "Home", False), # page says too little
])
def test_deceptive(card, page, odd):
assert cards.deceptive(card, page) is odd


def test_the_site_name_and_description_count():
assert not cards.deceptive("Proba-3 makes an artificial eclipse",
"Home page", "Proba-3 news and pictures", "ESA")


def _pages(found, asked):
async def fetch(url):
asked.append(url)
if url not in found:
raise OSError("did not answer")
return SimpleNamespace(title=found[url], desc="", site="")
return cards.Pages(fetch, log=lambda m: None)


def test_a_page_is_fetched_once_and_a_dead_one_is_no_finding():
asked = []
pages = _pages({BANK: "Cheap watches and pills online"}, asked)
m = SimpleNamespace(card=_card(BANK, "Log ind på Netbank - Danske Bank"))
why = asyncio.run(cards.check(m, pages))
assert "danske-bank-login.example" in why and "Cheap watches" in why
asyncio.run(cards.check(m, pages))
assert asked == [BANK] # kept, not fetched again
gone = SimpleNamespace(card=_card("https://gone.example/", "Log ind på Netbank - Danske Bank"))
assert asyncio.run(cards.check(gone, pages)) is None
assert asyncio.run(cards.check(SimpleNamespace(card=None), pages)) is None


@pytest.mark.parametrize("on", [True, False])
def test_check_post_reports_it_as_phishing(tmp_path, on):
m = msg(1, "dk.snak@x", "ed25519:spammer", f"Se {BANK}")
m.card = _card(BANK, "Log ind på Netbank - Danske Bank")

async def resolve(q):
return None
lk = dnsbl.Lookups([dnsbl.spamhaus_dqs("K")], resolve, log=lambda x: None)
lk.card_pages = _pages({BANK: "Cheap watches and pills online"}, [])
c = cfg(tmp_path)
c.cards = on
found = asyncio.run(watch.check_post(m, lk, State(tmp_path / "s.json"), c, time.time()))
assert [f.reason for f in found] == (["phishing"] if on else [])
if on:
assert found[0].issuer == "phishing"
5 changes: 5 additions & 0 deletions watchman.example.toml
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,11 @@ skip_groups = ["unseenet.test*"] # e.g. groups where odd posts are the point
# a dry run until publish = true.
labels = false

# Read the page behind a post's link card over Tor and report the post as phishing when
# the card's title has nothing in common with it (UN-RFC 0059 section 11). Each card is
# a fetch over Tor; off by default.
cards = false

[labels]
min_hits = 2 # rude words or phrases in a post for the label ...
short_words = 8 # ... or one, in a post of at most this many words
Expand Down
Loading