diff --git a/internal/config/config.go b/internal/config/config.go index 4546e59..76148d1 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -3,6 +3,8 @@ package config import ( "bytes" + "crypto/x509" + "errors" "fmt" "net" "os" @@ -33,6 +35,16 @@ type Config struct { Relay struct { Addr string `yaml:"addr"` // host:port of the outgoing SMTP relay Concurrency int `yaml:"concurrency"` // simultaneous deliveries + // TLS is "none" (default: a local Postfix), "starttls" (required, never silently skipped) + // or "tls" (encrypted from the first byte, port 465). + TLS string `yaml:"tls"` + ServerName string `yaml:"server_name"` // name the certificate must match; the host of addr by default + CAFile string `yaml:"ca_file"` // PEM bundle of the CAs to trust; the system's by default + Helo string `yaml:"helo"` // EHLO name; this machine's host name by default + // Username and the content of PasswordFile are the SMTP AUTH PLAIN credentials. The password + // is never in the config itself. + Username string `yaml:"username"` + PasswordFile string `yaml:"password_file"` } `yaml:"relay"` } @@ -72,7 +84,71 @@ func parseNet(s string) (*net.IPNet, error) { return &net.IPNet{IP: ip, Mask: net.CIDRMask(bits, bits)}, nil } +func isLoopbackHost(host string) bool { + if host == "localhost" { + return true + } + ip := net.ParseIP(host) + return ip != nil && ip.IsLoopback() +} + +// RelayPassword reads the relay password from its file (only the line ending is removed). It is +// empty when no username is configured. +func (c Config) RelayPassword() (string, error) { + if c.Relay.Username == "" { + return "", nil + } + b, err := os.ReadFile(c.Relay.PasswordFile) + if err != nil { + return "", fmt.Errorf("relay.password_file: %w", err) + } + pw := strings.TrimRight(string(b), "\r\n") + if pw == "" { + return "", fmt.Errorf("relay.password_file %s is empty", c.Relay.PasswordFile) + } + return pw, nil +} + +// RelayRootCAs reads relay.ca_file. It returns nil when none is set: the system roots apply. +func (c Config) RelayRootCAs() (*x509.CertPool, error) { + if c.Relay.CAFile == "" { + return nil, nil + } + b, err := os.ReadFile(c.Relay.CAFile) + if err != nil { + return nil, fmt.Errorf("relay.ca_file: %w", err) + } + pool := x509.NewCertPool() + if !pool.AppendCertsFromPEM(b) { + return nil, fmt.Errorf("relay.ca_file %s contains no certificate", c.Relay.CAFile) + } + return pool, nil +} + +func (c Config) validateRelay() error { + r := c.Relay + host, _, err := net.SplitHostPort(r.Addr) + if err != nil { + return fmt.Errorf("relay.addr %q must be host:port", r.Addr) + } + switch r.TLS { + case "", "none", "starttls", "tls": + default: + return fmt.Errorf("relay.tls must be none, starttls or tls, not %q", r.TLS) + } + if (r.Username == "") != (r.PasswordFile == "") { + return errors.New("relay.username and relay.password_file go together") + } + if r.Username != "" && (r.TLS == "" || r.TLS == "none") && !isLoopbackHost(host) { + return fmt.Errorf("relay.username is set but relay.tls is not: the password would cross the network in clear to %s; set relay.tls to starttls or tls", host) + } + return nil +} + func (c Config) validate() error { + if err := c.validateRelay(); err != nil { + return err + } for i, a := range c.LMTP.Allow { if _, err := parseNet(a); err != nil { return fmt.Errorf("lmtp.allow[%d]: %w", i, err) diff --git a/internal/config/config_test.go b/internal/config/config_test.go index 55bf393..6e08035 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -1,11 +1,19 @@ package config import ( + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/x509" + "crypto/x509/pkix" + "encoding/pem" + "math/big" "net" "os" "path/filepath" "strings" "testing" + "time" ) func write(t *testing.T, content string) string { @@ -126,3 +134,115 @@ func TestLoadRejectsABadLMTPAllowEntry(t *testing.T) { } } } + +func TestLoadRelayTLSSettings(t *testing.T) { + c, err := Load(write(t, "relay:\n addr: email-smtp.eu-west-1.amazonaws.com:587\n tls: starttls\n username: AKIAEXAMPLE\n password_file: /run/secrets/relay\n ca_file: /etc/ssl/private-ca.pem\n server_name: smtp.example.com\n helo: lists.example.org\n concurrency: 8\n")) + if err != nil { + t.Fatal(err) + } + r := c.Relay + if r.TLS != "starttls" || r.Username != "AKIAEXAMPLE" || r.PasswordFile != "/run/secrets/relay" || r.CAFile != "/etc/ssl/private-ca.pem" || + r.ServerName != "smtp.example.com" || r.Helo != "lists.example.org" || r.Concurrency != 8 { + t.Fatalf("relay: %+v", r) + } + if d, _ := Load(write(t, "{}\n")); d.Relay.TLS != "" || d.Relay.Username != "" { + t.Fatalf("defaults must keep the plain local relay: %+v", d.Relay) + } +} + +func TestLoadRejectsBadRelaySettings(t *testing.T) { + for name, y := range map[string]string{ + "unknown tls mode": "relay:\n tls: ssl\n", + "username without password file": "relay:\n addr: smtp.example.com:587\n tls: starttls\n username: u\n", + "password file without username": "relay:\n addr: smtp.example.com:587\n tls: starttls\n password_file: /p\n", + "credentials in clear to a host": "relay:\n addr: smtp.example.com:587\n username: u\n password_file: /p\n", + "credentials, tls none, a remote": "relay:\n addr: smtp.example.com:587\n tls: none\n username: u\n password_file: /p\n", + "inline password": "relay:\n addr: smtp.example.com:587\n tls: starttls\n username: u\n password: hunter2\n", + "relay address without a port": "relay:\n addr: smtp.example.com\n", + } { + if _, err := Load(write(t, y)); err == nil { + t.Errorf("%s: want an error", name) + } + } + _, err := Load(write(t, "relay:\n addr: smtp.example.com:587\n username: u\n password_file: /p\n")) + if err == nil || !strings.Contains(err.Error(), "relay.tls") { + t.Fatalf("the error says what to set: %v", err) + } +} + +func TestCredentialsToALoopbackRelayNeedNoTLS(t *testing.T) { + for _, addr := range []string{"127.0.0.1:587", "localhost:587", "[::1]:587"} { + if _, err := Load(write(t, "relay:\n addr: \""+addr+"\"\n username: u\n password_file: /p\n")); err != nil { + t.Errorf("%s: a local relay with SASL is fine in clear: %v", addr, err) + } + } + for _, mode := range []string{"starttls", "tls"} { + if _, err := Load(write(t, "relay:\n addr: smtp.example.com:587\n tls: "+mode+"\n username: u\n password_file: /p\n")); err != nil { + t.Errorf("%s: %v", mode, err) + } + } +} + +func TestRelayPasswordIsReadFromItsFile(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "relay-password") + os.WriteFile(path, []byte(" s3cret with spaces \n"), 0o600) + c, _ := Load(write(t, "relay:\n addr: smtp.example.com:587\n tls: starttls\n username: u\n password_file: "+path+"\n")) + pw, err := c.RelayPassword() + if err != nil || pw != " s3cret with spaces " { + t.Fatalf("only the line ending is removed: %q %v", pw, err) + } + os.WriteFile(path, []byte("with-crlf\r\n"), 0o600) + if pw, _ := c.RelayPassword(); pw != "with-crlf" { + t.Fatalf("%q", pw) + } + os.WriteFile(path, []byte("\n"), 0o600) + if _, err := c.RelayPassword(); err == nil || !strings.Contains(err.Error(), "empty") { + t.Fatalf("an empty password file is an error: %v", err) + } + os.Remove(path) + if _, err := c.RelayPassword(); err == nil { + t.Fatal("a missing password file is an error") + } + if none, _ := Load(write(t, "{}\n")); true { + if pw, err := none.RelayPassword(); err != nil || pw != "" { + t.Fatalf("no username, no password: %q %v", pw, err) + } + } +} + +func TestRelayCAFile(t *testing.T) { + good := filepath.Join(t.TempDir(), "ca.pem") + os.WriteFile(good, testCAPEM(t), 0o600) + c, _ := Load(write(t, "relay:\n ca_file: "+good+"\n")) + pool, err := c.RelayRootCAs() + if err != nil || pool == nil { + t.Fatalf("%v %v", pool, err) + } + bad := filepath.Join(t.TempDir(), "bad.pem") + os.WriteFile(bad, []byte("not a certificate"), 0o600) + c, _ = Load(write(t, "relay:\n ca_file: "+bad+"\n")) + if _, err := c.RelayRootCAs(); err == nil || !strings.Contains(err.Error(), "certificate") { + t.Fatalf("a CA file without a certificate is an error: %v", err) + } + c, _ = Load(write(t, "relay:\n ca_file: /nonexistent.pem\n")) + if _, err := c.RelayRootCAs(); err == nil { + t.Fatal("a missing CA file is an error") + } + if none, _ := Load(write(t, "{}\n")); true { + if pool, err := none.RelayRootCAs(); err != nil || pool != nil { + t.Fatalf("without ca_file the system roots are used: %v %v", pool, err) + } + } +} + +func testCAPEM(t *testing.T) []byte { + t.Helper() + key, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + tmpl := &x509.Certificate{SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "test"}, NotBefore: time.Now(), NotAfter: time.Now().Add(time.Hour), IsCA: true, BasicConstraintsValid: true} + der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key) + if err != nil { + t.Fatal(err) + } + return pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}) +}