// Passive DNS-Messung der Gemeinde-Websites: CNAME, A, AAAA, NS und Netzbetreiber (ASN). // Es wird keine Verbindung zu den Websites selbst aufgebaut. // Aufruf: node 03-messen.mjs --pilot 300 oder node 03-messen.mjs --alle // Der Lauf ist fortsetzbar: fertige Hosts in der Ergebnisdatei werden übersprungen. import { createHash } from 'node:crypto'; import { appendFileSync, existsSync, readFileSync, writeFileSync } from 'node:fs'; import { promises as dns } from 'node:dns'; import { dirname, join } from 'node:path'; import { fileURLToPath } from 'node:url'; const hier = dirname(fileURLToPath(import.meta.url)); const pilotIdx = process.argv.indexOf('--pilot'); const pilot = pilotIdx > -1 ? Number(process.argv[pilotIdx + 1] || 300) : 0; const listeIdx = process.argv.indexOf('--liste'); const listeDatei = listeIdx > -1 ? process.argv[listeIdx + 1] : null; const laufIdx = process.argv.indexOf('--lauf'); if (!pilot && !listeDatei && !process.argv.includes('--alle')) { console.error('Bitte --pilot , --alle oder --liste --lauf angeben'); process.exit(2); } const lauf = listeDatei ? (process.argv[laufIdx + 1] ?? 'nach') : pilot ? 'pilot' : 'voll'; const ausgabe = join(hier, 'daten', `messung-${lauf}.jsonl`); const asDatei = join(hier, 'daten', `as-namen-${lauf}.json`); const GLEICHZEITIG = 6; const resolver = ['1.1.1.1', '8.8.8.8'].map((server) => { const r = new dns.Resolver({ timeout: 2500, tries: 2 }); r.setServers([server]); return r; }); async function frage(art, name) { let letzter = 'UNBEKANNT'; for (const r of resolver) { try { return { w: await r[art](name) }; } catch (e) { if (e.code === 'ENODATA' || e.code === 'ENOTFOUND') return { leer: e.code }; letzter = e.code ?? String(e); } } return { fehler: letzter }; } function merke(cache, schluessel, f) { if (!cache.has(schluessel)) cache.set(schluessel, f()); return cache.get(schluessel); } function nibbles(ip) { const [l, r = ''] = ip.split('::'); const links = l ? l.split(':') : []; const rechts = r ? r.split(':') : []; const mitte = Array(Math.max(0, 8 - links.length - rechts.length)).fill('0'); return [...links, ...mitte, ...rechts].map((t) => t.padStart(4, '0')).join('').split('').reverse().join('.'); } const felder = (txt) => txt.split('|').map((s) => s.trim()); const ipCache = new Map(); const asCache = new Map(); const nsCache = new Map(); const zonenCache = new Map(); function ipInfo(ip) { return merke(ipCache, ip, async () => { const name = ip.includes(':') ? `${nibbles(ip)}.origin6.asn.cymru.com` : `${ip.split('.').reverse().join('.')}.origin.asn.cymru.com`; const t = await frage('resolveTxt', name); if (!t.w?.length) return { ip, asn: null, grund: t.fehler ?? t.leer }; // Bei mehreren Einträgen gilt der spezifischste Präfix, die Reihenfolge der Antworten wechselt. const laenge = (p) => Number(String(p).split('/')[1] ?? 0); const [asn, prefix, land, rir] = t.w.map((e) => felder(e.join(''))).sort((a, b) => laenge(b[1]) - laenge(a[1]))[0]; const erste = asn.split(' ')[0]; await asName(erste); return { ip, asn: erste, prefix, ipLand: land, rir }; }); } function asName(asn) { return merke(asCache, asn, async () => { const t = await frage('resolveTxt', `AS${asn}.asn.cymru.com`); if (!t.w?.length) return { asn, name: null, land: null }; const f = felder(t.w[0].join('')); return { asn, land: f[1] || null, name: f[4] || null }; }); } async function cnameKette(host) { const kette = []; let aktuell = host; for (let i = 0; i < 8; i++) { const c = await frage('resolveCname', aktuell); if (!c.w?.length) break; aktuell = c.w[0].toLowerCase().replace(/\.$/, ''); kette.push(aktuell); } return kette; } function zoneVon(name) { return merke(zonenCache, name, async () => { const teile = name.split('.'); for (let i = 0; i < teile.length - 1; i++) { const kandidat = teile.slice(i).join('.'); const c = await frage('resolveCname', kandidat); if (c.w?.length) continue; const n = await frage('resolveNs', kandidat); if (n.w?.length) return { zone: kandidat, ns: n.w.map((s) => s.toLowerCase().replace(/\.$/, '')).sort() }; } return null; }); } function nsInfo(ns) { return merke(nsCache, ns, async () => { const a = await frage('resolve4', ns); if (!a.w?.length) return { ns, asn: null }; const info = await ipInfo(a.w[0]); return { ns, ip: a.w[0], asn: info.asn }; }); } async function adressen(host) { const [a, aaaa] = await Promise.all([frage('resolve4', host), frage('resolve6', host)]); return { a: a.w ?? [], aaaa: aaaa.w ?? [], fehlerA: a.fehler ?? null, leerA: a.leer ?? null }; } async function messe(host) { let genutzt = host; let adr = await adressen(host); if (!adr.a.length && !adr.aaaa.length) { const ersatz = host.startsWith('www.') ? host.slice(4) : `www.${host}`; const zweite = await adressen(ersatz); if (zweite.a.length || zweite.aaaa.length) { genutzt = ersatz; adr = zweite; } } const status = adr.a.length || adr.aaaa.length ? 'ok' : adr.fehlerA ? 'fehler' : 'keine_adresse'; const cname = status === 'ok' ? await cnameKette(genutzt) : []; const ips = [...adr.a, ...adr.aaaa]; const netz = await Promise.all(ips.slice(0, 8).map(ipInfo)); const zone = await zoneVon(genutzt); const ns = zone ? await Promise.all(zone.ns.slice(0, 4).map(nsInfo)) : []; return { host, genutzt, zeit: new Date().toISOString(), status, grund: adr.fehlerA ?? adr.leerA, cname, a: adr.a, aaaa: adr.aaaa, netz, zone: zone?.zone ?? null, ns, }; } const gemeinden = readFileSync(join(hier, 'daten', 'gemeinden.jsonl'), 'utf8').trim().split('\n').map((z) => JSON.parse(z)); let hosts = [...new Set(gemeinden.filter((g) => g.host).map((g) => g.host))]; if (listeDatei) hosts = [...new Set(readFileSync(listeDatei, 'utf8').split(/\r?\n/).map((z) => z.trim().toLowerCase()).filter(Boolean))]; if (pilot) { const sortwert = (h) => createHash('sha256').update(`pilot-1:${h}`).digest('hex'); hosts = hosts.sort((a, b) => sortwert(a).localeCompare(sortwert(b))).slice(0, pilot); } const fertig = new Set( existsSync(ausgabe) ? readFileSync(ausgabe, 'utf8').trim().split('\n').filter(Boolean).map((z) => JSON.parse(z).host) : [], ); const offen = hosts.filter((h) => !fertig.has(h)); console.log(`Lauf ${lauf}: ${hosts.length} Hosts, davon offen ${offen.length}`); const start = Date.now(); let pos = 0; let erledigt = 0; await Promise.all(Array.from({ length: GLEICHZEITIG }, async () => { while (pos < offen.length) { const host = offen[pos++]; let zeile; try { zeile = await messe(host); } catch (e) { zeile = { host, zeit: new Date().toISOString(), status: 'fehler', grund: String(e.message ?? e) }; } appendFileSync(ausgabe, `${JSON.stringify(zeile)}\n`); erledigt++; if (erledigt % 250 === 0) console.log(`${erledigt}/${offen.length} nach ${Math.round((Date.now() - start) / 1000)} s`); } })); const asListe = await Promise.all([...asCache.values()]); const bisher = existsSync(asDatei) ? JSON.parse(readFileSync(asDatei, 'utf8')) : {}; for (const e of asListe) bisher[e.asn] = e; writeFileSync(asDatei, JSON.stringify(bisher, null, 1)); const alle = readFileSync(ausgabe, 'utf8').trim().split('\n').map((z) => JSON.parse(z)); const status = {}; const proAs = {}; for (const z of alle) { status[z.status] = (status[z.status] ?? 0) + 1; const asn = z.netz?.[0]?.asn; if (asn) proAs[asn] = (proAs[asn] ?? 0) + 1; } console.log(JSON.stringify({ dauerSekunden: Math.round((Date.now() - start) / 1000), hosts: alle.length, status, mitIPv6: alle.filter((z) => z.aaaa?.length).length, mitCname: alle.filter((z) => z.cname?.length).length, ohneAsn: alle.filter((z) => z.status === 'ok' && !z.netz?.[0]?.asn).length, topNetze: Object.entries(proAs).sort((a, b) => b[1] - a[1]).slice(0, 15) .map(([asn, n]) => ({ asn, n, land: bisher[asn]?.land, name: bisher[asn]?.name })), }, null, 1));