fix(poll): tighten claim host parsing and the reference verifier

- poll_url needs an http(s) URL with a non-empty host
- verify_poll_claim.py: 1 h freshness window by default, ReplayGuard for
  per-node replay, v == 2 and at most 8 nodes, 64 KiB input cap, and
  clean rejection of deeply nested JSON
- document which claim fields the signature covers
This commit is contained in:
agessaman committed 2026-11-28 15:37:01 -08:00
1 parent 5445c2f8f1
commit 382731bb55
5 files changed
+92 -16

No files matched your search

+1
View File
@@ -100,6 +100,7 @@ Notes:
`corescope-claim/v1|<origin_id lower>|<poll_url>|<timestamp>|<node_ids sorted, comma-joined>`.
The message is rebuilt from the claim's fields, so re-encoded claims still verify; a valid
signature proves the node named that analyzer, not that the analyzer accepted the node.
Only `origin_id`, `poll_url`, `timestamp` and the target IDs are signed; other fields are advisory.
`scripts/verify_poll_claim.py` is a reference verifier.
## Safety rules (all modes)
+25 -6
View File
@@ -9,7 +9,7 @@ from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from verify_poll_claim import claim_message, verify_claim # noqa: E402
from verify_poll_claim import ReplayGuard, claim_message, verify_claim # noqa: E402
# Built by buildClaimSigMessage/buildClaimJson and signed with lib/ed25519 on the host.
FIRMWARE_CLAIM = json.loads(r"""{"v": 2, "origin": "Bench", "origin_id": "755C4CB9256CA7CDC4ACFDC6CFEEDA849017E5B9F9514E99191BD67E0B0D4276", "timestamp": "2025-11-28T14:26:40.000000+00:00", "plugin": "meshcore.observer_fw/test", "policy_version": "p1", "community": true, "accepts_requests": false, "request_slots": 0, "poll_url": "live.meshcore.ca", "nodes": [{"node_id": "cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd", "reply_hops": 0, "via": null, "key": "shared", "snr": null, "state": "pending", "misses": 0, "last_attempt": null, "last_ok": null}, {"node_id": "0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a", "reply_hops": 0, "via": null, "key": "shared", "snr": null, "state": "pending", "misses": 0, "last_attempt": null, "last_ok": null}, {"node_id": "abababababababababababababababababababababababababababababababab", "reply_hops": 0, "via": null, "key": "shared", "snr": null, "state": "pending", "misses": 0, "last_attempt": null, "last_ok": null}], "sig": "b42af674e19b5a82608e0b1d8684ab0a04966eb77b9d5f9e92d1c329a461c8a287115ee2070dcfe52bd289f4dcee46f69824c347390821ce405bfcc71a937d03"}""")
@@ -24,7 +24,7 @@ class VerifyPollClaimTest(unittest.TestCase):
c = json.loads(json.dumps(FIRMWARE_CLAIM, separators=(",", ":")))
c["nodes"].reverse()
c["origin_id"] = c["origin_id"].lower()
assert verify_claim(c) is None
assert verify_claim(c, now=NOW) is None
def test_message_sorts_targets(self):
assert claim_message(FIRMWARE_CLAIM).endswith(
@@ -34,17 +34,17 @@ class VerifyPollClaimTest(unittest.TestCase):
for field, value in (("poll_url", "dev.meshcore.ca"), ("timestamp", "2025-11-28T14:26:41.000000+00:00")):
c = copy.deepcopy(FIRMWARE_CLAIM)
c[field] = value
assert verify_claim(c) == "signature does not match"
assert verify_claim(c, now=NOW) == "signature does not match"
c = copy.deepcopy(FIRMWARE_CLAIM)
c["nodes"].pop()
assert verify_claim(c) == "signature does not match"
assert verify_claim(c, now=NOW) == "signature does not match"
def test_host_age_and_missing_fields(self):
assert "is not" in verify_claim(FIRMWARE_CLAIM, host="dev.meshcore.ca")
assert "is not" in verify_claim(FIRMWARE_CLAIM, host="dev.meshcore.ca", now=NOW)
assert "old" in verify_claim(FIRMWARE_CLAIM, max_age=60, now=NOW)
c = copy.deepcopy(FIRMWARE_CLAIM)
del c["sig"]
assert verify_claim(c) == "missing sig"
assert verify_claim(c, now=NOW) == "missing sig"
def test_malformed_input_is_rejected_not_raised(self):
bad = [None, [], {"nodes": None}]
@@ -70,6 +70,25 @@ class VerifyPollClaimTest(unittest.TestCase):
early = datetime(2025, 11, 28, 14, 0, tzinfo=timezone.utc)
self.assertIn("future", verify_claim(FIRMWARE_CLAIM, max_age=3600, now=early))
def test_fresh_by_default_and_schema_limits(self):
late = datetime(2025, 11, 28, 16, 0, tzinfo=timezone.utc)
self.assertIn("old", verify_claim(FIRMWARE_CLAIM, now=late))
self.assertIsNone(verify_claim(FIRMWARE_CLAIM, max_age=None))
c = copy.deepcopy(FIRMWARE_CLAIM)
c["nodes"] = c["nodes"] * 3
self.assertIn("more than", verify_claim(c, now=NOW))
c = copy.deepcopy(FIRMWARE_CLAIM)
c["v"] = 3
self.assertEqual("v is not 2", verify_claim(c, now=NOW))
def test_replay_guard_accepts_each_claim_once(self):
guard = ReplayGuard()
self.assertIsNone(guard.check(FIRMWARE_CLAIM))
self.assertIn("not newer", guard.check(copy.deepcopy(FIRMWARE_CLAIM)))
newer = copy.deepcopy(FIRMWARE_CLAIM)
newer["timestamp"] = "2025-11-28T14:56:40.000000+00:00"
self.assertIsNone(guard.check(newer))
if __name__ == "__main__":
unittest.main()
+44 -6
View File
@@ -10,6 +10,9 @@ The message is rebuilt from the claim's fields, so a re-encoded claim still
verifies. A valid signature proves the node holding origin_id's key named this
host, time and target list; it does not prove the server accepted the node.
Only target IDs are signed: envelope fields (community, policy_version, ...)
and per-target status (state, snr, misses, ...) are advisory.
Usage: verify_poll_claim.py [--host HOST] [--max-age SECONDS] [claim.json | -]
Exit status: 0 valid, 1 invalid, 2 unusable input.
"""
@@ -24,6 +27,10 @@ from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
PREFIX = "corescope-claim/v1"
MAX_NODES = 8
MAX_AGE_S = 3600
MAX_SKEW_S = 300
MAX_INPUT_BYTES = 64 * 1024
HEX64 = re.compile(r"[0-9a-fA-F]{64}")
HEX128 = re.compile(r"[0-9a-fA-F]{128}")
HOST = re.compile(r"[a-z0-9.:\[\]-]+")
@@ -41,6 +48,8 @@ def check_fields(claim):
"""Return None when every signed field has its exact wire shape, else the reason."""
if not isinstance(claim, dict):
return "claim is not a JSON object"
if claim.get("v") != 2:
return "v is not 2"
for field in ("origin_id", "poll_url", "timestamp", "sig"):
if not isinstance(claim.get(field), str):
return f"missing {field}"
@@ -55,14 +64,19 @@ def check_fields(claim):
nodes = claim.get("nodes")
if not isinstance(nodes, list):
return "nodes is not a list"
if len(nodes) > MAX_NODES:
return f"more than {MAX_NODES} nodes"
for n in nodes:
if not isinstance(n, dict) or not isinstance(n.get("node_id"), str) or not HEX64.fullmatch(n["node_id"]):
return "a node_id is not 64 hex digits"
return None
def verify_claim(claim, host=None, max_age=None, now=None, max_skew=300):
"""Return None when the claim verifies, else the reason it does not."""
def verify_claim(claim, host=None, max_age=MAX_AGE_S, now=None, max_skew=MAX_SKEW_S):
"""Return None when the claim verifies, else the reason it does not.
max_age=None turns the freshness check off (for tests and archives only).
"""
reason = check_fields(claim)
if reason:
return reason
@@ -86,19 +100,43 @@ def verify_claim(claim, host=None, max_age=None, now=None, max_skew=300):
return None
class ReplayGuard:
"""Keeps the newest accepted timestamp per origin_id; an older or equal one is a replay."""
def __init__(self):
self._newest = {}
def check(self, claim):
"""Call after verify_claim() accepted the claim. Return None to accept, else the reason."""
origin = claim["origin_id"].lower()
ts = claim["timestamp"] # fixed-width UTC, so string order is time order
last = self._newest.get(origin)
if last is not None and ts <= last:
return f"not newer than the last claim from this node ({last})"
self._newest[origin] = ts
return None
def main():
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
ap.add_argument("claim", nargs="?", default="-")
ap.add_argument("--host", help="require this poll_url host")
ap.add_argument("--max-age", type=int, help="reject claims older than this many seconds")
ap.add_argument("--max-age", type=int, default=MAX_AGE_S,
help=f"reject claims older than this many seconds (default {MAX_AGE_S}; 0 = no limit)")
args = ap.parse_args()
try:
text = sys.stdin.read() if args.claim == "-" else open(args.claim).read()
if args.claim == "-":
text = sys.stdin.read(MAX_INPUT_BYTES + 1)
else:
with open(args.claim) as f:
text = f.read(MAX_INPUT_BYTES + 1)
if len(text) > MAX_INPUT_BYTES:
raise ValueError(f"input is over {MAX_INPUT_BYTES} bytes")
claim = json.loads(text)
except (OSError, ValueError) as e:
except (OSError, ValueError, RecursionError, MemoryError) as e:
print(f"unusable input: {e}", file=sys.stderr)
return 2
reason = verify_claim(claim, args.host, args.max_age)
reason = verify_claim(claim, args.host, args.max_age or None)
if reason:
print(f"INVALID: {reason}")
return 1
+14 -4
View File
@@ -101,15 +101,25 @@ static inline uint8_t claimKeyFor(const ClaimNode& n) {
return CLAIM_KEY_SHARED;
}
// The lowercase host[:port] of a base URL: the scheme and anything from the first '/', '?' or '#' are
// dropped. A host with any byte outside [a-z0-9.-:[]] yields "", so it never reaches a signed claim.
// The lowercase host[:port] of an http(s) base URL: anything from the first '/', '?' or '#' is dropped.
// No http(s) scheme, an empty host, or a byte outside [a-z0-9.-:[]] yields "", so it never reaches a
// signed claim.
static inline size_t claimUrlHost(char* out, size_t cap, const char* url) {
if (!out || cap == 0) return 0;
size_t n = 0;
out[0] = '\0';
if (!url) return 0;
const char* sep = strstr(url, "://");
const char* p = sep ? sep + 3 : url;
const char* p = url;
static const char* const kSchemes[] = {"https://", "http://"};
for (const char* scheme : kSchemes) {
size_t i = 0;
while (scheme[i] && (url[i] == scheme[i] || (url[i] >= 'A' && url[i] <= 'Z' && url[i] - 'A' + 'a' == scheme[i]))) i++;
if (!scheme[i]) {
p = url + i;
break;
}
}
if (p == url || *p == ':') return 0;
for (; *p && *p != '/' && *p != '?' && *p != '#'; p++) {
char c = *p;
if (c >= 'A' && c <= 'Z') c = static_cast<char>(c - 'A' + 'a');
@@ -509,6 +509,13 @@ TEST(PollClaims, ExtendedClaimReportsPollUrlHost) {
EXPECT_EQ(0u, poll::claimUrlHost(host, sizeof(host), "https://user@a.example"));
EXPECT_EQ(5u, poll::claimUrlHost(host, sizeof(host), "http://[::1]/"));
EXPECT_EQ(0u, poll::claimUrlHost(host, 4, "https://abcd"));
// Only an http(s) URL with a host yields one.
EXPECT_EQ(0u, poll::claimUrlHost(host, sizeof(host), "xhttps://evil.example"));
EXPECT_EQ(0u, poll::claimUrlHost(host, sizeof(host), "live.meshcore.ca"));
EXPECT_EQ(0u, poll::claimUrlHost(host, sizeof(host), "https://:8080/"));
EXPECT_EQ(0u, poll::claimUrlHost(host, sizeof(host), "https://"));
EXPECT_EQ(6u, poll::claimUrlHost(host, sizeof(host), "HTTP://a.b:81"));
EXPECT_STREQ("a.b:81", host);
// A new server is sent at once; blank, null and the plain v2 claim leave the field out.
poll::ClaimOptions other = opts;
@@ -903,6 +910,7 @@ TEST(PollClaims, ExtendedWorstCaseFitsClaimBuffer) {
// 31 origin bytes, each one written as a six-byte \u00XX escape.
const std::string origin(31, '\x01');
const std::string plugin = "meshcore.observer_fw/" + std::string(poll::kPluginTagMax - 22, 'p');
// The poller never sets via (it lists direct targets only), so via stays null here.
// A 15-byte policy version the parser accepts, each byte escaped as \u00XX.
const std::string policy(15, '\x01');
// The longest poll.url the setting holds, all of it host.