#!/usr/bin/env node // Checks a Visto evidence file without Visto: node scripts/verify-record.mjs // Needs only Node.js 18+. For the signed timestamps it also uses OpenSSL (installed on macOS and Linux). // It checks: // 1. every event's fingerprint: hash = SHA-256(prevHash + "|" + material), chained from 64 zeros; // 2. every event's material matches the event shown in the file (id, kind, who, version, data, time); // 3. every signed timestamp: the digest is SHA-256 of its lines, one line is this record at that point // of the chain, and (with OpenSSL) freetsa.org's signature over that digest and its time. // It cannot tell whether events were left out after the last signed timestamp, or whether what people // typed was true; it shows whether the record was changed after it was fingerprinted and timestamped. // It does not check Bitcoin: an OpenTimestamps proof is only checked to belong to the right digest, and is // saved so it can be checked at opentimestamps.org. import { createHash } from "node:crypto"; import { readFileSync, writeFileSync, mkdtempSync } from "node:fs"; import { execFileSync } from "node:child_process"; import { tmpdir } from "node:os"; import { join } from "node:path"; export function verifyEvidence(x) { const sha = s => createHash("sha256").update(s, "utf8").digest("hex"); const problems = [], notes = []; if (x.format !== "visto-evidence/1") problems.push("Unknown file format: " + x.format); let prev = "0".repeat(64); (x.events || []).forEach((e, i) => { if (e.seq !== i + 1) problems.push(`Event ${i + 1}: sequence number is ${e.seq}`); if (e.prevHash !== prev) problems.push(`Event ${e.seq}: does not follow the event before it`); if (sha(prev + "|" + e.material) !== e.hash) problems.push(`Event ${e.seq}: fingerprint does not match its content`); const m = String(e.material); const head = `${e.id}|${x.record.id}|`, tail = "|" + e.at; if (!m.startsWith(head) || !m.endsWith(tail)) problems.push(`Event ${e.seq}: id, record or time differs from what was fingerprinted`); else { const rest = m.slice(head.length, m.length - tail.length).split("|"); const [item, kind, actor, label, v] = rest.slice(0, 5), data = rest.slice(5).join("|"); let same = item === (e.item ?? "") && kind === e.kind && actor === e.actor && label === (e.label ?? "") && v === (e.v == null ? "" : String(e.v)); try { same = same && JSON.stringify(sortKeys(JSON.parse(data))) === JSON.stringify(sortKeys(e.data)); } catch { same = false; } if (!same) problems.push(`Event ${e.seq}: the details shown differ from what was fingerprinted`); } prev = e.hash; }); const n = (x.events || []).length, head = n ? x.events[n - 1].hash : null; if (x.chain && x.chain.head && x.chain.head !== head) problems.push("The record's stated fingerprint differs from its last event"); const tsa = []; for (const t of x.timestamps || []) { const line = `${x.record.id}:${t.covers && t.covers.count}:${t.covers && t.covers.head}`; if (sha((t.lines || []).join("\n")) !== t.digest) { problems.push(`Timestamp ${t.stampedAt}: its digest does not match its lines`); continue; } if (!(t.lines || []).includes(line)) { problems.push(`Timestamp ${t.stampedAt}: does not include this record`); continue; } const at = x.events[Number(t.covers.count) - 1]; if (!at || at.hash !== t.covers.head) { problems.push(`Timestamp ${t.stampedAt}: the record's events up to ${t.covers.count} were changed after this timestamp`); continue; } tsa.push(t); } notes.push(`${n} events, fingerprint ${head || "none"}`); return { ok: problems.length === 0, problems, notes, timestamps: tsa }; } const sortKeys = v => Array.isArray(v) ? v.map(sortKeys) : v && typeof v === "object" ? Object.fromEntries(Object.keys(v).sort().map(k => [k, sortKeys(v[k])])) : v; export async function opensslCheck(t) { const dir = mkdtempSync(join(tmpdir(), "visto-")); const tsr = join(dir, "token.tsr"); writeFileSync(tsr, Buffer.from(t.rfc3161Token, "base64")); try { const text = execFileSync("openssl", ["ts", "-reply", "-in", tsr, "-text"], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }); const when = (text.match(/^Time stamp: (.*)$/m) || [])[1]; const imprint = (text.match(/Message data:\s*([\s\S]*?)\n\S/) || [])[1] || ""; const hex = imprint.split("\n").map(l => (l.match(/ - ((?:[0-9a-f]{2}[ -]?)+)/i) || l.match(/((?:[0-9a-f]{2}[ -]){8,}[0-9a-f]{2})/i) || [])[1] || "").join("").replace(/[^0-9a-f]/gi, "").toLowerCase(); // covers: true / false from the token's message imprint; null if this OpenSSL prints it in a form not recognised. const read = hex.length >= 64 ? hex.includes(t.digest) : null; // timeMatches: whether the time the file claims equals the time inside the signed token (to the second). const signedMs = when ? Date.parse(when.replace(/\.\d+/, "")) : NaN, claimedMs = Date.parse(t.stampedAt); const timeMatches = isNaN(signedMs) || isNaN(claimedMs) ? null : Math.abs(signedMs - claimedMs) < 1000; // signature: true = verified, false = does not verify, null = could not be checked (no network for the certificates) let signature = null; try { for (const [u, n] of [["https://freetsa.org/files/cacert.pem", "cacert.pem"], ["https://freetsa.org/files/tsa.crt", "tsa.crt"]]) { const res = await fetch(u); if (!res.ok) throw new Error("HTTP " + res.status); writeFileSync(join(dir, n), Buffer.from(await res.arrayBuffer())); } } catch { return { when, covers: read, timeMatches, signature: null, file: tsr }; } try { execFileSync("openssl", ["ts", "-verify", "-digest", t.digest, "-in", tsr, "-CAfile", join(dir, "cacert.pem"), "-untrusted", join(dir, "tsa.crt")], { stdio: "pipe" }); signature = true; } catch { signature = false; } // OpenSSL's verify also checks that the token's imprint is this digest, so a verified signature means it covers it. return { when, covers: signature === true ? true : read, timeMatches, signature, file: tsr }; } catch (e) { // OpenSSL missing, or without the timestamp command (some LibreSSL builds): cannot check. // OpenSSL present and able, but the token is unreadable: the token is damaged. const err = String(e.stderr || "") + String(e.message || ""); if (e.code === "ENOENT" || /invalid command|unknown command|not supported|no such command/i.test(err)) return { missing: true, error: "this computer's OpenSSL cannot read timestamp tokens, so the signature was not checked", file: tsr }; return { unreadable: true, error: "the signed token is damaged or not a timestamp token", file: tsr }; } } // OpenTimestamps proof (.ots): after the fixed header and version comes the file-hash operation (0x08 = SHA-256) // and the 32-byte hash it starts from. That hash must be this timestamp's digest. // The proof's attestations are tagged; a Bitcoin block attestation has its own 8-byte tag. This script only looks // for the tag; it does not check the attestation against Bitcoin. const OTS_MAGIC = Buffer.from("004f70656e54696d657374616d7073000050726f6f6600bf89e2e884e89294", "hex"); const OTS_BITCOIN_TAG = Buffer.from("0588960d73d71901", "hex"); export function otsCheck(t) { if (!t.openTimestamps) return null; const b = Buffer.from(t.openTimestamps, "base64"); const ok = b.length > OTS_MAGIC.length + 34 && b.subarray(0, OTS_MAGIC.length).equals(OTS_MAGIC) && b[OTS_MAGIC.length] === 1 && b[OTS_MAGIC.length + 1] === 0x08; const covers = ok && b.subarray(OTS_MAGIC.length + 2, OTS_MAGIC.length + 34).toString("hex") === t.digest; const hasBitcoin = b.includes(OTS_BITCOIN_TAG); // The file says "complete" but the proof holds no Bitcoin attestation: the file's claim is false. return { covers, claimedComplete: t.bitcoin === "complete", hasBitcoin, inconsistent: t.bitcoin === "complete" && !hasBitcoin, bytes: b }; } // One result for the whole file. MATCH only when every fingerprint matches and every signed timestamp's signature checked out. // MISMATCH when anything does not match. INCOMPLETE when nothing mismatched but something could not be checked. // MATCH says only that: it does not say the entries are true, who made them, or that no later events were left out. export function verdict(r, checks) { if (!r.ok || checks.some(o => o.unreadable || o.signature === false || o.covers === false || o.timeMatches === false || (o.bitcoin && (!o.bitcoin.covers || o.bitcoin.inconsistent)))) return "MISMATCH"; if (!checks.length || checks.some(o => o.missing || o.signature !== true || o.timeMatches == null)) return "INCOMPLETE"; return "MATCH"; } if (import.meta.url === `file://${process.argv[1]}`) { const f = process.argv[2]; if (!f) { console.log("Usage: node scripts/verify-record.mjs "); process.exit(2); } const x = JSON.parse(readFileSync(f, "utf8")), r = verifyEvidence(x); console.log(`Visto evidence file for ${x.record.client} (${x.record.id}), exported ${x.exportedAt}`); r.notes.forEach(s => console.log(" " + s)); if (r.ok) console.log("OK Every event's fingerprint matches its content and the chain is unbroken."); else r.problems.forEach(p => console.log("FAIL " + p)); if (!(x.timestamps || []).length) console.log("-- No signed timestamp covers this record yet (they are taken once a day)."); const checks = []; for (const t of r.timestamps) { const o = await opensslCheck(t); o.bitcoin = otsCheck(t); checks.push(o); if (o.bitcoin) { if (!o.bitcoin.covers) console.log(`FAIL Bitcoin proof for ${t.stampedAt}: it is not a proof of this timestamp's digest`); else if (o.bitcoin.inconsistent) console.log(`FAIL Bitcoin proof for ${t.stampedAt}: the file says it is complete, but the proof contains no Bitcoin attestation`); else { const base = f.replace(/\.json$/i, "") + "-bitcoin-" + String(t.stampedAt).slice(0, 10); writeFileSync(base + ".txt", (t.lines || []).join("\n")); writeFileSync(base + ".txt.ots", o.bitcoin.bytes); console.log(o.bitcoin.hasBitcoin ? `-- Bitcoin proof for ${t.stampedAt} contains a Bitcoin attestation. NOT checked against Bitcoin by this script: open https://opentimestamps.org and drop in ${base}.txt.ots and ${base}.txt. It shows the digest existed by that Bitcoin block, which can be later than the freetsa.org time.` : `-- Bitcoin proof for ${t.stampedAt} is still waiting for Bitcoin (no Bitcoin attestation yet; download a newer evidence file later). Saved as ${base}.txt.ots`); } } if (o.error) { console.log(`${o.unreadable ? "FAIL" : "-- "} Timestamp ${t.stampedAt}: ${o.error}`); continue; } const good = o.covers === true && o.signature === true && o.timeMatches === true; const bad = o.signature === false || o.covers === false || o.timeMatches === false; console.log(`${good ? "OK " : bad ? "FAIL" : "-- "} ${t.service}: signed time ${o.when}, covering the first ${t.covers.count} events (digest ${t.digest.slice(0, 16)}…)` + (o.covers === false ? " · THE TOKEN IS FOR A DIFFERENT DIGEST" : o.signature === false ? " · SIGNATURE DOES NOT VERIFY" : o.signature === true ? " · signature checked with OpenSSL" : " · signature not checked (offline?)") + (o.timeMatches === false ? ` · THE FILE CLAIMS ${t.stampedAt}, WHICH IS NOT THE SIGNED TIME` : o.timeMatches == null ? " · signed time could not be read" : "")); if (o.signature !== true) { console.log(` To check freetsa.org's signature yourself: download https://freetsa.org/files/cacert.pem and https://freetsa.org/files/tsa.crt, then run`); console.log(` openssl ts -verify -digest ${t.digest} -in ${o.file} -CAfile cacert.pem -untrusted tsa.crt`); } } const v = verdict(r, checks); // Say exactly what was covered: which events a verified signed timestamp covers, and that Bitcoin was not checked. const total = (x.events || []).length; const covered = Math.max(0, ...r.timestamps.filter((t, i) => checks[i] && checks[i].signature === true && checks[i].covers === true && checks[i].timeMatches === true).map(t => Number(t.covers.count))); console.log(""); console.log("RESULT: " + v + (v === "MATCH" ? " · every event's fingerprint matches its content, and each signed timestamp's signature checked out against the events it names" : v === "MISMATCH" ? " · something in this file does not match; do not rely on it" : " · nothing failed, but not everything could be checked (see the lines marked --)")); if (v !== "MISMATCH") { console.log(covered ? ` Signed timestamps cover events 1-${covered} of ${total}.` + (covered < total ? (covered + 1 === total ? ` Event ${total} is` : ` Events ${covered + 1}-${total} are`) + " fingerprinted but not yet covered by a signed timestamp." : "") : ` No event is covered by a checked signed timestamp; the ${total} events are fingerprinted only.`); console.log(" Bitcoin was not checked by this script (see opentimestamps.org)."); } process.exit(v === "MATCH" ? 0 : v === "MISMATCH" ? 1 : 3); }