1
0
Fork 0
fahrPool/web/lib/firma/smtp-ziel.ts

66 lines
2.1 KiB
TypeScript

import { lookup } from "node:dns/promises";
import { BlockList, isIP } from "node:net";
// Nicht oeffentliche Ziele (SSRF-Schutz fuer den firmeneigenen SMTP-Server).
const GESPERRT = new BlockList();
for (const [netz, laenge] of [
["0.0.0.0", 8],
["10.0.0.0", 8],
["100.64.0.0", 10],
["127.0.0.0", 8],
["169.254.0.0", 16],
["172.16.0.0", 12],
["192.0.0.0", 24],
["192.168.0.0", 16],
["198.18.0.0", 15],
["224.0.0.0", 4],
["240.0.0.0", 4],
] as const) {
GESPERRT.addSubnet(netz, laenge, "ipv4");
}
GESPERRT.addAddress("::", "ipv6");
GESPERRT.addAddress("::1", "ipv6");
GESPERRT.addSubnet("fc00::", 7, "ipv6");
GESPERRT.addSubnet("fe80::", 10, "ipv6");
GESPERRT.addSubnet("ff00::", 8, "ipv6");
// ::ffff:a.b.c.d bzw. ::ffff:xxxx:yyyy auf die eingebettete IPv4-Adresse abbilden.
function normalisiere(ip: string): string {
const punkt = /^::ffff:(\d{1,3}(?:\.\d{1,3}){3})$/i.exec(ip);
if (punkt) return punkt[1];
const hex = /^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i.exec(ip);
if (hex) {
const hoch = parseInt(hex[1], 16);
const tief = parseInt(hex[2], 16);
return `${hoch >> 8}.${hoch & 255}.${tief >> 8}.${tief & 255}`;
}
return ip;
}
function istOeffentlich(ip: string): boolean {
const norm = normalisiere(ip);
const art = isIP(norm);
if (art === 0) return false;
return !GESPERRT.check(norm, art === 4 ? "ipv4" : "ipv6");
}
export type SmtpZielErgebnis = { ok: true; ip: string } | { ok: false };
// Loest den Host auf und liefert die zu verwendende (gepinnte) IP. Alle Adressen
// muessen oeffentlich sein; sonst ok:false (ohne Grund, kein Orakel fuer Admins).
export async function pruefeSmtpZiel(host: string): Promise<SmtpZielErgebnis> {
if (isIP(host) !== 0) {
return istOeffentlich(host) ? { ok: true, ip: host } : { ok: false };
}
let adressen: { address: string }[];
try {
adressen = await lookup(host, { all: true });
} catch {
return { ok: false };
}
if (adressen.length === 0 || !adressen.every((a) => istOeffentlich(a.address))) {
return { ok: false };
}
return { ok: true, ip: adressen[0].address };
}