21 分鐘閱讀 · 企業電子郵件與雲端

客戶打電話來說,我們寄出的報價單進了垃圾郵件資料夾,而這封郵件明明是用公司電子郵件正常寄送的。另一種常見情況是,會計或業務部門反映 ERP 系統寄出的郵件沒有送達部分收件者。一個可能的原因是,公司的網域還沒有向收件方宣告哪些寄件方可以代為寄信,或者有其他系統在管理員不知情的情況下以公司名義寄信。
本文用真實的程式來檢查這件事:一個 Node.js 單檔腳本,讀取網域的 SPF、DKIM、DMARC 和 MX 記錄,然後拿去對幾個眾所周知的公開網域執行。你會看到真實的數字,例如 SPF 用了多少次 DNS lookup、DMARC 的策略設在哪一級、DKIM 金鑰有多少位元。接下來是逐步調整策略的規劃表,以及一個彙整 DMARC 報告的小腳本,用來找出我們遺漏的寄件方。全部程式碼都在 examples/spf-dkim-dmarc-company-email 資料夾中,只用 Node.js 24,不需要安裝任何套件。
文中的公司範例(工廠、商店、辦公室)是為了呈現工作順序而假設的,並非 BT San 客戶的專案;標明為假設的數字也不是真實統計。公開網域的檢查結果來自 2026年11月21日 實際執行程式所得,而 DNS 隨時可能變動。
真實問題:任何人都可以把你的網域填進 From 欄位
基礎的郵件寄送協定(SMTP)在設計時就不檢查寄件者是否真的有權使用該網域。任何人都可以把 From 欄位設成 accounts@你們公司,因此收件方無從得知這封郵件到底來自真正的公司還是別人。SPF、DKIM 和 DMARC 是後來加上的三層機制,讓收件方可以進行驗證。每一層都透過你網域的 DNS 記錄來運作,所以這是負責管理 DNS 的人必須親自動手的工作,電子郵件服務供應商無法全部代勞。
另一個必須做的理由是收件方的門檻。依據 Google email sender guidelines 文件,向 Gmail 寄信的所有寄件方都必須至少設定 SPF 或 DKIM 其中一項;向 Gmail 帳號每天寄送超過 5,000 封郵件的寄件方,必須同時設定 SPF、DKIM 和 DMARC(DMARC 策略可以設為 none),並且郵件必須依同一份文件的 alignment 要求通過 DMARC。其他收件方有各自的標準。這些標準會變動,因此在做決定前應先開啟服務供應商的最新頁面。
三層機制如何運作
SPF:哪些伺服器可以代這個網域寄信
SPF(RFC 7208)是一筆以 v=spf1 開頭的 TXT 記錄,後面依序列出允許的寄送來源,例如 ip4:、include:、a、mx,並以 all 結尾,同時用限定符(qualifier)說明不在清單中的來源應視為什麼:-all 是 fail,~all 是 softfail,?all 是 neutral,+all 表示允許所有人,不應使用,因為這等於沒有 SPF。收件方拿寄信伺服器的 IP 與這份清單比對,依據的是 envelope 位址(MAIL FROM)中的網域,而不是人們看到的 From 欄位。
人們常常不知道的一個限制是 RFC 7208 第 4.6.4 節規定的 DNS lookup 上限:收件方在評估 SPF 時,lookup 不得超過 10 次。計入次數的有 include、a、mx、ptr、exists 和 redirect,而 ip4、ip6 和 all 不計入。巢狀的 include 會一層層繼續累計。如果超過 10 次,結果為 permerror,郵件可能被拒收。Microsoft 的文件也有一致的說明。此外,一個網域只能有一筆 SPF 記錄;如果有兩筆,結果同樣是 permerror。
DKIM:郵件本身的簽章
DKIM(RFC 6376)讓寄信伺服器用私鑰對郵件標頭和內文簽章,並把簽章放在 DKIM-Signature 標頭中,其中註明 d=(簽章的網域)和 s=(selector)。收件方從 DNS 中名為 selector._domainkey.網域 的記錄取得公鑰,再驗證簽章。金鑰記錄含有 k=(金鑰類型)和 p=(base64 格式的公鑰)等標籤。如果 p= 為空,表示該金鑰已被撤銷。一個網域可以有多個 selector,因此可用來輪替金鑰,或依寄信系統區分。依據 Google 的寄件方文件,向個人 Gmail 帳號寄信的寄件方必須使用 1024 位元或更長的 DKIM 金鑰。
DMARC:把驗證結果綁定到人們看到的網域,並規定應如何處理
DMARC 位於 _dmarc.網域,是一筆以 v=DMARC1 開頭的 TXT 記錄,有三項職責。第一,規定郵件必須通過 SPF 或 DKIM,且通過驗證的網域要與 From 欄位一致(alignment)。第二,用 p=none、quarantine 或 reject 告訴收件方,驗證不通過時該怎麼做。第三,用 rua= 要求收件方回傳報告。如果 SPF 通過,但通過驗證的網域與 From 不一致,就不算通過 DMARC。
關於標準:長期被引用的 RFC 7489 已被 RFC 9989(DMARC 協定)和 RFC 9990(aggregate reporting)取代,RFC Editor 頁面上註明新版 obsoletes RFC 7489。新版移除了 pct 標籤,並新增了 t、np、psd 等標籤,但許多正在使用的實際記錄仍帶有 pct,因此仍需照常讀取。本文的範例程式碼可以讀取 pct,範例報告的格式依照 RFC 7489 附錄 C,而收件方實際寄出的報告可能因新版而有所不同。
Alignment:SPF 通過但 DMARC 不通過的關鍵
一封郵件至少涉及三個網域,而 DMARC 會拿其中兩個與 From 欄位的網域比對。下表概括了誰與誰比對。
| 郵件中的網域 | 位於何處 | 用於什麼 | DMARC 是否與 From 比對 |
|---|---|---|---|
| Header From | 使用者看到的 From 欄位 | DMARC 的參照對象 | 是被比對的一方 |
| Envelope MAIL FROM | 透過 SMTP 寄送時的位址(Return-Path) | SPF 檢查這個網域 | 是,必須與 From align |
| DKIM d= | 在 DKIM-Signature 標頭中 | DKIM 檢查簽章的網域 | 是,必須與 From align |
| 模式 | 標籤 | 含義 | 假設範例(From = mail.factory.example) |
|---|---|---|---|
| relaxed(預設) | adkim=r, aspf=r | 主網域(organizational domain)一致即可 | d=factory.example 視為 align |
| strict | adkim=s, aspf=s | 必須每個字元都完全相同 | d=factory.example 不 align,必須是 mail.factory.example |
與外部系統往來時常見的情況是:ERP 系統或郵件寄送服務使用服務供應商的網域作為 MAIL FROM,SPF 雖然通過,但通過的是服務供應商的網域而不是公司的網域,所以不 align。解決辦法是讓該系統用公司的網域對郵件做 DKIM 簽章(d=公司網域),或者在服務供應商支援的情況下設定 custom return-path。下面的範例報告中就有這樣的一行。
範例 1:用程式讀取記錄
假設有一家工廠(假設範例)使用某家服務供應商的主電子郵件,ERP 系統寄送發票,文件掃描機把檔案寄到信箱。在修改 DNS 之前,管理員想先瞭解目前的狀態。程式分為兩部分:檔案 lib.mjs 存放邏輯,把 resolver 作為參數傳入,方便測試時換成模擬的 DNS;check.mjs 則是從命令列啟動的入口。
第一部分是 SPF。關鍵在於 lookup 的統計:在整棵 include 和 redirect 的樹中使用同一個計數器(RFC 中關於 void lookup 的補充規定,以及把 mx 展開為 A lookup 的情況,本範例沒有計入,屬於近似估算)。
// ---- SPF (RFC 7208) ----
const isSpf = (t) => /^v=spf1(\s|$)/i.test(t);
// Terms that cost a DNS lookup: include, a, mx, ptr, exists, redirect (RFC 7208 4.6.4).
export function lookupTerms(record) {
return record.trim().split(/\s+/).slice(1).map((t) => t.replace(/^[+\-~?]/, "")).filter((t) =>
/^(include:|exists:|redirect=|ptr(:|$)|a(:|\/|$)|mx(:|\/|$))/i.test(t));
}
export async function checkSpf(domain, r, state = { lookups: 0, seen: new Set() }, top = true) {
const records = (await r.txt(domain)).filter(isSpf);
if (top && records.length === 0) return { found: false };
if (records.length !== 1) return { found: records.length > 0, records: records.length, lookups: state.lookups, problem: records.length ? "more than one SPF record (permerror)" : "no SPF record" };
const record = records[0];
const out = { found: true, records: 1, record, all: (record.match(/(?:^|\s)([+\-~?]?)all(?=\s|$)/i) || [])[1] };
if (out.all === "") out.all = "+"; // bare "all" means +all
for (const term of lookupTerms(record)) {
state.lookups++;
const m = term.match(/^(?:include:|redirect=)(.+)$/i);
if (m && !state.seen.has(m[1].toLowerCase())) {
state.seen.add(m[1].toLowerCase());
await checkSpf(m[1], r, state, false); // children add to the shared counter
}
}
if (top) { out.lookups = state.lookups; out.overLimit = state.lookups > 10; }
return out;
}DMARC 部分用 parseTags 拆分標籤,再依規範補上預設值(pct=100、adkim=r、aspf=r),並對設定偏弱的情況產生警告,例如沒有 rua 的 p=none,意味著什麼都不攔截,也沒有任何人收到報告。
// ---- DMARC (RFC 7489) ----
export async function checkDmarc(domain, r) {
const rec = (await r.txt("_dmarc." + domain)).filter((t) => /^v=DMARC1\s*;/i.test(t));
if (rec.length === 0) return { found: false, warnings: ["no DMARC record"] };
const t = parseTags(rec[0]);
const d = { found: true, record: rec[0], p: t.p, sp: t.sp, pct: t.pct ?? "100", rua: t.rua, ruf: t.ruf, adkim: t.adkim ?? "r", aspf: t.aspf ?? "r", warnings: [] };
if (rec.length > 1) d.warnings.push("more than one DMARC record");
if (!["none", "quarantine", "reject"].includes(d.p)) d.warnings.push("p= missing or invalid");
if (d.p === "none" && !d.rua) d.warnings.push("p=none without rua: monitoring only and nobody gets the reports");
if (d.p === "none" && d.rua) d.warnings.push("p=none: monitoring only, nothing is blocked yet");
if (d.p !== "none" && Number(d.pct) < 100) d.warnings.push(`pct=${d.pct}: policy applies to a sample only`);
if (!d.rua && d.p !== "none") d.warnings.push("no rua= (no aggregate reports)");
return d;
}DKIM 部分透過把 p= 的 base64 解碼成 DER,再讓 node:crypto 模組讀取 modulusLength 來估算金鑰大小,這比從字串長度猜測更準確;如果金鑰是 ed25519,則依原始金鑰大小回報為 256 位元。
// ---- DKIM (RFC 6376) ----
export function keyBits(tags) {
if (!tags.p) return null;
const der = Buffer.from(tags.p.replace(/\s+/g, ""), "base64");
if ((tags.k ?? "rsa").toLowerCase() === "ed25519") return 256; // raw 32-byte key
try { return createPublicKey({ key: der, format: "der", type: "spki" }).asymmetricKeyDetails.modulusLength; }
catch { return null; } // not a valid SPKI key
}
export async function checkDkim(domain, selector, r) {
const rec = (await r.txt(`${selector}._domainkey.${domain}`)).filter((t) => /(^|;)\s*p=/i.test(t));
if (rec.length === 0) return { selector, found: false };
const t = parseTags(rec[0]);
return { selector, found: true, k: t.k ?? "rsa", revoked: t.p === "", bits: keyBits(t), testing: /(^|:)y(:|$)/.test(t.t ?? "") };
}入口程式只是呼叫上面的函式並印出結果。管理員必須自行指定 selector,因為 DNS 沒有辦法查詢某個網域有哪些 selector。服務供應商通常使用可預期的名稱,例如 Microsoft 365 使用 selector1 和 selector2。
// Usage: node check.mjs <domain> [selector ...]
import { realResolver as r, checkSpf, checkDmarc, checkDkim } from "./lib.mjs";
const [domain, ...selectors] = process.argv.slice(2);
if (!domain) { console.error("usage: node check.mjs <domain> [selector ...]"); process.exit(2); }
console.log(`== ${domain}`);
const mx = await r.mx(domain);
console.log("MX:", mx.length ? mx.map((m) => `${m.priority} ${m.exchange}`).join(", ") : "(none)");
const spf = await checkSpf(domain, r);
if (!spf.found) console.log("SPF: not found");
else {
console.log(`SPF: records=${spf.records} all=${spf.all ? spf.all + "all" : "(none)"} lookups=${spf.lookups}/10${spf.overLimit ? " OVER LIMIT (permerror)" : ""}`);
if (spf.problem) console.log(" problem:", spf.problem);
}
const dmarc = await checkDmarc(domain, r);
if (!dmarc.found) console.log("DMARC: not found");
else {
console.log(`DMARC: p=${dmarc.p} sp=${dmarc.sp ?? "-"} pct=${dmarc.pct} adkim=${dmarc.adkim} aspf=${dmarc.aspf} rua=${dmarc.rua ? "yes" : "no"} ruf=${dmarc.ruf ? "yes" : "no"}`);
}
for (const w of dmarc.warnings) console.log(" warn:", w);
for (const s of selectors) {
const k = await checkDkim(domain, s, r);
console.log(k.found
? `DKIM ${s}: k=${k.k} ${k.revoked ? "REVOKED (p= empty)" : `~${k.bits} bits`}${k.testing ? " (testing flag)" : ""}`
: `DKIM ${s}: not found`);
}公開網域的真實結果
我們用程式檢查了五個公開網域:google.com、microsoft.com,以及三個在 DNS 中公布了 DMARC 策略的泰國網域。這些資料本來就任何人都能讀取,我們只是拿來對照,讓大家有個直觀印象,並不評斷哪個組織的設定是對是錯,因為每個組織都有我們看不到的背景,而且所試的 selector 只是猜測的常見名稱,所以只能看到找得到的部分。
== google.com
MX: 10 smtp.google.com
SPF: records=1 all=~all lookups=1/10
DMARC: p=reject sp=- pct=100 adkim=r aspf=r rua=yes ruf=no
DKIM google: not found
DKIM 20230601: k=rsa REVOKED (p= empty)
== microsoft.com
MX: 10 microsoft-com.mail.protection.outlook.com
SPF: records=1 all=-all lookups=6/10
DMARC: p=reject sp=- pct=100 adkim=r aspf=r rua=yes ruf=yes
DKIM selector1: not found
DKIM selector2: k=rsa ~1024 bits
== kasikornbank.com
MX: 5 kasikornbank-com.mail.protection.outlook.com
SPF: records=1 all=-all lookups=2/10
DMARC: p=reject sp=- pct=100 adkim=r aspf=r rua=yes ruf=yes
DKIM selector1: k=rsa ~2048 bits
DKIM selector2: k=rsa ~2048 bits
== chula.ac.th
MX: 20 mail2-gw1.it.chula.ac.th, 100 mail-gw1.it.chula.ac.th
SPF: records=1 all=-all lookups=9/10
DMARC: p=quarantine sp=- pct=100 adkim=r aspf=r rua=yes ruf=yes
DKIM google: k=rsa ~1024 bits
DKIM s1: k=rsa ~2048 bits
== thaipbs.or.th
MX: 10 mx1.hc112-45.ap.iphmx.com, 10 mx2.hc112-45.ap.iphmx.com, 20 thaipbs-or-th.mail.protection.outlook.com
SPF: records=1 all=~all lookups=3/10
DMARC: p=none sp=- pct=100 adkim=r aspf=r rua=no ruf=no
warn: p=none without rua: monitoring only and nobody gets the reports
DKIM selector1: k=rsa ~1024 bits
DKIM selector2: not found
== sample-report.xml (known sender: 192.0.2.10)
192.0.2.10 pass= 125 fail= 0 known
198.51.100.7 pass= 0 fail= 35 UNKNOWN sender
203.0.113.99 pass= 0 fail= 8 UNKNOWN sender
unknown senders: 2結果解讀如下:每個網域都只有一筆 SPF 記錄;all 限定符各不相同,有的用 -all,有的用 ~all。lookup 次數差異很大:google.com 用了 1 次,而 chula.ac.th 用了 9 次(上限 10 次),意味著只剩 1 次的餘地,如果再新增一個需要 include 的郵件寄送服務,就可能超出上限。這組網域的 DMARC 策略三個級別都有,即 reject、quarantine 和 none,而設為 none 的網域既有帶 rua 的,也有不帶 rua 的,對後者程式會提出警告。在 DKIM 方面可以看到,1024 位元和 2048 位元的金鑰都在使用,而且 google.com 有一個 selector 已被撤銷(p= 為空),這是服務供應商用來停用舊金鑰的做法。
最後兩行來自 report.mjs 和我們自己撰寫的範例檔案,將在下面的 DMARC 報告一節中說明。
範例 2:讀取 DMARC 報告,找出被遺忘的寄件方
設定 rua= 之後,大型收件方會每天向指定的信箱寄送一份彙總報告(aggregate report),格式為 XML 檔案。檔案中說明哪個 IP 以你的網域寄了多少封郵件,以及 SPF/DKIM 的 align 結果如何。報告一多,肉眼幾乎無法閱讀,所以需要有彙整工具。我們的範例使用自己撰寫的範例檔案,其結構依照 RFC 7489 附錄 C;檔案中的網域和 IP 是文件範例專用的值(factory.example,以及 192.0.2.0/24、198.51.100.0/24、203.0.113.0/24 範圍內的 IP),不屬於任何人的資料。
<?xml version="1.0" encoding="UTF-8" ?>
<!-- MADE-UP sample shaped like RFC 7489 Appendix C. Domain and IPs are documentation examples. -->
<feedback>
<report_metadata>
<org_name>receiver.example</org_name>
<email>[email protected]</email>
<report_id>made-up-0001</report_id>
<date_range><begin>1700000000</begin><end>1700086399</end></date_range>
</report_metadata>
<policy_published>
<domain>factory.example</domain>
<adkim>r</adkim><aspf>r</aspf><p>none</p><pct>100</pct>
</policy_published>
<record>
<row><source_ip>192.0.2.10</source_ip><count>120</count>
<policy_evaluated><disposition>none</disposition><dkim>pass</dkim><spf>pass</spf></policy_evaluated></row>
<identifiers><header_from>factory.example</header_from></identifiers>
<auth_results><dkim><domain>factory.example</domain><result>pass</result></dkim>
<spf><domain>factory.example</domain><result>pass</result></spf></auth_results>
</record>
<record>
<row><source_ip>198.51.100.7</source_ip><count>35</count>
<policy_evaluated><disposition>none</disposition><dkim>fail</dkim><spf>fail</spf></policy_evaluated></row>
<identifiers><header_from>factory.example</header_from></identifiers>
<auth_results><spf><domain>erp-mailer.example</domain><result>pass</result></spf></auth_results>
</record>
<record>
<row><source_ip>203.0.113.99</source_ip><count>8</count>
<policy_evaluated><disposition>none</disposition><dkim>fail</dkim><spf>fail</spf></policy_evaluated></row>
<identifiers><header_from>factory.example</header_from></identifiers>
<auth_results><spf><domain>factory.example</domain><result>fail</result></spf></auth_results>
</record>
<record>
<row><source_ip>192.0.2.10</source_ip><count>5</count>
<policy_evaluated><disposition>none</disposition><dkim>pass</dkim><spf>fail</spf></policy_evaluated></row>
<identifiers><header_from>factory.example</header_from></identifiers>
<auth_results><dkim><domain>factory.example</domain><result>pass</result></dkim></auth_results>
</record>
</feedback>腳本 report.mjs 依 IP 彙整郵件數量,分為通過和未通過,判斷 DMARC 通過的依據是 policy_evaluated 中的 dkim 或 spf 為 pass;然後與我們已知的 IP 清單比對,剩下的就是未知寄件方。值得注意的是,在範例 XML 中,198.51.100.7 那一行的原始 SPF 結果對 erp-mailer.example 網域是 pass,但 policy_evaluated 是 fail,因為該網域與 From 不 align。這就是前面提到的 ERP 系統使用服務供應商 MAIL FROM 的情況。
// Sum DMARC results per source IP from an aggregate report and flag unknown senders.
// Usage: node report.mjs <report.xml> [known-ip ...]
import { readFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
// A record counts as DMARC-pass when either aligned check (dkim / spf in policy_evaluated) passes.
// simplified: regex parsing is enough for the fixed report shape; use a real XML parser for production.
export function summarize(xml) {
const perIp = new Map();
for (const [, rec] of xml.matchAll(/<record>([\s\S]*?)<\/record>/g)) {
const get = (tag) => rec.match(new RegExp(`<${tag}>([^<]*)</${tag}>`))?.[1];
const ip = get("source_ip"), n = Number(get("count"));
const pe = rec.match(/<policy_evaluated>([\s\S]*?)<\/policy_evaluated>/)[1];
const pass = /<dkim>pass</.test(pe) || /<spf>pass</.test(pe);
const row = perIp.get(ip) ?? { pass: 0, fail: 0 };
row[pass ? "pass" : "fail"] += n;
perIp.set(ip, row);
}
return perIp;
}
export function flagUnknown(perIp, known) {
return [...perIp].filter(([ip]) => !known.includes(ip)).map(([ip]) => ip);
}
if (process.argv[1] === fileURLToPath(import.meta.url)) {
const [file, ...known] = process.argv.slice(2);
const perIp = summarize(readFileSync(file, "utf8"));
const unknown = flagUnknown(perIp, known);
for (const [ip, { pass, fail }] of perIp)
console.log(`${ip.padEnd(15)} pass=${String(pass).padStart(4)} fail=${String(fail).padStart(4)} ${known.includes(ip) ? "known" : "UNKNOWN sender"}`);
console.log(`unknown senders: ${unknown.length}`);
}結果見上面 output.txt 的末尾:192.0.2.10 是已知寄件方,通過 125 封(120 封兩項都通過,加上 5 封 DKIM 通過但 SPF 未通過,這仍算通過 DMARC)。而 198.51.100.7 未通過 35 封,203.0.113.99 未通過 8 封,兩者都是未知寄件方。管理員需要去詢問 198.51.100.7 是否是我們的 ERP 系統;如果是,就改為用公司網域做 DKIM 簽章;如果不是,而且沒人認識它,就說明有人在冒用網域寄信,而這正是 DMARC 設為 reject 最終能夠攔住的。
如果需要定期閱讀真實的報告,建議使用廣泛使用的開源工具,例如 GitHub 上的 parsedmarc(domainaware/parsedmarc,採用 Apache-2.0 授權),它透過 IMAP 或 API 接收報告,再轉送到資料檢視系統。我們的範例寫得很短,只是為了呈現原理。
範例 3:可離線執行的測試
這類做計數和拆分的程式碼很容易悄悄出錯,例如修改 regex 後把 include 多數了一個。因此有一個測試檔案,用固定表格的模擬 DNS,不需要連網,測試 lookup 計數器、超過上限、有兩筆 SPF 記錄的情況、DMARC 的警告、用測試中現場產生的金鑰來檢查 DKIM 金鑰大小(必須得到 2048),以及報告彙整。
// Offline self-check: node --test test.mjs (DNS is replaced by a fixed table)
import test from "node:test";
import assert from "node:assert/strict";
import { generateKeyPairSync } from "node:crypto";
import { readFileSync } from "node:fs";
import { checkSpf, checkDmarc, checkDkim, lookupTerms } from "./lib.mjs";
import { summarize, flagUnknown } from "./report.mjs";
const zone = (t) => ({ txt: async (n) => t[n] ?? [], mx: async () => [] });
test("SPF: counts lookups through includes, ignores ip4/all, reads qualifier", async () => {
const r = zone({
"a.example": ["v=spf1 include:b.example mx a:mail.a.example ip4:192.0.2.0/24 ~all"], // 3 terms
"b.example": ["v=spf1 include:c.example exists:%{i}.x.example -all"], // +2
"c.example": ["v=spf1 ptr ip6:2001:db8::/32 -all"], // +1
});
const s = await checkSpf("a.example", r);
assert.equal(s.lookups, 6);
assert.equal(s.all, "~");
assert.equal(s.overLimit, false);
assert.deepEqual(lookupTerms("v=spf1 ip4:1.2.3.4 -all"), []);
});
test("SPF: 11 lookups is over the limit; two records is a problem", async () => {
const many = "v=spf1 " + Array.from({ length: 11 }, (_, i) => `include:i${i}.example`).join(" ") + " -all";
assert.equal((await checkSpf("a.example", zone({ "a.example": [many] }))).overLimit, true);
const two = await checkSpf("a.example", zone({ "a.example": ["v=spf1 -all", "v=spf1 +all"] }));
assert.match(two.problem, /more than one/);
});
test("DMARC: tags and weak-setup warnings", async () => {
const weak = await checkDmarc("a.example", zone({ "_dmarc.a.example": ["v=DMARC1; p=none"] }));
assert.equal(weak.pct, "100");
assert.ok(weak.warnings.some((w) => w.includes("without rua")));
const ok = await checkDmarc("a.example", zone({ "_dmarc.a.example": ["v=DMARC1; p=quarantine; pct=25; rua=mailto:[email protected]; adkim=s"] }));
assert.equal(ok.adkim, "s");
assert.ok(ok.warnings.some((w) => w.includes("pct=25")));
assert.equal((await checkDmarc("none.example", zone({}))).found, false);
});
test("DKIM: key size from a real generated key, revoked key", async () => {
const { publicKey } = generateKeyPairSync("rsa", { modulusLength: 2048 });
const p = publicKey.export({ type: "spki", format: "der" }).toString("base64");
const r = zone({ "s1._domainkey.a.example": [`v=DKIM1; k=rsa; p=${p}`], "old._domainkey.a.example": ["v=DKIM1; p="] });
assert.equal((await checkDkim("a.example", "s1", r)).bits, 2048);
assert.equal((await checkDkim("a.example", "old", r)).revoked, true);
assert.equal((await checkDkim("a.example", "nope", r)).found, false);
});
test("Report: sums per IP and flags unknown senders", () => {
const m = summarize(readFileSync(new URL("./sample-report.xml", import.meta.url), "utf8"));
assert.deepEqual(m.get("192.0.2.10"), { pass: 125, fail: 0 }); // 120 + 5 (dkim pass, spf fail still passes DMARC)
assert.deepEqual(m.get("203.0.113.99"), { pass: 0, fail: 8 });
assert.deepEqual(flagUnknown(m, ["192.0.2.10"]), ["198.51.100.7", "203.0.113.99"]);
});三種假設情境
由 ERP 寄送發票的工廠
假設範例:工廠使用某家服務供應商的主電子郵件,ERP 系統把發票寄給客戶,掃描機寄送內部檔案。首先要做的是盤點,然後檢查並讓 ERP 用公司網域做 DKIM 簽章。發票關係到錢,郵件進垃圾郵件匣或被拒收就會影響收款,所以應讓這個系統先於其他系統通過 DMARC,並用報告檢查結果。
有行銷郵件的商店
假設範例:商店使用外部服務供應商的電子報寄送系統。Microsoft 文件建議把我們無法控制的服務(例如大量郵件 bulk email)移到子網域上(例如 marketing.公司網域),這樣可以把信譽與員工郵件分開,並擁有自己的 10 次 lookup 上限。好處是,如果電子報被檢舉為垃圾郵件,主網域寄出的報價郵件不會受到太大連帶影響。
用掃描機寄送警示郵件的辦公室
假設範例:掃描機和監視攝影機以公司的 noreply 名義,直接從辦公室的 IP 寄送警示郵件。這類裝置通常無法做 DKIM 簽章。可選的做法是在 SPF 中加入辦公室的 ip4:(不計入 lookup),或者讓它們透過會代為簽章的主郵件伺服器寄送。需要注意的是,如果辦公室的 IP 隨網際網路服務供應商而變,就必須相應更新 SPF。
lookup 預算:用假設的數字計算
假設某公司有四個 include(主電子郵件、ERP、電子報、掃描機),並假設每個 include 在巢狀計算時合計使用 2 次 lookup,則共計 4 × 2 = 8 次 lookup。如果再新增一個會用到 3 次的新服務,就會變成 11 次,超過 10 次的上限。這個數字是為了呈現思路而假設的,真實情況請直接執行 check.mjs 查看。
依服務供應商文件列出的記錄範例
表中的值來自各家的官方文件(連結見參考資料清單),以 contoso.com 或假設的網域取代真實網域,而且服務供應商可能會更改這些值。實際使用前,務必開啟最新頁面,並始終使用服務供應商在管理員頁面為你產生的值。
| 服務供應商 | SPF(網域根部的 TXT) | DKIM |
|---|---|---|
| Google Workspace | v=spf1 include:_spf.google.com ~all | 在 Admin console 頁面產生金鑰,再把 TXT 值放進 DNS(本輪尚未核對 Google 的 DKIM 步驟頁面) |
| Microsoft 365 | v=spf1 include:spf.protection.outlook.com -all | 兩筆 CNAME:selector1._domainkey 和 selector2._domainkey,指向 Microsoft 為每個網域指定的目標(文件中的值僅為示意,請使用你自己網域的值) |
| Zoho Mail | v=spf1 include:zoho.com -all(如果使用 Zoho 的多項服務,文件顯示為 include:one.zoho.com) | 在 Admin console 中建立 selector 和金鑰,再作為 TXT 放在 selector._domainkey.網域,然後按 Verify 並啟用 |
文件中的觀察:Microsoft 指出,對於 Microsoft 365 網域建議使用 -all,因為它與 DKIM 和 DMARC 搭配使用,並提醒如果郵件沒有 DKIM 簽章,DMARC 搭配 ~all 就無法充分發揮作用。而 Google 的範例使用 ~all,這也是可接受的選擇。兩者並不矛盾,只是預設值不同。另外,Microsoft 不建議對 Microsoft 365 的 SPF 做 flatten,因為 IP 經常變動。
逐步調整 DMARC 策略的規劃
不要在第一天就設成 reject。比較安全的順序是:先只觀察,再逐步讓收件方採取行動。下表是我們依據 RFC 中各策略的含義歸納的通用做法,沒有規定具體時程,因為這取決於報告什麼時候變得乾淨。
| 步驟 | 範例記錄 | 對收件方的影響 | 需要查看什麼 |
|---|---|---|---|
| 1 只觀察 | v=DMARC1; p=none; rua=mailto:dmarc@公司網域 | 不攔截郵件,收件方會寄送報告 | 所有來源 IP 的清單:哪些認識,哪些不認識 |
| 2 修正真實的寄件方 | 同上 | 同上 | 已知但未通過的寄件方(忘了 include、沒有用公司網域做 DKIM 簽章、沒有 align) |
| 3 部分 quarantine | p=quarantine; pct=10(起始數字為假設,再逐步提高) | 收件方把一部分未通過的郵件放入可疑郵件分組 | 有沒有人抱怨郵件遺失;報告中未通過的郵件是否只剩未知寄件方 |
| 4 完整 quarantine | p=quarantine (pct=100) | 所有未通過的郵件都被攔下歸為可疑 | 未經通知就新增的寄件方 |
| 5 reject | p=reject | 收件方拒收未通過的郵件 | 退回的郵件(bounce);透過報告持續觀察,並有人負責在新增系統時跟進 |
在推進每一步之前,先用 report.mjs 或 parsedmarc 這類工具查看:已知寄件方是否幾乎全部通過,未知 IP 的清單是否都已追查清楚。如果有完全不用來寄信的網域,就直接發布 v=spf1 -all 和 DMARC p=reject。Microsoft 也建議對閒置網域(parked domain)使用 v=spf1 -all。
郵件轉寄和郵件群組會讓結果失真
- 轉寄(forwarding):被轉寄的郵件會來自轉寄伺服器的 IP,而這個 IP 不在原始網域的 SPF 中,所以轉寄後 SPF 通常不通過。而 DKIM 只要簽章的郵件標頭和內文沒有被修改,仍然可以通過,因此應讓每個系統都做 DKIM 簽章,不要只依賴 SPF。
- 郵件群組:郵件群組軟體常常修改主旨或在郵件末尾加內容,導致原有的 DKIM 簽章失效,寄送的 IP 也隨之改變。設為 p=reject 的網域,其成員寄出的郵件經過郵件群組後可能被拒收。如果組織有外部郵件群組,應在升級為 reject 之前先查看報告。
- 代寄的服務供應商:以公司名義寄信的預約系統或 HR 系統必須列入盤點清單,否則在提升策略時會被攔下。
- 子網域:如果不設定 sp=,子網域沿用主網域的 p= 策略;而寄信的子網域必須有自己的 SPF(依據 Microsoft 的文件,主網域的 SPF 記錄不涵蓋子網域)。
常見錯誤與檢查清單
- 有兩筆 SPF 記錄:結果為 permerror,應合併為一筆(可用 check.mjs 檢查,它會提示 more than one SPF record)
- include 超過 10 次 lookup:減少服務數量、把服務移到子網域,或者在服務供應商有固定 IP 且文件有註明時改用 ip4:(如 Microsoft 所建議的),但之後需要有人追蹤 IP 的變化
- include 寫錯格式:例如在網域末尾加了句點、用 = 代替 :,或在 include: 後面留了空格(Microsoft 把它列為錯誤範例)
- 把 +all 或 ?all 一直留著:會讓 SPF 幾乎失去作用
- 沒有 rua 的 DMARC p=none:既不攔截也沒有報告,等於什麼都沒學到
- 在盤點寄件方之前就設成 reject:被遺忘的系統寄出的真實郵件會遺失
- DKIM 金鑰太短:Google 文件規定個人 Gmail 要使用 1024 位元或更長
- 忘了舊金鑰:輪替金鑰之後,應依服務供應商的步驟刪除舊金鑰或把 p= 設為空
- 列出所有以網域名義寄信的系統,並註明各系統的負責人
- 修改之前,先記錄原有的 SPF、DKIM、DMARC 記錄
- 對主網域和用來寄信的子網域執行 check.mjs,查看 lookup 次數和警告
- 在主電子郵件系統以及所有代寄信的系統中啟用 DKIM,並讓 d= 網域與公司網域一致
- 設定 DMARC p=none,並配上真正有人閱讀的 rua 信箱
- 逐步查看報告,直到已知寄件方都通過,再處理未知寄件方
- 依上表升級為 quarantine 和 reject
- 每次修改後都測試寄信,並在新增系統時指定專人查看報告
如果要實際應用
本文的程式碼是學習用的範例,不是 production 等級的工具。需要瞭解的限制有:lookup 的統計是近似的(沒有計入展開為 A lookup 的 mx,也沒有計入 void lookup),不評估哪個 IP 實際會通過或不通過,用 regex 讀取報告,而且只測試了已撰寫的部分。如果要當作日常工作使用,應當按日保存報告,在出現未知的新 IP 或 lookup 次數接近上限時發出提醒,並記錄每個郵件寄送系統由誰核准。
檢查結果變好並不意味著郵件一定會進入 inbox,因為收件方還會考慮其他因素,例如 IP 的信譽和內容;而且 SPF、DKIM、DMARC 也無法防止使用外觀相似網域的釣魚郵件。但它們是大多數收件方已經期待的基礎。
參考資料
- RFC 7208: Sender Policy Framework (SPF) (accessed 2026-11-21)
- RFC 6376: DomainKeys Identified Mail (DKIM) Signatures (accessed 2026-11-21)
- RFC 7489: DMARC (obsoleted by RFC 9989) (accessed 2026-11-21)
- RFC 9989: DMARC Protocol (accessed 2026-11-21)
- Google: Email sender guidelines (accessed 2026-11-21)
- Google Workspace: Set up SPF (accessed 2026-11-21)
- Microsoft: Set up SPF to help prevent spoofing (accessed 2026-11-21)
- Microsoft: Use DKIM for email in your custom domain (accessed 2026-11-21)
- Zoho Mail: SPF configuration (accessed 2026-11-21)
- Zoho Mail: DKIM configuration (accessed 2026-11-21)




