implement outgoing tls reports

we were already accepting, processing and displaying incoming tls reports. now
we start tracking TLS connection and security-policy-related errors for
outgoing message deliveries as well. we send reports once a day, to the
reporting addresses specified in TLSRPT records (rua) of a policy domain. these
reports are about MTA-STS policies and/or DANE policies, and about
STARTTLS-related failures.

sending reports is enabled by default, but can be disabled through setting
NoOutgoingTLSReports in mox.conf.

only at the end of the implementation process came the realization that the
TLSRPT policy domain for DANE (MX) hosts are separate from the TLSRPT policy
for the recipient domain, and that MTA-STS and DANE TLS/policy results are
typically delivered in separate reports. so MX hosts need their own TLSRPT
policies.

config for the per-host TLSRPT policy should be added to mox.conf for existing
installs, in field HostTLSRPT. it is automatically configured by quickstart for
new installs. with a HostTLSRPT config, the "dns records" and "dns check" admin
pages now suggest the per-host TLSRPT record. by creating that record, you're
requesting TLS reports about your MX host.

gathering all the TLS/policy results is somewhat tricky. the tentacles go
throughout the code. the positive result is that the TLS/policy-related code
had to be cleaned up a bit. for example, the smtpclient TLS modes now reflect
reality better, with independent settings about whether PKIX and/or DANE
verification has to be done, and/or whether verification errors have to be
ignored (e.g. for tls-required: no header). also, cached mtasts policies of
mode "none" are now cleaned up once the MTA-STS DNS record goes away.
This commit is contained in:
Mechiel Lukkien
2023-11-09 17:40:46 +01:00
parent df18ca3c02
commit 893a6f8911
58 changed files with 3246 additions and 504 deletions

View File

@ -365,7 +365,8 @@ type CheckResult struct {
SPF SPFCheckResult
DKIM DKIMCheckResult
DMARC DMARCCheckResult
TLSRPT TLSRPTCheckResult
HostTLSRPT TLSRPTCheckResult
DomainTLSRPT TLSRPTCheckResult
MTASTS MTASTSCheckResult
SRVConf SRVConfCheckResult
Autoconf AutoconfCheckResult
@ -1130,28 +1131,27 @@ EOF
}
}()
// TLSRPT
wg.Add(1)
go func() {
checkTLSRPT := func(result *TLSRPTCheckResult, dom dns.Domain, address smtp.Address, isHost bool) {
defer logPanic(ctx)
defer wg.Done()
record, txt, err := tlsrpt.Lookup(ctx, resolver, domain)
record, txt, err := tlsrpt.Lookup(ctx, resolver, dom)
if err != nil {
addf(&r.TLSRPT.Errors, "Looking up TLSRPT record: %s", err)
addf(&result.Errors, "Looking up TLSRPT record: %s", err)
}
r.TLSRPT.TXT = txt
result.TXT = txt
if record != nil {
r.TLSRPT.Record = &TLSRPTRecord{*record}
result.Record = &TLSRPTRecord{*record}
}
instr := `TLSRPT is an opt-in mechanism to request feedback about TLS connectivity from remote SMTP servers when they connect to us. It allows detecting delivery problems and unwanted downgrades to plaintext SMTP connections. With TLSRPT you configure an email address to which reports should be sent. Remote SMTP servers will send a report once a day with the number of successful connections, and the number of failed connections including details that should help debugging/resolving any issues.`
if domConf.TLSRPT != nil {
instr := `TLSRPT is an opt-in mechanism to request feedback about TLS connectivity from remote SMTP servers when they connect to us. It allows detecting delivery problems and unwanted downgrades to plaintext SMTP connections. With TLSRPT you configure an email address to which reports should be sent. Remote SMTP servers will send a report once a day with the number of successful connections, and the number of failed connections including details that should help debugging/resolving any issues. Both the mail host (e.g. mail.domain.example) and a recipient domain (e.g. domain.example, with an MX record pointing to mail.domain.example) can have a TLSRPT record. The TLSRPT record for the hosts is for reporting about DANE, the TLSRPT record for the domain is for MTA-STS.`
var zeroaddr smtp.Address
if address != zeroaddr {
// TLSRPT does not require validation of reporting addresses outside the domain.
// ../rfc/8460:1463
uri := url.URL{
Scheme: "mailto",
Opaque: smtp.NewAddress(domConf.TLSRPT.ParsedLocalpart, domConf.TLSRPT.DNSDomain).Pack(false),
Opaque: address.Pack(false),
}
uristr := uri.String()
uristr = strings.ReplaceAll(uristr, ",", "%2C")
@ -1167,11 +1167,29 @@ Ensure a DNS TXT record like the following exists:
_smtp._tls TXT %s
`, mox.TXTStrings(tlsrptr.String()))
} else if isHost {
addf(&result.Errors, `Configure a host TLSRPT localpart in static mox.conf config file.`)
} else {
addf(&r.TLSRPT.Errors, `Configure a TLSRPT destination in domain in config file.`)
addf(&result.Errors, `Configure a domain TLSRPT destination in domains.conf config file.`)
}
addf(&r.TLSRPT.Instructions, instr)
}()
addf(&result.Instructions, instr)
}
// Hots TLSRPT
wg.Add(1)
var hostTLSRPTAddr smtp.Address
if mox.Conf.Static.HostTLSRPT.Localpart != "" {
hostTLSRPTAddr = smtp.NewAddress(mox.Conf.Static.HostTLSRPT.ParsedLocalpart, mox.Conf.Static.HostnameDomain)
}
go checkTLSRPT(&r.HostTLSRPT, mox.Conf.Static.HostnameDomain, hostTLSRPTAddr, true)
// Domain TLSRPT
wg.Add(1)
var domainTLSRPTAddr smtp.Address
if domConf.TLSRPT != nil {
domainTLSRPTAddr = smtp.NewAddress(domConf.TLSRPT.ParsedLocalpart, domain)
}
go checkTLSRPT(&r.DomainTLSRPT, domain, domainTLSRPTAddr, false)
// MTA-STS
wg.Add(1)
@ -1960,3 +1978,51 @@ func (Admin) DMARCRemoveEvaluations(ctx context.Context, domain string) {
err = dmarcdb.RemoveEvaluationsDomain(ctx, dom)
xcheckf(ctx, err, "removing evaluations for domain")
}
// TLSRPTResults returns all TLSRPT results in the database.
func (Admin) TLSRPTResults(ctx context.Context) []tlsrptdb.TLSResult {
results, err := tlsrptdb.Results(ctx)
xcheckf(ctx, err, "get results")
return results
}
// TLSRPTResultsPolicyDomain returns the TLS results for a domain.
func (Admin) TLSRPTResultsPolicyDomain(ctx context.Context, policyDomain string) (dns.Domain, []tlsrptdb.TLSResult) {
dom, err := dns.ParseDomain(policyDomain)
xcheckf(ctx, err, "parsing domain")
results, err := tlsrptdb.ResultsPolicyDomain(ctx, dom)
xcheckf(ctx, err, "get result for policy domain")
return dom, results
}
// LookupTLSRPTRecord looks up a TLSRPT record and returns the parsed form, original txt
// form from DNS, and error with the TLSRPT record as a string.
func (Admin) LookupTLSRPTRecord(ctx context.Context, domain string) (record *TLSRPTRecord, txt string, errstr string) {
dom, err := dns.ParseDomain(domain)
xcheckf(ctx, err, "parsing domain")
resolver := dns.StrictResolver{Pkg: "webadmin"}
r, txt, err := tlsrpt.Lookup(ctx, resolver, dom)
if err != nil && (errors.Is(err, tlsrpt.ErrNoRecord) || errors.Is(err, tlsrpt.ErrMultipleRecords) || errors.Is(err, tlsrpt.ErrRecordSyntax)) {
errstr = err.Error()
err = nil
}
xcheckf(ctx, err, "fetching tlsrpt record")
if r != nil {
record = &TLSRPTRecord{Record: *r}
}
return record, txt, errstr
}
// TLSRPTRemoveResults removes the TLS results for a domain for the given day. If
// day is empty, all results are removed.
func (Admin) TLSRPTRemoveResults(ctx context.Context, domain string, day string) {
dom, err := dns.ParseDomain(domain)
xcheckf(ctx, err, "parsing domain")
err = tlsrptdb.RemoveResultsPolicyDomain(ctx, dom, day)
xcheckf(ctx, err, "removing tls results")
}

View File

@ -19,6 +19,7 @@ table table td, table table th { padding: 0 0.1em; }
table.long >tbody >tr >td { padding: 1em .5em; }
table.long td { vertical-align: top; }
table > tbody > tr:nth-child(odd) { background-color: #f8f8f8; }
table.hover > tbody > tr:hover { background-color: #f0f0f0; }
.text { max-width: 50em; }
p { margin-bottom: 1em; max-width: 50em; }
[title] { text-decoration: underline; text-decoration-style: dotted; }
@ -262,12 +263,12 @@ const index = async () => {
dom.br(),
dom.h2('Reports'),
dom.div(dom.a('DMARC', attr({href: '#dmarc/reports'}))),
dom.div(dom.a('TLS', attr({href: '#tlsrpt'}))),
dom.div(dom.a('TLS', attr({href: '#tlsrpt/reports'}))),
dom.br(),
dom.h2('Operations'),
dom.div(dom.a('MTA-STS policies', attr({href: '#mtasts'}))),
dom.div(dom.a('DMARC evaluations', attr({href: '#dmarc/evaluations'}))),
// todo: outgoing TLSRPT findings
dom.div(dom.a('TLS connection results', attr({href: '#tlsrpt/results'}))),
// todo: routing, globally, per domain and per account
dom.br(),
dom.h2('DNS blocklist status'),
@ -960,8 +961,8 @@ const domainDNSCheck = async (d) => {
dom.div('Domain: ' + checks.DMARC.Domain),
!checks.DMARC.TXT ? [] : dom.div('TXT record: ' + checks.DMARC.TXT),
]
const detailsTLSRPT = !checks.TLSRPT.TXT ? [] : [
dom.div('TXT record: ' + checks.TLSRPT.TXT),
const detailsTLSRPT = (checksTLSRPT) => !checksTLSRPT.TXT ? [] : [
dom.div('TXT record: ' + checksTLSRPT.TXT),
]
const detailsMTASTS = !checks.MTASTS.TXT && !checks.MTASTS.PolicyText ? [] : [
!checks.MTASTS.TXT ? [] : dom.div('MTA-STS record: ' + checks.MTASTS.TXT),
@ -1007,7 +1008,8 @@ const domainDNSCheck = async (d) => {
resultSection('SPF', checks.SPF, detailsSPF),
resultSection('DKIM', checks.DKIM, detailsDKIM),
resultSection('DMARC', checks.DMARC, detailsDMARC),
resultSection('TLSRPT', checks.TLSRPT, detailsTLSRPT),
resultSection('Host TLSRPT', checks.HostTLSRPT, detailsTLSRPT(checks.HostTLSRPT)),
resultSection('Domain TLSRPT', checks.DomainTLSRPT, detailsTLSRPT(checks.DomainTLSRPT)),
resultSection('MTA-STS', checks.MTASTS, detailsMTASTS),
resultSection('SRV conf', checks.SRVConf, detailsSRVConf),
resultSection('Autoconf', checks.Autoconf, detailsAutoconf),
@ -1458,7 +1460,149 @@ const domainDMARCReport = async (d, reportID) => {
)
}
const tlsrpt = async () => {
const tlsrptIndex = async () => {
const page = document.getElementById('page')
dom._kids(page,
crumbs(
crumblink('Mox Admin', '#'),
'TLSRPT reports and connectivity results',
),
dom.ul(
dom.li(
dom.a(attr({href: '#tlsrpt/reports'}), 'Reports'), ', incoming TLS reports.',
),
dom.li(
dom.a(attr({href: '#tlsrpt/results'}), 'Results'), ', for outgoing TLS reports.',
),
),
)
}
const tlsrptResults = async () => {
const results = await api.TLSRPTResults()
// todo: add a view where results are grouped by policy domain+dayutc. now each recipient domain gets a row.
const page = document.getElementById('page')
dom._kids(page,
crumbs(
crumblink('Mox Admin', '#'),
crumblink('TLSRPT', '#tlsrpt'),
'Results',
),
dom.p('Messages are delivered with SMTP with TLS using STARTTLS if supported and/or required by the recipient domain\'s mail server. TLS connections may fail for various reasons, such as mismatching certificate host name, expired certificates or TLS protocol version/cipher suite incompatibilities. Statistics about successful connections and failed connections are tracked. Results can be tracked for recipient domains (for MTA-STS policies), and per MX host (for DANE). A domain/host can publish a TLSRPT DNS record with addresses that should receive TLS reports. Reports are sent every 24 hours. Not all results are enough reason to send a report, but if a report is sent all results are included.'),
dom('table.hover',
dom.thead(
dom.tr(
dom.th('Day (UTC)', attr({title: 'Day covering these results, a whole day from 00:00 UTC to 24:00 UTC.'})),
dom.th('Recipient domain', attr({title: 'Domain of addressee. For delivery to a recipient, the recipient and policy domains will match for reporting on MTA-STS policies, but can also result in reports for hosts from the MX record of the recipient to report on DANE policies.'})),
dom.th('Policy domain', attr({title: 'Domain for TLSRPT policy, specifying URIs to which reports should be sent.'})),
dom.th('Host', attr({title: 'Whether policy domain is an (MX) host (for DANE), or a recipient domain (for MTA-STS).'})),
dom.th('Success', attr({title: 'Total number of successful connections.'})),
dom.th('Failure', attr({title: 'Total number of failed connection attempts.'})),
dom.th('Failure details', attr({title: 'Total number of details about failures.'})),
dom.th('Send report', attr({title: 'Whether the current results will cause a report to be sent. A report is only sent if the domain has a TLSRPT with reporting addresses configured.'})),
),
),
dom.tbody(
results.sort((a, b) => {
if (a.DayUTC !== b.DayUTC) {
return a.DayUTC < b.DayUTC ? -1 : 1
}
if (a.RecipientDomain !== b.RecipientDomain) {
return a.RecipientDomain < b.RecipientDomain ? -1 : 1
}
return a.PolicyDomain < b.PolicyDomain ? -1 : 1
}).map(r => {
let success = 0
let failed = 0
let failureDetails = 0
r.Results.forEach(result => {
success += result.summary['total-successful-session-count']
failed += result.summary['total-failure-session-count']
failureDetails += (result['failure-details'] || []).length
})
return dom.tr(
dom.td(r.DayUTC),
dom.td(r.RecipientDomain),
dom.td(dom.a(attr({href: '#tlsrpt/results/'+r.PolicyDomain}), r.PolicyDomain)),
dom.td(r.IsHost ? '✓' : ''),
dom.td(style({textAlign: 'right'}), ''+success),
dom.td(style({textAlign: 'right'}), ''+failed),
dom.td(style({textAlign: 'right'}), ''+failureDetails),
dom.td(style({textAlign: 'right'}), r.SendReport ? '✓' : ''),
)
}),
results.length === 0 ? dom.tr(dom.td(attr({colspan: '8'}), 'No results.')) : [],
),
),
)
}
const tlsrptResultsPolicyDomain = async (domain) => {
const [d, tlsresults] = await api.TLSRPTResultsPolicyDomain(domain)
const recordPromise = api.LookupTLSRPTRecord(domain)
let recordBox
const page = document.getElementById('page')
dom._kids(page,
crumbs(
crumblink('Mox Admin', '#'),
crumblink('TLSRPT', '#tlsrpt'),
crumblink('Results', '#tlsrpt/results'),
'Policy domain '+domainString(d),
),
dom.div(
dom.button('Remove results', async function click(e) {
e.preventDefault()
e.target.disabled = true
try {
await api.TLSRPTRemoveResults(domain, '')
window.location.reload() // todo: only clear the table?
} catch (err) {
console.log({err})
window.alert('Error: ' + err.message)
} finally {
e.target.disabled = false
}
}),
),
dom.br(),
dom.div('Fetching TLSRPT DNS record for policy domain...'),
recordBox=dom.div(),
dom.br(),
dom.p('Below are the results per day and recipient domain that may be sent in a report.'),
tlsresults.map(tlsresult => [
dom.h2(tlsresult.DayUTC, ' - ', dom.span(attr({title: 'Recipient domain, as used in SMTP MAIL TO, usually based on message To/Cc/Bcc.'}), tlsresult.RecipientDomain)),
dom.p(
'Send report (if TLSRPT exists and has address): '+(tlsresult.SendReport ? 'Yes' : 'No'),
dom.br(),
'Report about (MX) host (instead of recipient domain): '+(tlsresult.IsHost ? 'Yes' : 'No'),
),
dom('div.literal', JSON.stringify(tlsresult.Results, null, '\t')),
])
)
// In background so page load fade doesn't look weird.
;(async () => {
let record, txt, errmsg
try {
[record, txt, errmsg] = await recordPromise
} catch (err) {
errmsg = 'error: '+err.message
}
const l = []
if (txt) {
l.push(dom('div.literal', txt))
}
if (errmsg) {
l.push(box(red, errmsg))
}
dom._kids(recordBox, l)
})()
}
const tlsrptReports = async () => {
const end = new Date().toISOString()
const start = new Date(new Date().getTime() - 30*24*3600*1000).toISOString()
const summaries = await api.TLSRPTSummaries(start, end, '')
@ -2431,7 +2575,13 @@ const init = async () => {
} else if (h === 'queue') {
await queueList()
} else if (h === 'tlsrpt') {
await tlsrpt()
await tlsrptIndex()
} else if (h === 'tlsrpt/reports') {
await tlsrptReports()
} else if (h === 'tlsrpt/results') {
await tlsrptResults()
} else if (t[0] == 'tlsrpt' && t[1] == 'results' && t.length === 3) {
await tlsrptResultsPolicyDomain(t[2])
} else if (h === 'dmarc') {
await dmarcIndex()
} else if (h === 'dmarc/reports') {

View File

@ -807,6 +807,99 @@
}
],
"Returns": []
},
{
"Name": "TLSRPTResults",
"Docs": "TLSRPTResults returns all TLSRPT results in the database.",
"Params": [],
"Returns": [
{
"Name": "r0",
"Typewords": [
"[]",
"TLSResult"
]
}
]
},
{
"Name": "TLSRPTResultsPolicyDomain",
"Docs": "TLSRPTResultsPolicyDomain returns the TLS results for a domain.",
"Params": [
{
"Name": "policyDomain",
"Typewords": [
"string"
]
}
],
"Returns": [
{
"Name": "r0",
"Typewords": [
"Domain"
]
},
{
"Name": "r1",
"Typewords": [
"[]",
"TLSResult"
]
}
]
},
{
"Name": "LookupTLSRPTRecord",
"Docs": "LookupTLSRPTRecord looks up a TLSRPT record and returns the parsed form, original txt\nform from DNS, and error with the TLSRPT record as a string.",
"Params": [
{
"Name": "domain",
"Typewords": [
"string"
]
}
],
"Returns": [
{
"Name": "record",
"Typewords": [
"nullable",
"TLSRPTRecord"
]
},
{
"Name": "txt",
"Typewords": [
"string"
]
},
{
"Name": "errstr",
"Typewords": [
"string"
]
}
]
},
{
"Name": "TLSRPTRemoveResults",
"Docs": "TLSRPTRemoveResults removes the TLS results for a domain for the given day. If\nday is empty, all results are removed.",
"Params": [
{
"Name": "domain",
"Typewords": [
"string"
]
},
{
"Name": "day",
"Typewords": [
"string"
]
}
],
"Returns": []
}
],
"Sections": [],
@ -879,7 +972,14 @@
]
},
{
"Name": "TLSRPT",
"Name": "HostTLSRPT",
"Docs": "",
"Typewords": [
"TLSRPTCheckResult"
]
},
{
"Name": "DomainTLSRPT",
"Docs": "",
"Typewords": [
"TLSRPTCheckResult"
@ -2148,6 +2248,13 @@
"[]",
"Pair"
]
},
{
"Name": "PolicyText",
"Docs": "Text that make up the policy, as retrieved. We didn't store this in the past. If empty, policy can be reconstructed from Policy field. Needed by TLSRPT.",
"Typewords": [
"string"
]
}
]
},
@ -2183,6 +2290,13 @@
"string"
]
},
{
"Name": "HostReport",
"Docs": "Report for host TLSRPT record, as opposed to domain TLSRPT record.",
"Typewords": [
"bool"
]
},
{
"Name": "Report",
"Docs": "",
@ -2290,7 +2404,7 @@
"Name": "policy-type",
"Docs": "",
"Typewords": [
"string"
"PolicyType"
]
},
{
@ -2367,6 +2481,7 @@
"Name": "receiving-mx-helo",
"Docs": "",
"Typewords": [
"nullable",
"string"
]
},
@ -3672,6 +3787,76 @@
]
}
]
},
{
"Name": "TLSResult",
"Docs": "TLSResult is stored in the database to track TLS results per policy domain, day\nand recipient domain. These records will be included in TLS reports.",
"Fields": [
{
"Name": "ID",
"Docs": "",
"Typewords": [
"int64"
]
},
{
"Name": "PolicyDomain",
"Docs": "Domain with TLSRPT DNS record, with addresses that will receive reports. Either a recipient domain (for MTA-STS policies) or an (MX) host (for DANE policies). Unicode.",
"Typewords": [
"string"
]
},
{
"Name": "DayUTC",
"Docs": "DayUTC is of the form yyyymmdd.",
"Typewords": [
"string"
]
},
{
"Name": "RecipientDomain",
"Docs": "Reports are sent per policy domain. When delivering a message to a recipient domain, we can get multiple TLSResults, typically one for MTA-STS, and one or more for DANE (one for each MX target, or actually TLSA base domain). We track recipient domain so we can display successes/failures for delivery of messages to a recipient domain in the admin pages. Unicode.",
"Typewords": [
"string"
]
},
{
"Name": "Created",
"Docs": "",
"Typewords": [
"timestamp"
]
},
{
"Name": "Updated",
"Docs": "",
"Typewords": [
"timestamp"
]
},
{
"Name": "IsHost",
"Docs": "Result is for host (e.g. DANE), not recipient domain (e.g. MTA-STS).",
"Typewords": [
"bool"
]
},
{
"Name": "SendReport",
"Docs": "Whether to send a report. TLS results for delivering messages with TLS reports will be recorded, but will not cause a report to be sent.",
"Typewords": [
"bool"
]
},
{
"Name": "Results",
"Docs": "Results is updated for each TLS attempt.",
"Typewords": [
"[]",
"Result"
]
}
]
}
],
"Ints": [],
@ -3739,6 +3924,27 @@
}
]
},
{
"Name": "PolicyType",
"Docs": "PolicyType indicates the policy success/failure results are for.",
"Values": [
{
"Name": "TLSA",
"Value": "tlsa",
"Docs": "For DANE, against a mail host (not recipient domain)."
},
{
"Name": "STS",
"Value": "sts",
"Docs": "For MTA-STS, against a recipient domain (not a mail host)."
},
{
"Name": "NoPolicyFound",
"Value": "no-policy-found",
"Docs": "Recipient domain did not have MTA-STS policy, or mail host (TSLA base domain)\ndid not have DANE TLSA records."
}
]
},
{
"Name": "ResultType",
"Docs": "ResultType represents a TLS error.",