From 58c9615ab4724a004837be1481c3d7371452e7b6 Mon Sep 17 00:00:00 2001 From: Parman Mohammadalizadeh Date: Mon, 16 Nov 2026 18:11:03 +0100 Subject: [PATCH] feat(check/milter): Add TLS support A tls:// endpoint now makes the milter client dial through crypto/tls.Dialer, wrapping the existing net.Dialer so its timeout covers the handshake too. The new tls_client block customises the TLS config the same way it does for check.rspamd, target.smtp and auth.ldap, and inherits the global tls_client. Fixes #905 Signed-off-by: Parman Mohammadalizadeh --- docs/reference/checks/milter.md | 9 +++ internal/check/milter/milter.go | 19 +++++-- internal/check/milter/milter_test.go | 83 +++++++++++++++++++++++++++- 3 files changed, 105 insertions(+), 6 deletions(-) diff --git a/docs/reference/checks/milter.md b/docs/reference/checks/milter.md index 8286a79b1..0d462149f 100644 --- a/docs/reference/checks/milter.md +++ b/docs/reference/checks/milter.md @@ -20,6 +20,7 @@ incomplete implementation. check.milter { endpoint fail_open false + tls_client { ... } } milter @@ -39,6 +40,8 @@ Specifies milter protocol endpoint to use. The endpoit is specified in standard URL-like format: `tcp://127.0.0.1:6669` or `unix:///var/lib/milter/filter.sock` +Use `tls://milter.example.org:6669` to connect to the milter over TLS. + --- ### fail_open _boolean_ @@ -47,3 +50,9 @@ Default: `false` Toggles behavior on milter I/O errors. If false ("fail closed") - message is rejected with temporary error code. If true ("fail open") - check is skipped. +--- + +### tls_client { ... } +Default: not set + +Configure TLS client used for `tls://` endpoints. See [TLS configuration / Client](/reference/tls/#client) for details. diff --git a/internal/check/milter/milter.go b/internal/check/milter/milter.go index 756053622..ba0301a18 100644 --- a/internal/check/milter/milter.go +++ b/internal/check/milter/milter.go @@ -30,6 +30,7 @@ import ( "github.com/emersion/go-milter" "github.com/foxcpp/maddy/framework/buffer" "github.com/foxcpp/maddy/framework/config" + tls2 "github.com/foxcpp/maddy/framework/config/tls" "github.com/foxcpp/maddy/framework/container" "github.com/foxcpp/maddy/framework/exterrors" "github.com/foxcpp/maddy/framework/log" @@ -74,8 +75,13 @@ func (c *Check) Configure(inlineArgs []string, cfg *config.Map) error { return fmt.Errorf("%s: unexpected amount of arguments, want 1 or 0", modName) } + var tlsConfig *tls.Config + cfg.String("endpoint", false, false, c.milterUrl, &c.milterUrl) cfg.Bool("fail_open", false, false, &c.failOpen) + cfg.Custom("tls_client", true, false, func() (interface{}, error) { + return &tls.Config{}, nil + }, tls2.TLSClientBlock, &tlsConfig) if _, err := cfg.Process(); err != nil { return err } @@ -94,14 +100,19 @@ func (c *Check) Configure(inlineArgs []string, cfg *config.Map) error { default: return fmt.Errorf("%s: scheme unsupported: %v", modName, endp.Scheme) } + netDialer := &net.Dialer{ + Timeout: 10 * time.Second, + } + var dialer milter.Dialer = netDialer if endp.IsTLS() { - return fmt.Errorf("%s: tls is not supported", modName) + dialer = &tls.Dialer{ + NetDialer: netDialer, + Config: tlsConfig, + } } c.cl = milter.NewClientWithOptions(endp.Network(), endp.Address(), milter.ClientOptions{ - Dialer: &net.Dialer{ - Timeout: 10 * time.Second, - }, + Dialer: dialer, ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second, ActionMask: milter.OptAddHeader | milter.OptQuarantine, diff --git a/internal/check/milter/milter_test.go b/internal/check/milter/milter_test.go index 8c4df0182..3037b86e1 100644 --- a/internal/check/milter/milter_test.go +++ b/internal/check/milter/milter_test.go @@ -20,7 +20,16 @@ package milter import ( "context" + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/tls" + "crypto/x509" + "encoding/pem" + "math/big" "net" + "os" + "path/filepath" "testing" "time" @@ -41,6 +50,8 @@ func TestAcceptValidEndpoints(t *testing.T) { "unix:///path", "unix://also/path", "unix:///also/path", + "tls://0.0.0.0:10025", + "tls:0.0.0.0:10025", } { c := &Check{milterUrl: endpoint} @@ -54,8 +65,8 @@ func TestAcceptValidEndpoints(t *testing.T) { func TestRejectInvalidEndpoints(t *testing.T) { for _, endpoint := range []string{ - "tls://0.0.0.0:10025", - "tls:0.0.0.0:10025", + "udp://0.0.0.0:10025", + "tcp://0.0.0.0", } { c := &Check{milterUrl: endpoint} err := c.Configure(nil, &config.Map{}) @@ -66,6 +77,74 @@ func TestRejectInvalidEndpoints(t *testing.T) { } } +func selfSignedCert(t *testing.T) (tls.Certificate, []byte) { + t.Helper() + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + t.Fatal(err) + } + tmpl := &x509.Certificate{ + SerialNumber: big.NewInt(1), + NotBefore: time.Now().Add(-time.Hour), + NotAfter: time.Now().Add(time.Hour), + KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign, + ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, + IPAddresses: []net.IP{net.IPv4(127, 0, 0, 1)}, + IsCA: true, + BasicConstraintsValid: true, + } + der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key) + if err != nil { + t.Fatal(err) + } + return tls.Certificate{Certificate: [][]byte{der}, PrivateKey: key}, + pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}) +} + +func TestTLSEndpoint(t *testing.T) { + cert, certPEM := selfSignedCert(t) + caPath := filepath.Join(t.TempDir(), "ca.pem") + if err := os.WriteFile(caPath, certPEM, 0o600); err != nil { + t.Fatal(err) + } + + l, err := tls.Listen("tcp", "127.0.0.1:0", &tls.Config{Certificates: []tls.Certificate{cert}}) + if err != nil { + t.Fatal(err) + } + defer func() { _ = l.Close() }() + + handshake := make(chan error, 1) + go func() { + conn, err := l.Accept() + if err != nil { + handshake <- err + return + } + defer func() { _ = conn.Close() }() + handshake <- conn.(*tls.Conn).Handshake() + }() + + c := &Check{milterUrl: "tls://" + l.Addr().String()} + err = c.Configure(nil, config.NewMap(nil, config.Node{Children: []config.Node{ + {Name: "tls_client", Children: []config.Node{ + {Name: "root_ca", Args: []string{caPath}}, + }}, + }})) + if err != nil { + t.Fatal(err) + } + + // The server hangs up right after the handshake, so negotiation fails. + if session, err := c.cl.Session(); err == nil { + _ = session.Close() + } + + if err := <-handshake; err != nil { + t.Fatalf("TLS handshake with the milter failed: %v", err) + } +} + // unreachableAddr returns a loopback TCP address that is guaranteed to // refuse connections: it binds a listener to get a free port, then closes // it immediately, so dialing it fails fast with ECONNREFUSED instead of