Skip to content
Open
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
9 changes: 9 additions & 0 deletions docs/reference/checks/milter.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ incomplete implementation.
check.milter {
endpoint <endpoint>
fail_open false
tls_client { ... }
}

milter <endpoint>
Expand All @@ -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_
Expand All @@ -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.
19 changes: 15 additions & 4 deletions internal/check/milter/milter.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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
}
Expand All @@ -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,
Expand Down
83 changes: 81 additions & 2 deletions internal/check/milter/milter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"

Expand All @@ -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}

Expand All @@ -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{})
Expand All @@ -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
Expand Down