{"id":"XE-0097","kind":"bounty","visibility":"public","source":"github","source_repo":"xeprotocol/xe","source_ref":"156","source_url":"https://github.com/xeprotocol/xe/issues/156","reporter_id":34,"title":"[Medium] Directory registrations have no freshness bound, and future-dated entries never expire (TTL/prune bypass)","area":"node-api","claimed_tier":"medium","assessed_tier":null,"verdict":null,"duplicate_of":null,"tracked":false,"internal_ref":"","internal_url":null,"status":"triaging","closed_reason":null,"github_state":"open","disclosed_at":null,"award_xe":null,"award_approved":false,"paid_ref":"","created_at":"2026-10-29T13:57:26.377753+00:00","updated_at":"2026-11-14T13:19:32.290103+00:00","source_created_at":"2026-10-29T01:34:20+00:00","told_at":"2026-11-08T20:19:06+00:00","status_changed_at":"2026-11-08T20:17:53.832882+00:00","url":"https://bounty.xe.network/XE-0097","body":"Suggested severity tier: Medium\n\nArea: `directory/verify.go` (`VerifyRegistration`), `directory/directory.go` (`Register`, `Lookup`, `List`, `Prune`), `api/directory.go` (`POST /directory/register`, `GET /directory`, `GET /directory/{account}`), `node/node.go` (`RegisterAccount`, directory prune/re-register loops)\n\nRepository state checked: `xeprotocol/xe` HEAD `978785929bc17a2f4ab30c383e5fc9cf4d634512` (master)\nLive target: `https://ldn.core.test.network` — `xe/16fc1f9`, network `testnet-0005`\n\nXE address for the reward: `ac594521b0cacb948eb907590f07c3240885c4305fce70b4da9fb0e7569d8e71`\n\n## Summary\n\nDirectory registrations are verified by signature only. `VerifyRegistration()` requires `account`, `pub_key`, `node_peer`, `timestamp` and `signature` to be present, checks that `pub_key` derives `account`, and verifies the signature over the canonical bytes — but it never compares `timestamp` with the current time. There is no skew window and no upper bound, so a registration dated arbitrarily far in the future is accepted.\n\nThe TTL is then applied as `time.Since(time.Unix(0, reg.Timestamp))` in `Lookup()` and as `now - reg.Timestamp` in `List()`/`Prune()`. For a future timestamp both expressions are negative, so the entry is always considered fresh: it is served indefinitely and `Prune()` can never remove it.\n\nThe registration endpoint is unauthenticated apart from the signature, needs no account on chain and no funds: an attacker generates a keypair locally and can register as many entries as the per-IP rate limit (10 writes/s) allows. Those entries are gossiped to the rest of the mesh and are permanently immune to the only eviction path the directory has, so `GET /directory` and `GET /directory/{account}` keep advertising a peer for an account that no client can retire.\n\n## What was proven\n\nLive against the public testnet node `https://ldn.core.test.network` (`xe/16fc1f9`, `testnet-0005`), freshly generated keys per case, nothing else touched:\n\n| registration timestamp | `POST /directory/register` | `GET /directory/{account}` | served |\n|---|---|---|---|\n| now | 200 | 200 | yes |\n| now − 5 min | 200 | 200 | yes |\n| now − 31 min | 200 | **404** | no (TTL evicted, correct) |\n| now − 2 h | 200 | 404 | no |\n| now − 25 h | 200 | 404 | no |\n| **now + 10 years** | **200** | **200** | **yes** |\n| **now + 200 years** | **200** | **200** | **yes** |\n\nRe-check 61 minutes after the registrations (TTL has elapsed twice over): the two future-dated entries still answer `200` with their full registration body, while every past-dated entry that exceeded the TTL is gone. The TTL boundary exists, but it only applies to the past.\n\n## Why it happens\n\n- `directory/verify.go:29-51` — `VerifyRegistration()` validates presence, the `pub_key → account` binding and the signature. `reg.Timestamp == 0` is the only timestamp check; any non-zero value is accepted, including values decades ahead of `core.Now()`.\n- `directory/directory.go:61` — `Lookup()`: `if time.Since(time.Unix(0, reg.Timestamp)) > d.ttl { return nil, false }`. With a future timestamp `time.Since` is negative, so the condition is false forever.\n- `directory/directory.go:81` — `List()`: `if now-reg.Timestamp <= int64(d.ttl)`; a future timestamp makes this true forever, so the entry is also always listed.\n- `directory/directory.go:95` — `Prune()`: `if now-reg.Timestamp > int64(d.ttl)`; a future timestamp never satisfies this, so the entry is never pruned.\n- `directory/directory.go:44` — `Register()` keeps the entry with the greater timestamp (`existing.Timestamp >= reg.Timestamp` → no-op), so a future-dated entry cannot be displaced by an equal or lower value either.\n- `api/directory.go:11-23` and `node/node.go:2425-2433` — the handler validates the body and calls `RegisterAccount`, which stores the entry and publishes it to peers; no extra freshness check exists on either path.\n\nCompare `chat/envelope.go` (`MaxEnvelopeSkew`, ±5 min) and `core/ledger.go` (`timestampWindow`) — both bound freshness — and `net/marketplace_sign.go`, which is the same \"verified by signature, no age check\" pattern that issue #18 reports for marketplace messages. The directory path was not covered by that report: registrations use their own message type, their own verifier and their own TTL/eviction code, and are not fixed by #134.\n\n## Impact\n\n- **Un-retirable directory state.** Any guest can create entries that survive forever in an in-memory map that has no other eviction path. Each entry carries a 64-char account, 64-char key, peer ID and 128-char signature (~400 B with map/JSON overhead); the per-IP write limit of 10/s, multiplied by the usual botnet or many-node vantage points, makes sustained growth of every node's directory practical while the operator's prune loop silently reports nothing to remove.\n- **Permanent stale advertisements served to the whole mesh.** `GET /directory` and `GET /directory/{account}` are public and are the lookup used to map an account to a libp2p peer. Entries dated in the future are gossiped to peers (`node.go:2429`) and stay advertised there, so a client that resolves through the directory can be pointed at a peer that was never alive, with no expiry to clean it up.\n- **Broken accounting for operators.** The prune loop (`node.go:2385-2398`) and `Directory.TTL()`-based self-registration (`node.go:2401-2423`) treat TTL as the source of truth for liveness; entries that can never be pruned make that signal unreliable.\n\nI am reporting this as Medium: it is a missing check on a public, unauthenticated endpoint with a reproducible impact on shared directory state, not a consensus or fund-loss bug.\n\n## Reproduction\n\n`poc_directory_ttl_standalone.py` — needs only Python 3 and an ed25519 library (`pynacl`). It generates its own keypair per case, builds the canonical registration payload, signs it, registers it, and immediately looks the account up:\n\n```python\n#!/usr/bin/env python3\n\"\"\"XE testnet directory TTL/skew PoC. python3 poc_directory_ttl_standalone.py [node-url]\"\"\"\nimport hashlib, json, secrets, sys, time, urllib.error, urllib.request\nfrom nacl.signing import SigningKey\n\nNODE = sys.argv[1] if len(sys.argv) > 1 else \"https://ldn.core.test.network\"\nNETWORK_ID = \"testnet-0005\"\nADDR_DOMAIN = \"xe/account/v1\"\nREG_TAG = b\"xe/directory-registration/v1\\x00\"\nUA = \"Mozilla/5.0\"\nMIN, HOUR, YEAR = 60 * 10**9, 3600 * 10**9, 365 * 24 * 3600 * 10**9\nB58 = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\"\n\ndef b58(data):\n    n, out = int.from_bytes(data, \"big\"), \"\"\n    while n:\n        n, r = divmod(n, 58); out = B58[r] + out\n    return \"1\" * (len(data) - len(data.lstrip(b\"\\x00\"))) + out\n\ndef peer_id(pub):\n    proto = bytes([0x08, 0x01, 0x12, 0x20]) + pub\n    return b58(bytes([0x00, len(proto)]) + proto)\n\ndef address(pub):\n    return hashlib.sha256(ADDR_DOMAIN.encode() + pub).hexdigest()\n\ndef sign_registration(sk, account, pub_hex, peer, ts):\n    buf = bytearray(REG_TAG)\n    for f in (NETWORK_ID, account, pub_hex, peer, str(ts)):\n        fb = f.encode(); buf += len(fb).to_bytes(8, \"big\") + fb\n    return sk.sign(hashlib.sha256(bytes(buf)).digest()).signature.hex()\n\ndef post(path, payload):\n    req = urllib.request.Request(NODE + path, data=json.dumps(payload).encode(),\n                                headers={\"Content-Type\": \"application/json\", \"User-Agent\": UA}, method=\"POST\")\n    try:\n        with urllib.request.urlopen(req, timeout=30) as r: return r.status\n    except urllib.error.HTTPError as e: return e.code\n\ndef get(path):\n    req = urllib.request.Request(NODE + path, headers={\"User-Agent\": UA})\n    try:\n        with urllib.request.urlopen(req, timeout=30) as r: return r.status, json.load(r)\n    except urllib.error.HTTPError as e: return e.code, None\n\nnow = time.time_ns()\nfor label, delta in ((\"now\", 0), (\"now - 2h\", -2 * HOUR), (\"now + 10 years\", 10 * YEAR)):\n    sk = SigningKey(secrets.token_bytes(32)); pub = bytes(sk.verify_key)\n    account, peer, ts = address(pub), peer_id(pub), now + delta\n    reg = {\"account\": account, \"pub_key\": pub.hex(), \"node_peer\": peer, \"timestamp\": ts,\n           \"signature\": sign_registration(sk, account, pub.hex(), peer, ts)}\n    rc = post(\"/directory/register\", reg); gc, body = get(\"/directory/\" + account)\n    served = gc == 200 and isinstance(body, dict) and body.get(\"account\") == account\n    print(f\"{label:16} register={rc}  GET={gc}  served={served}\")\n    time.sleep(0.2)\n```\n\nObserved run (2026-10-29, node `xe/16fc1f9`):\n\n```\nnow              register=200  GET /directory/{acct}=200  served=True\nnow - 2h         register=200  GET /directory/{acct}=404  served=False\nnow + 10 years   register=200  GET /directory/{acct}=200  served=True\n```\n\nFull log, the exact accounts used and the 61-minute re-check output are available on request; the re-check prints `future-dated (now + 10 years): HTTP 200 served=True` while every past-dated case is `404`.\n\n## Suggested fix\n\n1. In `VerifyRegistration()`, bound the timestamp the same way the other signed message types do: reject `|core.Now().UnixNano() - reg.Timestamp| > <skew window>` (the chat envelope uses ±5 min; the ledger uses `timestampWindow`).\n2. Make the TTL arithmetic robust regardless of clock skew: use an absolute difference (or clamp negative ages to zero) in `Lookup()`, `List()` and `Prune()`, so a future-dated entry is treated as expiring `ttl` after its timestamp rather than never.\n3. Optionally reject registrations whose account has no on-chain presence, and/or cap the number of live entries per source IP.\n","patch_refs":[{"id":171,"repo":"xeprotocol/xe","kind":"pr","ref":"165","title":"directory: enforce freshness bounds and TTL window on registrations (#156)","url":"https://github.com/xeprotocol/xe/pull/165","note":"","state":"open","author":"fangjian-bit","added_by":"desk","created_at":"2026-10-29T13:57:30.091343+00:00"}],"thread":[{"id":46,"source":"github","source_ref":"6487370681","author":"fangjian-bit","team":false,"body":"I have submitted a clean fix in PR #165 (https://github.com/xeprotocol/xe/pull/165).\n\n### Summary of Fix\n- Enforced freshness bounds in `directory/verify.go:VerifyRegistration`: reject timestamps further ahead than `MaxRegistrationSkew = 5 * time.Minute` (`registration timestamp too far in the future`) and reject registrations older than `DefaultTTL + MaxRegistrationSkew` (`registration timestamp expired`).\n- Hardened `Directory.Lookup`, `List`, and `Prune` in `directory/directory.go` so future-skewed entries do not evade TTL expiration or block un-retirable directory state.\n- Added comprehensive unit tests in `directory/directory_test.go` covering `now`, past thresholds, and the `now + 10 years` / `now + 200 years` PoC attack vectors.","created_at":"2026-10-29T03:48:42+00:00"},{"id":1172,"source":"github","source_ref":"6726599157","author":"Joseph Denne","team":true,"body":"Thanks for the report. We have confirmed the behaviour you describe and it is being handled; we will update this ticket when there is more to share.","created_at":"2026-11-08T20:19:06+00:00"},{"id":3080,"source":"web","source_ref":"reporter:34:f509b17a6e57113c","author":"ryurea6","team":false,"body":"Re-test against the live node, 2026-11-14 UTC (ldn.core.test.network, build xe/3019b76, network testnet-0005, same script that produced the original PoC in poc_directory_ttl_standalone.py):\n\n- timestamp = now: register 200, GET /directory/{account} 200, served.\n- timestamp = now - 2h: register 400, GET 404, not served.\n- timestamp = now + 10 years: register 400, GET 404, not served.\n\nThe far-future registration that the report described is now refused at registration and no longer served, while a registration dated now still succeeds, so the freshness/TTL bound the report asked for now holds in the live build. Nothing further from me on the reproduction; the entry that was immortal on 2026-10-29 is not accepted any more.","created_at":"2026-11-14T13:19:32.269043+00:00"},{"id":14933,"source":"github","source_ref":"7043026986","author":"ryurea6","team":false,"body":"Re-test on the current live build, 2026-11-20 UTC — `https://ldn.core.test.network`, build `xe/2c5ed5a`, network `testnet-0006` (the node has been rebuilt and the network id has moved on from `testnet-0005`). Same standalone script that produced the original PoC (`poc_directory_ttl_standalone.py`), freshly generated keys per case, nothing else touched:\n\n| registration timestamp | `POST /directory/register` | `GET /directory/{account}` | served |\n|---|---|---|---|\n| `now` | 200 | 200 | yes |\n| `now - 2h` | 400 | 404 | no |\n| `now + 10 years` | 400 | 404 | no |\n\nThe far-future registration is still refused at registration and is not served, while a registration dated `now` still succeeds — so the freshness/TTL bound holds on the current build as well, not just on the 2026-11-14 build. Nothing further from me on the reproduction.\n\nDesk note: the newer reports of this same class that still claim it is live (`XE-15203`, `XE-16170`, `XE-17811`) do not reproduce against `xe/2c5ed5a` / `testnet-0006` with the same three-case script, so they look like re-tests of the pre-fix build or of the retired `testnet-0005` network.\n\nXE address for the reward (unchanged): `ac594521b0cacb948eb907590f07c3240885c4305fce70b4da9fb0e7569d8e71`","created_at":"2026-11-20T15:11:23+00:00"}]}