Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ Requires Go 1.27 or newer.
| FMSG_RETRY_INTERVAL | 20 | Seconds. Minimum time before retrying delivery to a recipient that previously failed. |
| FMSG_RETRY_MAX_AGE | 86400 | Seconds. Maximum age of a message since creation before giving up on delivery retries (default 1 day). |
| FMSG_POLL_INTERVAL | 10 | Seconds. How often the sender polls the database for pending messages. |
| FMSG_MAX_CONCURRENT_SEND | 1024 | Maximum number of concurrent outbound message deliveries. |
| FMSG_MAX_CONCURRENT_SEND | 1024 | Maximum number of outbound deliveries dispatched at once. Each delivery holds one connection from the sender's database pool (32) for the whole exchange, so at most 32 run concurrently; the rest wait for a connection. |
| FMSG_SKIP_DOMAIN_IP_CHECK | false | Set to "true" to skip verifying this host's external IP is in the fmsg DNS authorised IP set on startup. |
| FMSG_SKIP_AUTHORISED_IPS | false | Set to "true" to skip verifying remote hosts IP is in the fmsg DNS authorised IP set during message exchange, and an indicator datagram's source address. WARNING setting this true effectively disables sender verification. |
| FMSG_CHALLENGE_MODE | HAS_NOT_PARTICIPATED | When to issue an automatic CHALLENGE to the sending host. `HAS_NOT_PARTICIPATED` (default): challenge only when the message has no pid, or no message in the thread is from this host's domain. `ALWAYS`: always challenge. `NEVER`: never challenge. |
Expand Down
107 changes: 86 additions & 21 deletions cmd/fmsgd/dns.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package main

import (
"context"
"fmt"
"io"
"log"
Expand All @@ -14,25 +15,45 @@ import (
"github.com/miekg/dns"
)

const (
// dnsLookupTimeout bounds a single per-nameserver DNSSEC UDP/TCP exchange.
dnsLookupTimeout = 5 * time.Second
// resolverLookupTimeout bounds the full non-DNSSEC net.Resolver lookup so
// Go's stub resolver retains headroom for retries and nameserver failover
// (resolv.conf defaults to 5s per attempt).
resolverLookupTimeout = 20 * time.Second
)

var (
dnsClient = &dns.Client{Timeout: dnsLookupTimeout}
dnsTCPClient = &dns.Client{Net: "tcp", Timeout: dnsLookupTimeout}
lookupIPWithContext = func(ctx context.Context, network, host string) ([]net.IP, error) {
return net.DefaultResolver.LookupIP(ctx, network, host)
}
)

func dnssecRequired() bool {
return os.Getenv("FMSG_REQUIRE_DNSSEC") == "true"
}

func resolverAuthenticatedData(name string, qtype uint16) (bool, error) {
cfg, err := dns.ClientConfigFromFile("/etc/resolv.conf")
if err != nil {
return false, err
}
type dnssecQueryResult struct {
ips []net.IP
ad bool
err error
}

func queryDNSSEC(cfg *dns.ClientConfig, name string, qtype uint16) dnssecQueryResult {
msg := new(dns.Msg)
msg.SetQuestion(dns.Fqdn(name), qtype)
msg.SetEdns0(4096, true)

client := &dns.Client{Timeout: 5 * time.Second}
var lastErr error
for _, server := range cfg.Servers {
addr := net.JoinHostPort(server, cfg.Port)
resp, _, err := client.Exchange(msg, addr)
resp, _, err := dnsClient.Exchange(msg, addr)
if err == nil && resp != nil && resp.Truncated {
resp, _, err = dnsTCPClient.Exchange(msg, addr)
}
if err != nil {
lastErr = err
continue
Expand All @@ -45,37 +66,81 @@ func resolverAuthenticatedData(name string, qtype uint16) (bool, error) {
lastErr = fmt.Errorf("dns rcode %d from %s", resp.Rcode, addr)
continue
}
return resp.AuthenticatedData, nil
var ips []net.IP
for _, rr := range resp.Answer {
switch r := rr.(type) {
case *dns.A:
if qtype == dns.TypeA && r.A != nil {
ips = append(ips, r.A)
}
case *dns.AAAA:
if qtype == dns.TypeAAAA && r.AAAA != nil {
ips = append(ips, r.AAAA)
}
}
}
return dnssecQueryResult{ips: ips, ad: resp.AuthenticatedData}
}

if lastErr == nil {
lastErr = fmt.Errorf("no DNS resolvers configured")
}
return false, lastErr
return dnssecQueryResult{err: lastErr}
}

func validateDNSSECResults(fmsgDomain string, resA, resAAAA dnssecQueryResult) ([]net.IP, error) {
if resA.err != nil && resAAAA.err != nil {
return nil, fmt.Errorf("dnssec validation failed for %s: A=%v AAAA=%v", fmsgDomain, resA.err, resAAAA.err)
}
if resA.err == nil && len(resA.ips) > 0 && !resA.ad {
return nil, fmt.Errorf("dnssec validation failed for %s: A response missing AD bit", fmsgDomain)
}
if resAAAA.err == nil && len(resAAAA.ips) > 0 && !resAAAA.ad {
return nil, fmt.Errorf("dnssec validation failed for %s: AAAA response missing AD bit", fmsgDomain)
}

var verified []net.IP
if resA.err == nil && resA.ad {
verified = append(verified, resA.ips...)
}
if resAAAA.err == nil && resAAAA.ad {
verified = append(verified, resAAAA.ips...)
}
if len(verified) == 0 {
if resA.err != nil {
return nil, fmt.Errorf("dnssec validation failed for %s: A=%v", fmsgDomain, resA.err)
}
if resAAAA.err != nil {
return nil, fmt.Errorf("dnssec validation failed for %s: AAAA=%v", fmsgDomain, resAAAA.err)
}
return nil, fmt.Errorf("no DNSSEC-verified A/AAAA records found for %s", fmsgDomain)
}
return verified, nil
}

// lookupAuthorisedIPs resolves fmsg.<domain> for A and AAAA records
func lookupAuthorisedIPs(domain string) ([]net.IP, error) {
fmsgDomain := "fmsg." + domain
ips, err := net.LookupIP(fmsgDomain)
if dnssecRequired() {
cfg, err := dns.ClientConfigFromFile("/etc/resolv.conf")
if err != nil {
return nil, fmt.Errorf("dnssec validation failed for %s: %w", fmsgDomain, err)
}
resA := queryDNSSEC(cfg, fmsgDomain, dns.TypeA)
resAAAA := queryDNSSEC(cfg, fmsgDomain, dns.TypeAAAA)
return validateDNSSECResults(fmsgDomain, resA, resAAAA)
}

ctx, cancel := context.WithTimeout(context.Background(), resolverLookupTimeout)
defer cancel()
ips, err := lookupIPWithContext(ctx, "ip", fmsgDomain)
if err != nil {
return nil, fmt.Errorf("DNS lookup for %s failed: %w", fmsgDomain, err)
}
if len(ips) == 0 {
return nil, fmt.Errorf("no A/AAAA records found for %s", fmsgDomain)
}

if dnssecRequired() {
adA, errA := resolverAuthenticatedData(fmsgDomain, dns.TypeA)
adAAAA, errAAAA := resolverAuthenticatedData(fmsgDomain, dns.TypeAAAA)
if !adA && !adAAAA {
if errA != nil && errAAAA != nil {
return nil, fmt.Errorf("dnssec validation failed for %s: A=%v AAAA=%v", fmsgDomain, errA, errAAAA)
}
return nil, fmt.Errorf("dnssec validation failed for %s: resolver did not set AD bit", fmsgDomain)
}
}

return ips, nil
}

Expand Down
84 changes: 84 additions & 0 deletions cmd/fmsgd/dns_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
package main

import (
"context"
"errors"
"net"
"testing"
"time"
)

func TestLookupAuthorisedIPsResolverTimeoutAllowsFailover(t *testing.T) {
t.Setenv("FMSG_REQUIRE_DNSSEC", "")

// Per-server DNSSEC clients keep the 5s per-attempt timeout.
if dnsClient.Timeout != dnsLookupTimeout || dnsTCPClient.Timeout != dnsLookupTimeout {
t.Fatalf("DNSSEC client timeouts = (%v, %v), want %v", dnsClient.Timeout, dnsTCPClient.Timeout, dnsLookupTimeout)
}

origLookup := lookupIPWithContext
t.Cleanup(func() {
lookupIPWithContext = origLookup
})

wantIP := net.ParseIP("192.0.2.42")
var attempts int
lookupIPWithContext = func(ctx context.Context, network, host string) ([]net.IP, error) {
if network != "ip" {
t.Errorf("network = %q, want %q", network, "ip")
}
if host != "fmsg.example.com" {
t.Errorf("host = %q, want %q", host, "fmsg.example.com")
}

deadline, ok := ctx.Deadline()
if !ok {
t.Fatal("expected context with deadline for non-DNSSEC lookup")
}
remaining := time.Until(deadline)
if remaining < 15*time.Second {
t.Fatalf("resolver context deadline remaining = %v, want >= 15s to allow nameserver failover", remaining)
}
if remaining > resolverLookupTimeout {
t.Fatalf("resolver context deadline remaining = %v, want <= %v", remaining, resolverLookupTimeout)
}

// Simulate a multi-nameserver resolver: nameserver 1 times out after
// one 5s per-attempt timeout, and nameserver 2 succeeds because the
// overall context still has budget remaining.
nameservers := []func() ([]net.IP, error){
func() ([]net.IP, error) {
remaining -= dnsLookupTimeout
return nil, errors.New("i/o timeout on primary nameserver")
},
func() ([]net.IP, error) {
if remaining <= 0 || ctx.Err() != nil {
return nil, context.DeadlineExceeded
}
return []net.IP{wantIP}, nil
},
}

var lastErr error
for _, queryNS := range nameservers {
attempts++
ips, err := queryNS()
if err == nil {
return ips, nil
}
lastErr = err
}
return nil, lastErr
}

ips, err := lookupAuthorisedIPs("example.com")
if err != nil {
t.Fatalf("lookupAuthorisedIPs failed across nameserver failover: %v", err)
}
if attempts != 2 {
t.Fatalf("nameserver attempts = %d, want 2 (failover)", attempts)
}
if len(ips) != 1 || !ips[0].Equal(wantIP) {
t.Fatalf("lookupAuthorisedIPs = %v, want [%s]", ips, wantIP)
}
}
Loading