mox/mtasts/mtasts_test.go

271 lines
7.2 KiB
Go
Raw Normal View History

2023-01-30 16:27:06 +03:00
package mtasts
import (
"context"
"crypto/ed25519"
cryptorand "crypto/rand"
"crypto/tls"
"crypto/x509"
"errors"
"io"
"log"
"math/big"
"net"
"net/http"
"reflect"
"strings"
"sync"
"testing"
"time"
implement dnssec-awareness throughout code, and dane for incoming/outgoing mail delivery the vendored dns resolver code is a copy of the go stdlib dns resolver, with awareness of the "authentic data" (i.e. dnssec secure) added, as well as support for enhanced dns errors, and looking up tlsa records (for dane). ideally it would be upstreamed, but the chances seem slim. dnssec-awareness is added to all packages, e.g. spf, dkim, dmarc, iprev. their dnssec status is added to the Received message headers for incoming email. but the main reason to add dnssec was for implementing dane. with dane, the verification of tls certificates can be done through certificates/public keys published in dns (in the tlsa records). this only makes sense (is trustworthy) if those dns records can be verified to be authentic. mox now applies dane to delivering messages over smtp. mox already implemented mta-sts for webpki/pkix-verification of certificates against the (large) pool of CA's, and still enforces those policies when present. but it now also checks for dane records, and will verify those if present. if dane and mta-sts are both absent, the regular opportunistic tls with starttls is still done. and the fallback to plaintext is also still done. mox also makes it easy to setup dane for incoming deliveries, so other servers can deliver with dane tls certificate verification. the quickstart now generates private keys that are used when requesting certificates with acme. the private keys are pre-generated because they must be static and known during setup, because their public keys must be published in tlsa records in dns. autocert would generate private keys on its own, so had to be forked to add the option to provide the private key when requesting a new certificate. hopefully upstream will accept the change and we can drop the fork. with this change, using the quickstart to setup a new mox instance, the checks at internet.nl result in a 100% score, provided the domain is dnssec-signed and the network doesn't have any issues.
2023-10-10 13:09:35 +03:00
"github.com/mjl-/adns"
2023-01-30 16:27:06 +03:00
"github.com/mjl-/mox/dns"
"github.com/mjl-/mox/mlog"
2023-01-30 16:27:06 +03:00
)
func TestLookup(t *testing.T) {
mlog.SetConfig(map[string]mlog.Level{"": mlog.LevelDebug})
2023-01-30 16:27:06 +03:00
resolver := dns.MockResolver{
TXT: map[string][]string{
"_mta-sts.a.example.": {"v=STSv1; id=1"},
"_mta-sts.one.example.": {"v=STSv1; id=1", "bogus"},
"_mta-sts.bad.example.": {"v=STSv1; bogus"},
"_mta-sts.multiple.example.": {"v=STSv1; id=1", "v=STSv1; id=2"},
"_mta-sts.c.cnames.example.": {"v=STSv1; id=1"},
"_mta-sts.temperror.example.": {"v=STSv1; id=1"},
"_mta-sts.other.example.": {"bogus", "more"},
},
CNAME: map[string]string{
"_mta-sts.a.cnames.example.": "_mta-sts.b.cnames.example.",
"_mta-sts.b.cnames.example.": "_mta-sts.c.cnames.example.",
"_mta-sts.followtemperror.example.": "_mta-sts.temperror.example.",
2023-01-30 16:27:06 +03:00
},
Fail: []string{
"txt _mta-sts.temperror.example.",
2023-01-30 16:27:06 +03:00
},
}
test := func(host string, expRecord *Record, expErr error) {
2023-01-30 16:27:06 +03:00
t.Helper()
record, _, err := LookupRecord(context.Background(), resolver, dns.Domain{ASCII: host})
2023-01-30 16:27:06 +03:00
if (err == nil) != (expErr == nil) || err != nil && !errors.Is(err, expErr) {
t.Fatalf("lookup: got err %#v, expected %#v", err, expErr)
}
if err != nil {
return
}
if !reflect.DeepEqual(record, expRecord) {
t.Fatalf("lookup: got record %#v, expected %#v", record, expRecord)
2023-01-30 16:27:06 +03:00
}
}
test("absent.example", nil, ErrNoRecord)
test("other.example", nil, ErrNoRecord)
test("a.example", &Record{Version: "STSv1", ID: "1"}, nil)
test("one.example", &Record{Version: "STSv1", ID: "1"}, nil)
test("bad.example", nil, ErrRecordSyntax)
test("multiple.example", nil, ErrMultipleRecords)
test("a.cnames.example", &Record{Version: "STSv1", ID: "1"}, nil)
test("temperror.example", nil, ErrDNS)
test("followtemperror.example", nil, ErrDNS)
2023-01-30 16:27:06 +03:00
}
func TestMatches(t *testing.T) {
p, err := ParsePolicy("version: STSv1\nmode: enforce\nmax_age: 1\nmx: a.example\nmx: *.b.example\n")
if err != nil {
t.Fatalf("parsing policy: %s", err)
}
mustParseDomain := func(s string) dns.Domain {
t.Helper()
d, err := dns.ParseDomain(s)
if err != nil {
t.Fatalf("parsing domain %q: %s", s, err)
}
return d
}
match := func(s string) {
t.Helper()
if !p.Matches(mustParseDomain(s)) {
t.Fatalf("unexpected mismatch for %q", s)
}
}
not := func(s string) {
t.Helper()
if p.Matches(mustParseDomain(s)) {
t.Fatalf("unexpected match for %q", s)
}
}
match("a.example")
match("sub.b.example")
not("b.example")
not("sub.sub.b.example")
not("other")
}
type pipeListener struct {
sync.Mutex
closed bool
C chan net.Conn
}
var _ net.Listener = &pipeListener{}
func newPipeListener() *pipeListener { return &pipeListener{C: make(chan net.Conn)} }
func (l *pipeListener) Dial() (net.Conn, error) {
l.Lock()
defer l.Unlock()
if l.closed {
return nil, errors.New("closed")
}
c, s := net.Pipe()
l.C <- s
return c, nil
}
func (l *pipeListener) Accept() (net.Conn, error) {
conn := <-l.C
if conn == nil {
return nil, io.EOF
}
return conn, nil
}
func (l *pipeListener) Close() error {
l.Lock()
defer l.Unlock()
if !l.closed {
l.closed = true
close(l.C)
}
return nil
}
func (l *pipeListener) Addr() net.Addr { return pipeAddr{} }
type pipeAddr struct{}
func (a pipeAddr) Network() string { return "pipe" }
func (a pipeAddr) String() string { return "pipe" }
func fakeCert(t *testing.T, expired bool) tls.Certificate {
notAfter := time.Now()
if expired {
notAfter = notAfter.Add(-time.Hour)
} else {
notAfter = notAfter.Add(time.Hour)
}
privKey := ed25519.NewKeyFromSeed(make([]byte, ed25519.SeedSize)) // Fake key, don't use this for real!
template := &x509.Certificate{
SerialNumber: big.NewInt(1), // Required field...
DNSNames: []string{"mta-sts.mox.example"},
NotBefore: time.Now().Add(-time.Hour),
NotAfter: notAfter,
}
localCertBuf, err := x509.CreateCertificate(cryptorand.Reader, template, template, privKey.Public(), privKey)
if err != nil {
t.Fatalf("making certificate: %s", err)
}
cert, err := x509.ParseCertificate(localCertBuf)
if err != nil {
t.Fatalf("parsing generated certificate: %s", err)
}
c := tls.Certificate{
Certificate: [][]byte{localCertBuf},
PrivateKey: privKey,
Leaf: cert,
}
return c
}
func TestFetch(t *testing.T) {
certok := fakeCert(t, false)
certbad := fakeCert(t, true)
defer func() {
HTTPClient.Transport = nil
}()
resolver := dns.MockResolver{
TXT: map[string][]string{
"_mta-sts.mox.example.": {"v=STSv1; id=1"},
"_mta-sts.other.example.": {"v=STSv1; id=1"},
},
}
test := func(cert tls.Certificate, domain string, status int, policyText string, expPolicy *Policy, expErr error) {
t.Helper()
pool := x509.NewCertPool()
pool.AddCert(cert.Leaf)
l := newPipeListener()
defer l.Close()
go func() {
mux := &http.ServeMux{}
mux.HandleFunc("/.well-known/mta-sts.txt", func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Location", "/other") // Ignored except for redirect.
w.WriteHeader(status)
w.Write([]byte(policyText))
})
s := &http.Server{
Handler: mux,
TLSConfig: &tls.Config{
Certificates: []tls.Certificate{cert},
},
ErrorLog: log.New(io.Discard, "", 0),
}
s.ServeTLS(l, "", "")
}()
HTTPClient.Transport = &http.Transport{
Dial: func(network, addr string) (net.Conn, error) {
if strings.HasPrefix(addr, "mta-sts.doesnotexist.example") {
implement dnssec-awareness throughout code, and dane for incoming/outgoing mail delivery the vendored dns resolver code is a copy of the go stdlib dns resolver, with awareness of the "authentic data" (i.e. dnssec secure) added, as well as support for enhanced dns errors, and looking up tlsa records (for dane). ideally it would be upstreamed, but the chances seem slim. dnssec-awareness is added to all packages, e.g. spf, dkim, dmarc, iprev. their dnssec status is added to the Received message headers for incoming email. but the main reason to add dnssec was for implementing dane. with dane, the verification of tls certificates can be done through certificates/public keys published in dns (in the tlsa records). this only makes sense (is trustworthy) if those dns records can be verified to be authentic. mox now applies dane to delivering messages over smtp. mox already implemented mta-sts for webpki/pkix-verification of certificates against the (large) pool of CA's, and still enforces those policies when present. but it now also checks for dane records, and will verify those if present. if dane and mta-sts are both absent, the regular opportunistic tls with starttls is still done. and the fallback to plaintext is also still done. mox also makes it easy to setup dane for incoming deliveries, so other servers can deliver with dane tls certificate verification. the quickstart now generates private keys that are used when requesting certificates with acme. the private keys are pre-generated because they must be static and known during setup, because their public keys must be published in tlsa records in dns. autocert would generate private keys on its own, so had to be forked to add the option to provide the private key when requesting a new certificate. hopefully upstream will accept the change and we can drop the fork. with this change, using the quickstart to setup a new mox instance, the checks at internet.nl result in a 100% score, provided the domain is dnssec-signed and the network doesn't have any issues.
2023-10-10 13:09:35 +03:00
return nil, &adns.DNSError{IsNotFound: true}
2023-01-30 16:27:06 +03:00
}
return l.Dial()
},
TLSClientConfig: &tls.Config{
RootCAs: pool,
},
}
p, _, err := FetchPolicy(context.Background(), dns.Domain{ASCII: domain})
if (err == nil) != (expErr == nil) || err != nil && !errors.Is(err, expErr) {
t.Fatalf("policy: got err %#v, expected %#v", err, expErr)
}
if err == nil && !reflect.DeepEqual(p, expPolicy) {
t.Fatalf("policy: got %#v, expected %#v", p, expPolicy)
}
if domain == "doesnotexist.example" {
expErr = ErrNoRecord
}
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.
2023-11-09 19:40:46 +03:00
_, p, _, err = Get(context.Background(), resolver, dns.Domain{ASCII: domain})
2023-01-30 16:27:06 +03:00
if (err == nil) != (expErr == nil) || err != nil && !errors.Is(err, expErr) {
t.Fatalf("get: got err %#v, expected %#v", err, expErr)
}
if err == nil && !reflect.DeepEqual(p, expPolicy) {
t.Fatalf("get: got %#v, expected %#v", p, expPolicy)
}
}
test(certok, "mox.example", 200, "bogus", nil, ErrPolicySyntax)
test(certok, "other.example", 200, "bogus", nil, ErrPolicyFetch)
test(certbad, "mox.example", 200, "bogus", nil, ErrPolicyFetch)
test(certok, "mox.example", 404, "bogus", nil, ErrNoPolicy)
test(certok, "doesnotexist.example", 200, "bogus", nil, ErrNoPolicy)
test(certok, "mox.example", 301, "bogus", nil, ErrPolicyFetch)
test(certok, "mox.example", 500, "bogus", nil, ErrPolicyFetch)
large := make([]byte, 64*1024+2)
test(certok, "mox.example", 200, string(large), nil, ErrPolicySyntax)
validPolicy := "version:STSv1\nmode:none\nmax_age:1"
test(certok, "mox.example", 200, validPolicy, &Policy{Version: "STSv1", Mode: "none", MaxAgeSeconds: 1}, nil)
}