mirror of
https://github.com/decke/smtprelay.git
synced 2025-12-25 16:02:31 -07:00
Compare commits
1 Commits
v1.10.0
...
add-servic
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
190c615029 |
8
.github/workflows/codeql-analysis.yml
vendored
8
.github/workflows/codeql-analysis.yml
vendored
@@ -25,7 +25,7 @@ jobs:
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v3
|
||||
uses: actions/checkout@v2
|
||||
with:
|
||||
# We must fetch at least the immediate parents so that if this is
|
||||
# a pull request then we can checkout the head.
|
||||
@@ -38,7 +38,7 @@ jobs:
|
||||
|
||||
# Initializes the CodeQL tools for scanning.
|
||||
- name: Initialize CodeQL
|
||||
uses: github/codeql-action/init@v2
|
||||
uses: github/codeql-action/init@v1
|
||||
with:
|
||||
languages: ${{ matrix.language }}
|
||||
# If you wish to specify custom queries, you can do so here or in a config file.
|
||||
@@ -49,7 +49,7 @@ jobs:
|
||||
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
|
||||
# If this step fails, then you should remove it and run the build manually (see below)
|
||||
- name: Autobuild
|
||||
uses: github/codeql-action/autobuild@v2
|
||||
uses: github/codeql-action/autobuild@v1
|
||||
|
||||
# ℹ️ Command-line programs to run using the OS shell.
|
||||
# 📚 https://git.io/JvXDl
|
||||
@@ -63,4 +63,4 @@ jobs:
|
||||
# make release
|
||||
|
||||
- name: Perform CodeQL Analysis
|
||||
uses: github/codeql-action/analyze@v2
|
||||
uses: github/codeql-action/analyze@v1
|
||||
|
||||
20
.github/workflows/go.yml
vendored
20
.github/workflows/go.yml
vendored
@@ -1,18 +1,24 @@
|
||||
name: Go
|
||||
on: [push, pull_request]
|
||||
on: [push]
|
||||
jobs:
|
||||
|
||||
build:
|
||||
name: Build
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/setup-go@v4
|
||||
|
||||
- name: Set up Go 1.15
|
||||
uses: actions/setup-go@v2.1.3
|
||||
with:
|
||||
go-version: 'stable'
|
||||
go-version: 1.15
|
||||
id: go
|
||||
|
||||
- name: Check out code into the Go module directory
|
||||
uses: actions/checkout@v1
|
||||
|
||||
- name: Get dependencies
|
||||
run: |
|
||||
go get -v -t -d ./...
|
||||
|
||||
- name: Build
|
||||
run: go build -v .
|
||||
|
||||
- name: Test
|
||||
run: go test -v .
|
||||
|
||||
8
.github/workflows/release.yaml
vendored
8
.github/workflows/release.yaml
vendored
@@ -11,20 +11,20 @@ jobs:
|
||||
strategy:
|
||||
matrix:
|
||||
goos: [freebsd, linux, windows]
|
||||
goarch: [amd64, arm64]
|
||||
goarch: ["386", amd64]
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/checkout@v2
|
||||
|
||||
- name: Set APP_VERSION env
|
||||
run: echo APP_VERSION=$(echo ${GITHUB_REF} | rev | cut -d'/' -f 1 | rev ) >> ${GITHUB_ENV}
|
||||
- name: Set BUILD_TIME env
|
||||
run: echo BUILD_TIME=$(date) >> ${GITHUB_ENV}
|
||||
|
||||
- uses: wangyoucao577/go-release-action@v1
|
||||
- uses: wangyoucao577/go-release-action@v1.15
|
||||
with:
|
||||
github_token: ${{ secrets.GITHUB_TOKEN }}
|
||||
goos: ${{ matrix.goos }}
|
||||
goarch: ${{ matrix.goarch }}
|
||||
goversion: "1.20"
|
||||
goversion: "https://golang.org/dl/go1.15.8.linux-amd64.tar.gz"
|
||||
extra_files: LICENSE README.md smtprelay.ini
|
||||
ldflags: -s -w -X "main.appVersion=${{ env.APP_VERSION }}" -X "main.buildTime=${{ env.BUILD_TIME }}"
|
||||
|
||||
@@ -16,17 +16,16 @@ configure.
|
||||
|
||||
My use case is simple. I need to send automatically generated mails from
|
||||
cron via msmtp/sSMTP/dma, mails from various services and network printers
|
||||
via a remote SMTP server without giving away my mail credentials to each
|
||||
device which produces mail.
|
||||
to GMail without giving away my GMail credentials to each device which
|
||||
produces mail.
|
||||
|
||||
|
||||
## Main features
|
||||
|
||||
* Simple configuration with ini file .env file or environment variables
|
||||
* Supports SMTPS/TLS (465), STARTTLS (587) and unencrypted SMTP (25)
|
||||
* Checks for sender, receiver, client IP
|
||||
* Authentication support with file (LOGIN, PLAIN)
|
||||
* Enforce encryption for authentication
|
||||
* Forwards all mail to a smarthost (any SMTP server)
|
||||
* Forwards all mail to a smarthost (GMail, MailGun or any other SMTP server)
|
||||
* Small codebase
|
||||
* IPv6 support
|
||||
|
||||
247
config.go
247
config.go
@@ -1,17 +1,12 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"os"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
"net/smtp"
|
||||
|
||||
"github.com/peterbourgon/ff/v3"
|
||||
"github.com/vharitonsky/iniflags"
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
@@ -21,49 +16,31 @@ var (
|
||||
)
|
||||
|
||||
var (
|
||||
flagset = flag.NewFlagSet("smtprelay", flag.ContinueOnError)
|
||||
|
||||
// config flags
|
||||
logFile = flagset.String("logfile", "", "Path to logfile")
|
||||
logFormat = flagset.String("log_format", "default", "Log output format")
|
||||
logLevel = flagset.String("log_level", "info", "Minimum log level to output")
|
||||
hostName = flagset.String("hostname", "localhost.localdomain", "Server hostname")
|
||||
welcomeMsg = flagset.String("welcome_msg", "", "Welcome message for SMTP session")
|
||||
listenStr = flagset.String("listen", "127.0.0.1:25 [::1]:25", "Address and port to listen for incoming SMTP")
|
||||
localCert = flagset.String("local_cert", "", "SSL certificate for STARTTLS/TLS")
|
||||
localKey = flagset.String("local_key", "", "SSL private key for STARTTLS/TLS")
|
||||
localForceTLS = flagset.Bool("local_forcetls", false, "Force STARTTLS (needs local_cert and local_key)")
|
||||
readTimeoutStr = flagset.String("read_timeout", "60s", "Socket timeout for read operations")
|
||||
writeTimeoutStr = flagset.String("write_timeout", "60s", "Socket timeout for write operations")
|
||||
dataTimeoutStr = flagset.String("data_timeout", "5m", "Socket timeout for DATA command")
|
||||
maxConnections = flagset.Int("max_connections", 100, "Max concurrent connections, use -1 to disable")
|
||||
maxMessageSize = flagset.Int("max_message_size", 10240000, "Max message size in bytes")
|
||||
maxRecipients = flagset.Int("max_recipients", 100, "Max RCPT TO calls for each envelope")
|
||||
allowedNetsStr = flagset.String("allowed_nets", "127.0.0.0/8 ::1/128", "Networks allowed to send mails")
|
||||
allowedSenderStr = flagset.String("allowed_sender", "", "Regular expression for valid FROM EMail addresses")
|
||||
allowedRecipStr = flagset.String("allowed_recipients", "", "Regular expression for valid TO EMail addresses")
|
||||
allowedUsers = flagset.String("allowed_users", "", "Path to file with valid users/passwords")
|
||||
command = flagset.String("command", "", "Path to pipe command")
|
||||
remotesStr = flagset.String("remotes", "", "Outgoing SMTP servers")
|
||||
|
||||
// additional flags
|
||||
_ = flagset.String("config", "", "Path to config file (ini format)")
|
||||
versionInfo = flagset.Bool("version", false, "Show version information")
|
||||
|
||||
// internal
|
||||
listenAddrs = []protoAddr{}
|
||||
readTimeout time.Duration
|
||||
writeTimeout time.Duration
|
||||
dataTimeout time.Duration
|
||||
logFile = flag.String("logfile", "", "Path to logfile")
|
||||
logFormat = flag.String("log_format", "default", "Log output format")
|
||||
logLevel = flag.String("log_level", "info", "Minimum log level to output")
|
||||
hostName = flag.String("hostname", "localhost.localdomain", "Server hostname")
|
||||
welcomeMsg = flag.String("welcome_msg", "", "Welcome message for SMTP session")
|
||||
listen = flag.String("listen", "127.0.0.1:25 [::1]:25", "Address and port to listen for incoming SMTP")
|
||||
localCert = flag.String("local_cert", "", "SSL certificate for STARTTLS/TLS")
|
||||
localKey = flag.String("local_key", "", "SSL private key for STARTTLS/TLS")
|
||||
localForceTLS = flag.Bool("local_forcetls", false, "Force STARTTLS (needs local_cert and local_key)")
|
||||
allowedNetsStr = flag.String("allowed_nets", "127.0.0.0/8 ::1/128", "Networks allowed to send mails")
|
||||
allowedNets = []*net.IPNet{}
|
||||
allowedSenderStr = flag.String("allowed_sender", "", "Regular expression for valid FROM EMail addresses")
|
||||
allowedSender *regexp.Regexp
|
||||
allowedRecipStr = flag.String("allowed_recipients", "", "Regular expression for valid TO EMail addresses")
|
||||
allowedRecipients *regexp.Regexp
|
||||
remotes = []*Remote{}
|
||||
allowedUsers = flag.String("allowed_users", "", "Path to file with valid users/passwords")
|
||||
remoteHost = flag.String("remote_host", "", "Outgoing SMTP server")
|
||||
remoteUser = flag.String("remote_user", "", "Username for authentication on outgoing SMTP server")
|
||||
remotePass = flag.String("remote_pass", "", "Password for authentication on outgoing SMTP server")
|
||||
remoteAuthStr = flag.String("remote_auth", "none", "Auth method on outgoing SMTP server (none, plain, login)")
|
||||
remoteAuth smtp.Auth
|
||||
remoteSender = flag.String("remote_sender", "", "Sender e-mail address on outgoing SMTP server")
|
||||
versionInfo = flag.Bool("version", false, "Show version information")
|
||||
)
|
||||
|
||||
func localAuthRequired() bool {
|
||||
return *allowedUsers != ""
|
||||
}
|
||||
|
||||
func setupAllowedNetworks() {
|
||||
for _, netstr := range splitstr(*allowedNetsStr, ' ') {
|
||||
@@ -78,7 +55,7 @@ func setupAllowedNetworks() {
|
||||
// meaning the address refers to a host and not a network.
|
||||
if !allowedNet.IP.Equal(baseIP) {
|
||||
log.WithFields(logrus.Fields{
|
||||
"given_net": netstr,
|
||||
"given_net": netstr,
|
||||
"proper_net": allowedNet,
|
||||
}).Fatal("Invalid network in allowed_nets (host bits set)")
|
||||
}
|
||||
@@ -90,7 +67,7 @@ func setupAllowedNetworks() {
|
||||
func setupAllowedPatterns() {
|
||||
var err error
|
||||
|
||||
if *allowedSenderStr != "" {
|
||||
if (*allowedSenderStr != "") {
|
||||
allowedSender, err = regexp.Compile(*allowedSenderStr)
|
||||
if err != nil {
|
||||
log.WithField("allowed_sender", *allowedSenderStr).
|
||||
@@ -99,7 +76,7 @@ func setupAllowedPatterns() {
|
||||
}
|
||||
}
|
||||
|
||||
if *allowedRecipStr != "" {
|
||||
if (*allowedRecipStr != "") {
|
||||
allowedRecipients, err = regexp.Compile(*allowedRecipStr)
|
||||
if err != nil {
|
||||
log.WithField("allowed_recipients", *allowedRecipStr).
|
||||
@@ -109,167 +86,61 @@ func setupAllowedPatterns() {
|
||||
}
|
||||
}
|
||||
|
||||
func setupRemotes() {
|
||||
logger := log.WithField("remotes", *remotesStr)
|
||||
|
||||
if *remotesStr != "" {
|
||||
for _, remoteURL := range strings.Split(*remotesStr, " ") {
|
||||
r, err := ParseRemote(remoteURL)
|
||||
if err != nil {
|
||||
logger.Fatal(fmt.Sprintf("error parsing url: '%s': %v", remoteURL, err))
|
||||
}
|
||||
func setupRemoteAuth() {
|
||||
logger := log.WithField("remote_auth", *remoteAuthStr)
|
||||
|
||||
remotes = append(remotes, r)
|
||||
// Remote auth disabled?
|
||||
if *remoteAuthStr == "" || *remoteAuthStr == "none" {
|
||||
if *remoteUser != "" {
|
||||
logger.Fatal("remote_user given but not used")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type protoAddr struct {
|
||||
protocol string
|
||||
address string
|
||||
}
|
||||
|
||||
func splitProto(s string) protoAddr {
|
||||
idx := strings.Index(s, "://")
|
||||
if idx == -1 {
|
||||
return protoAddr{
|
||||
address: s,
|
||||
}
|
||||
}
|
||||
return protoAddr{
|
||||
protocol: s[0:idx],
|
||||
address: s[idx+3:],
|
||||
}
|
||||
}
|
||||
|
||||
func setupListeners() {
|
||||
for _, listenAddr := range strings.Split(*listenStr, " ") {
|
||||
pa := splitProto(listenAddr)
|
||||
|
||||
if localAuthRequired() && pa.protocol == "" {
|
||||
log.WithField("address", pa.address).
|
||||
Fatal("Local authentication (via allowed_users file) " +
|
||||
"not allowed with non-TLS listener")
|
||||
if *remotePass != "" {
|
||||
logger.Fatal("remote_pass given but not used")
|
||||
}
|
||||
|
||||
listenAddrs = append(listenAddrs, pa)
|
||||
// No auth; use empty default
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func setupTimeouts() {
|
||||
var err error
|
||||
// We need a username, password, and remote host
|
||||
if *remoteUser == "" {
|
||||
logger.Fatal("remote_user required but empty")
|
||||
}
|
||||
if *remotePass == "" {
|
||||
logger.Fatal("remote_pass required but empty")
|
||||
}
|
||||
if *remoteHost == "" {
|
||||
logger.Fatal("remote_auth without remote_host is pointless")
|
||||
}
|
||||
|
||||
readTimeout, err = time.ParseDuration(*readTimeoutStr)
|
||||
host, _, err := net.SplitHostPort(*remoteHost)
|
||||
if err != nil {
|
||||
log.WithField("read_timeout", *readTimeoutStr).
|
||||
WithError(err).
|
||||
Fatal("read_timeout duration string invalid")
|
||||
}
|
||||
if readTimeout.Seconds() < 1 {
|
||||
log.WithField("read_timeout", *readTimeoutStr).
|
||||
Fatal("read_timeout less than one second")
|
||||
logger.WithField("remote_host", *remoteHost).
|
||||
Fatal("Invalid remote_host")
|
||||
}
|
||||
|
||||
writeTimeout, err = time.ParseDuration(*writeTimeoutStr)
|
||||
if err != nil {
|
||||
log.WithField("write_timeout", *writeTimeoutStr).
|
||||
WithError(err).
|
||||
Fatal("write_timeout duration string invalid")
|
||||
}
|
||||
if writeTimeout.Seconds() < 1 {
|
||||
log.WithField("write_timeout", *writeTimeoutStr).
|
||||
Fatal("write_timeout less than one second")
|
||||
}
|
||||
|
||||
dataTimeout, err = time.ParseDuration(*dataTimeoutStr)
|
||||
if err != nil {
|
||||
log.WithField("data_timeout", *dataTimeoutStr).
|
||||
WithError(err).
|
||||
Fatal("data_timeout duration string invalid")
|
||||
}
|
||||
if dataTimeout.Seconds() < 1 {
|
||||
log.WithField("data_timeout", *dataTimeoutStr).
|
||||
Fatal("data_timeout less than one second")
|
||||
switch *remoteAuthStr {
|
||||
case "plain":
|
||||
remoteAuth = smtp.PlainAuth("", *remoteUser, *remotePass, host)
|
||||
case "login":
|
||||
remoteAuth = LoginAuth(*remoteUser, *remotePass)
|
||||
default:
|
||||
logger.Fatal("Invalid remote_auth type")
|
||||
}
|
||||
}
|
||||
|
||||
func ConfigLoad() {
|
||||
// use .env file if it exists
|
||||
if _, err := os.Stat(".env"); err == nil {
|
||||
if err := ff.Parse(flagset, os.Args[1:],
|
||||
ff.WithEnvVarPrefix("smtprelay"),
|
||||
ff.WithConfigFile(".env"),
|
||||
ff.WithConfigFileParser(ff.EnvParser),
|
||||
); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "error: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
} else {
|
||||
// use env variables and smtprelay.ini file
|
||||
if err := ff.Parse(flagset, os.Args[1:],
|
||||
ff.WithEnvVarPrefix("smtprelay"),
|
||||
ff.WithConfigFileFlag("config"),
|
||||
ff.WithConfigFileParser(IniParser),
|
||||
); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "error: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
iniflags.Parse()
|
||||
|
||||
// Set up logging as soon as possible
|
||||
setupLogger()
|
||||
|
||||
if *versionInfo {
|
||||
fmt.Printf("smtprelay/%s (%s)\n", appVersion, buildTime)
|
||||
os.Exit(0)
|
||||
}
|
||||
|
||||
if *remotesStr == "" && *command == "" {
|
||||
log.Warn("no remotes or command set; mail will not be forwarded!")
|
||||
if (*remoteHost == "") {
|
||||
log.Warn("remote_host not set; mail will not be forwarded!")
|
||||
}
|
||||
|
||||
setupAllowedNetworks()
|
||||
setupAllowedPatterns()
|
||||
setupRemotes()
|
||||
setupListeners()
|
||||
setupTimeouts()
|
||||
}
|
||||
|
||||
// IniParser is a parser for config files in classic key/value style format. Each
|
||||
// line is tokenized as a single key/value pair. The first "=" delimited
|
||||
// token in the line is interpreted as the flag name, and all remaining tokens
|
||||
// are interpreted as the value. Any leading hyphens on the flag name are
|
||||
// ignored.
|
||||
func IniParser(r io.Reader, set func(name, value string) error) error {
|
||||
s := bufio.NewScanner(r)
|
||||
for s.Scan() {
|
||||
line := strings.TrimSpace(s.Text())
|
||||
if line == "" {
|
||||
continue // skip empties
|
||||
}
|
||||
|
||||
if line[0] == '#' || line[0] == ';' {
|
||||
continue // skip comments
|
||||
}
|
||||
|
||||
var (
|
||||
name string
|
||||
value string
|
||||
index = strings.IndexRune(line, '=')
|
||||
)
|
||||
if index < 0 {
|
||||
name, value = line, "true" // boolean option
|
||||
} else {
|
||||
name, value = strings.TrimSpace(line[:index]), strings.Trim(strings.TrimSpace(line[index+1:]), "\"")
|
||||
}
|
||||
|
||||
if i := strings.Index(value, " #"); i >= 0 {
|
||||
value = strings.TrimSpace(value[:i])
|
||||
}
|
||||
|
||||
if err := set(name, value); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
setupRemoteAuth()
|
||||
}
|
||||
|
||||
@@ -1,44 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestSplitProto(t *testing.T) {
|
||||
var tests = []struct {
|
||||
input string
|
||||
proto string
|
||||
addr string
|
||||
}{
|
||||
{
|
||||
input: "localhost",
|
||||
proto: "",
|
||||
addr: "localhost",
|
||||
},
|
||||
{
|
||||
input: "tls://my.local.domain",
|
||||
proto: "tls",
|
||||
addr: "my.local.domain",
|
||||
},
|
||||
{
|
||||
input: "starttls://my.local.domain",
|
||||
proto: "starttls",
|
||||
addr: "my.local.domain",
|
||||
},
|
||||
}
|
||||
|
||||
for i, test := range tests {
|
||||
testName := test.input
|
||||
t.Run(testName, func(t *testing.T) {
|
||||
pa := splitProto(test.input)
|
||||
if pa.protocol != test.proto {
|
||||
t.Errorf("Testcase %d: Incorrect proto: expected %v, got %v",
|
||||
i, test.proto, pa.protocol)
|
||||
}
|
||||
if pa.address != test.addr {
|
||||
t.Errorf("Testcase %d: Incorrect addr: expected %v, got %v",
|
||||
i, test.addr, pa.address)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
22
go.mod
22
go.mod
@@ -1,21 +1,11 @@
|
||||
module github.com/decke/smtprelay
|
||||
|
||||
require (
|
||||
github.com/chrj/smtpd v0.3.1
|
||||
github.com/google/uuid v1.3.0
|
||||
github.com/peterbourgon/ff/v3 v3.3.2
|
||||
github.com/sirupsen/logrus v1.9.3
|
||||
github.com/stretchr/testify v1.8.4
|
||||
golang.org/x/crypto v0.10.0
|
||||
github.com/chrj/smtpd v0.3.0
|
||||
github.com/google/uuid v1.2.0
|
||||
github.com/sirupsen/logrus v1.8.1
|
||||
github.com/vharitonsky/iniflags v0.0.0-20180513140207-a33cd0b5f3de
|
||||
golang.org/x/crypto v0.0.0-20201221181555-eec23a3978ad
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/davecgh/go-spew v1.1.1 // indirect
|
||||
github.com/kr/pretty v0.3.1 // indirect
|
||||
github.com/pmezard/go-difflib v1.0.0 // indirect
|
||||
golang.org/x/sys v0.9.0 // indirect
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
)
|
||||
|
||||
go 1.20
|
||||
go 1.13
|
||||
|
||||
55
go.sum
55
go.sum
@@ -1,39 +1,24 @@
|
||||
github.com/chrj/smtpd v0.3.1 h1:kogHFkbFdKaoH3bgZkqNC9uVtKYOFfM3uV3rroBdooE=
|
||||
github.com/chrj/smtpd v0.3.1/go.mod h1:JtABvV/LzvLmEIzy0NyDnrfMGOMd8wy5frAokwf6J9Q=
|
||||
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/chrj/smtpd v0.3.0 h1:cw1LSHDOz7N3XbkcZSF/bue9dh7ATKk5ZksfBztV6b0=
|
||||
github.com/chrj/smtpd v0.3.0/go.mod h1:1hmG9KbrE10JG1SmvG79Krh4F6713oUrw2+gRp1oSYk=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I=
|
||||
github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=
|
||||
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
||||
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
|
||||
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
|
||||
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
|
||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||
github.com/peterbourgon/ff/v3 v3.3.2 h1:2J07/5/36kd9HYVt42Zve0xCeQ+LLRIvoKrt6sAZXJ4=
|
||||
github.com/peterbourgon/ff/v3 v3.3.2/go.mod h1:zjJVUhx+twciwfDl0zBcFzl4dW8axCRyXE/eKY9RztQ=
|
||||
github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA=
|
||||
github.com/eaigner/dkim v0.0.0-20150301120808-6fe4a7ee9cfb/go.mod h1:FSCIHbrqk7D01Mj8y/jW+NS1uoCerr+ad+IckTHTFf4=
|
||||
github.com/google/uuid v1.2.0 h1:qJYtXnJRWmpe7m/3XlyhrsLrEURqHRM2kxzoxXqyUDs=
|
||||
github.com/google/uuid v1.2.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8=
|
||||
github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=
|
||||
github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
|
||||
github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
|
||||
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
|
||||
golang.org/x/crypto v0.10.0 h1:LKqV2xt9+kDzSTfOhx4FrkEBcMrAgHSYgzywV9zcGmM=
|
||||
golang.org/x/crypto v0.10.0/go.mod h1:o4eNf7Ede1fv+hwOwZsTHl9EsPFO6q6ZvYR8vYfY45I=
|
||||
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.9.0 h1:KS/R3tvhPqvJvwcKfnBHJwwthS11LRhmM5D59eEXa0s=
|
||||
golang.org/x/sys v0.9.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
github.com/sirupsen/logrus v1.8.1 h1:dJKuHgqk1NNQlqoA6BTlM1Wf9DOH3NBjQyu0h9+AZZE=
|
||||
github.com/sirupsen/logrus v1.8.1/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0=
|
||||
github.com/stretchr/testify v1.2.2 h1:bSDNvY7ZPG5RlJ8otE/7V6gMiyenm9RtJ7IUVIAoJ1w=
|
||||
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
|
||||
github.com/vharitonsky/iniflags v0.0.0-20180513140207-a33cd0b5f3de h1:fkw+7JkxF3U1GzQoX9h69Wvtvxajo5Rbzy6+YMMzPIg=
|
||||
github.com/vharitonsky/iniflags v0.0.0-20180513140207-a33cd0b5f3de/go.mod h1:irMhzlTz8+fVFj6CH2AN2i+WI5S6wWFtK3MBCIxIpyI=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20201221181555-eec23a3978ad h1:DN0cp81fZ3njFcrLCytUHRSUkqBjfTo4Tx9RJTWs0EY=
|
||||
golang.org/x/crypto v0.0.0-20201221181555-eec23a3978ad/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I=
|
||||
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20191026070338-33540a1f6037 h1:YyJpGZS1sBuBCzLAR1VEpK193GlqGZbnPFnPV/5Rsb4=
|
||||
golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
|
||||
@@ -16,7 +16,7 @@ func setupLogger() {
|
||||
log = logrus.New()
|
||||
|
||||
// Handle logfile
|
||||
if *logFile == "" {
|
||||
if (*logFile == "") {
|
||||
log.SetOutput(os.Stderr)
|
||||
} else {
|
||||
writer, err := os.OpenFile(*logFile, os.O_CREATE|os.O_RDWR|os.O_APPEND, 0600)
|
||||
|
||||
161
main.go
161
main.go
@@ -1,13 +1,11 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/tls"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/textproto"
|
||||
"os"
|
||||
"os/exec"
|
||||
"os/signal"
|
||||
"strings"
|
||||
"syscall"
|
||||
@@ -83,12 +81,12 @@ func addrAllowed(addr string, allowedAddrs []string) bool {
|
||||
|
||||
func senderChecker(peer smtpd.Peer, addr string) error {
|
||||
// check sender address from auth file if user is authenticated
|
||||
if localAuthRequired() && peer.Username != "" {
|
||||
if *allowedUsers != "" && peer.Username != "" {
|
||||
user, err := AuthFetch(peer.Username)
|
||||
if err != nil {
|
||||
// Shouldn't happen: authChecker already validated username+password
|
||||
log.WithFields(logrus.Fields{
|
||||
"peer": peer.Addr,
|
||||
"peer": peer.Addr,
|
||||
"username": peer.Username,
|
||||
}).WithError(err).Warn("could not fetch auth user")
|
||||
return smtpd.Error{Code: 451, Message: "Bad sender address"}
|
||||
@@ -96,8 +94,8 @@ func senderChecker(peer smtpd.Peer, addr string) error {
|
||||
|
||||
if !addrAllowed(addr, user.allowedAddresses) {
|
||||
log.WithFields(logrus.Fields{
|
||||
"peer": peer.Addr,
|
||||
"username": peer.Username,
|
||||
"peer": peer.Addr,
|
||||
"username": peer.Username,
|
||||
"sender_address": addr,
|
||||
}).Warn("sender address not allowed for authenticated user")
|
||||
return smtpd.Error{Code: 451, Message: "Bad sender address"}
|
||||
@@ -116,7 +114,7 @@ func senderChecker(peer smtpd.Peer, addr string) error {
|
||||
|
||||
log.WithFields(logrus.Fields{
|
||||
"sender_address": addr,
|
||||
"peer": peer.Addr,
|
||||
"peer": peer.Addr,
|
||||
}).Warn("sender address not allowed by allowed_sender pattern")
|
||||
return smtpd.Error{Code: 451, Message: "Bad sender address"}
|
||||
}
|
||||
@@ -133,7 +131,7 @@ func recipientChecker(peer smtpd.Peer, addr string) error {
|
||||
}
|
||||
|
||||
log.WithFields(logrus.Fields{
|
||||
"peer": peer.Addr,
|
||||
"peer": peer.Addr,
|
||||
"recipient_address": addr,
|
||||
}).Warn("recipient address not allowed by allowed_recipients pattern")
|
||||
return smtpd.Error{Code: 451, Message: "Bad recipient address"}
|
||||
@@ -143,7 +141,7 @@ func authChecker(peer smtpd.Peer, username string, password string) error {
|
||||
err := AuthCheckPassword(username, password)
|
||||
if err != nil {
|
||||
log.WithFields(logrus.Fields{
|
||||
"peer": peer.Addr,
|
||||
"peer": peer.Addr,
|
||||
"username": username,
|
||||
}).WithError(err).Warn("auth error")
|
||||
return smtpd.Error{Code: 535, Message: "Authentication credentials invalid"}
|
||||
@@ -159,81 +157,59 @@ func mailHandler(peer smtpd.Peer, env smtpd.Envelope) error {
|
||||
|
||||
logger := log.WithFields(logrus.Fields{
|
||||
"from": env.Sender,
|
||||
"to": env.Recipients,
|
||||
"to": env.Recipients,
|
||||
"peer": peerIP,
|
||||
"host": *remoteHost,
|
||||
"uuid": generateUUID(),
|
||||
})
|
||||
|
||||
if *remotesStr == "" && *command == "" {
|
||||
logger.Warning("no remote_host or command set; discarding mail")
|
||||
if (*remoteHost == "") {
|
||||
logger.Warning("remote_host not set; discarding mail")
|
||||
return nil
|
||||
}
|
||||
|
||||
logger.Info("delivering mail from peer using smarthost")
|
||||
|
||||
env.AddReceivedLine(peer)
|
||||
|
||||
if *command != "" {
|
||||
cmdLogger := logger.WithField("command", *command)
|
||||
var sender string
|
||||
|
||||
var stdout bytes.Buffer
|
||||
var stderr bytes.Buffer
|
||||
|
||||
environ := os.Environ()
|
||||
environ = append(environ, fmt.Sprintf("%s=%s", "SMTPRELAY_FROM", env.Sender))
|
||||
environ = append(environ, fmt.Sprintf("%s=%s", "SMTPRELAY_TO", env.Recipients))
|
||||
environ = append(environ, fmt.Sprintf("%s=%s", "SMTPRELAY_PEER", peerIP))
|
||||
|
||||
cmd := exec.Cmd{
|
||||
Env: environ,
|
||||
Path: *command,
|
||||
}
|
||||
|
||||
cmd.Stdin = bytes.NewReader(env.Data)
|
||||
cmd.Stdout = &stdout
|
||||
cmd.Stderr = &stderr
|
||||
|
||||
err := cmd.Run()
|
||||
if err != nil {
|
||||
cmdLogger.WithError(err).Error(stderr.String())
|
||||
return smtpd.Error{Code: 554, Message: "External command failed"}
|
||||
}
|
||||
|
||||
cmdLogger.Info("pipe command successful: " + stdout.String())
|
||||
if *remoteSender == "" {
|
||||
sender = env.Sender
|
||||
} else {
|
||||
sender = *remoteSender
|
||||
}
|
||||
|
||||
for _, remote := range remotes {
|
||||
logger = logger.WithField("host", remote.Addr)
|
||||
logger.Info("delivering mail from peer using smarthost")
|
||||
err := SendMail(
|
||||
*remoteHost,
|
||||
remoteAuth,
|
||||
sender,
|
||||
env.Recipients,
|
||||
env.Data,
|
||||
)
|
||||
if err != nil {
|
||||
var smtpError smtpd.Error
|
||||
|
||||
err := SendMail(
|
||||
remote,
|
||||
env.Sender,
|
||||
env.Recipients,
|
||||
env.Data,
|
||||
)
|
||||
if err != nil {
|
||||
var smtpError smtpd.Error
|
||||
switch err.(type) {
|
||||
case *textproto.Error:
|
||||
err := err.(*textproto.Error)
|
||||
smtpError = smtpd.Error{Code: err.Code, Message: err.Msg}
|
||||
|
||||
switch err := err.(type) {
|
||||
case *textproto.Error:
|
||||
smtpError = smtpd.Error{Code: err.Code, Message: err.Msg}
|
||||
logger.WithFields(logrus.Fields{
|
||||
"err_code": err.Code,
|
||||
"err_msg": err.Msg,
|
||||
}).Error("delivery failed")
|
||||
default:
|
||||
smtpError = smtpd.Error{Code: 554, Message: "Forwarding failed"}
|
||||
|
||||
logger.WithFields(logrus.Fields{
|
||||
"err_code": err.Code,
|
||||
"err_msg": err.Msg,
|
||||
}).Error("delivery failed")
|
||||
default:
|
||||
smtpError = smtpd.Error{Code: 554, Message: "Forwarding failed"}
|
||||
|
||||
logger.WithError(err).
|
||||
Error("delivery failed")
|
||||
}
|
||||
|
||||
return smtpError
|
||||
logger.WithError(err).
|
||||
Error("delivery failed")
|
||||
}
|
||||
|
||||
logger.Debug("delivery successful")
|
||||
return smtpError
|
||||
}
|
||||
|
||||
logger.Debug("delivery successful")
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -270,7 +246,7 @@ func getTLSConfig() *tls.Config {
|
||||
if *localCert == "" || *localKey == "" {
|
||||
log.WithFields(logrus.Fields{
|
||||
"cert_file": *localCert,
|
||||
"key_file": *localKey,
|
||||
"key_file": *localKey,
|
||||
}).Fatal("TLS certificate/key file not defined in config")
|
||||
}
|
||||
|
||||
@@ -291,11 +267,16 @@ func getTLSConfig() *tls.Config {
|
||||
func main() {
|
||||
ConfigLoad()
|
||||
|
||||
if *versionInfo {
|
||||
fmt.Printf("smtprelay/%s (%s)\n", appVersion, buildTime)
|
||||
os.Exit(0)
|
||||
}
|
||||
|
||||
log.WithField("version", appVersion).
|
||||
Debug("starting smtprelay")
|
||||
|
||||
// Load allowed users file
|
||||
if localAuthRequired() {
|
||||
if *allowedUsers != "" {
|
||||
err := AuthLoadFile(*allowedUsers)
|
||||
if err != nil {
|
||||
log.WithField("file", *allowedUsers).
|
||||
@@ -307,56 +288,54 @@ func main() {
|
||||
var servers []*smtpd.Server
|
||||
|
||||
// Create a server for each desired listen address
|
||||
for _, listen := range listenAddrs {
|
||||
logger := log.WithField("address", listen.address)
|
||||
|
||||
for _, listenAddr := range strings.Split(*listen, " ") {
|
||||
server := &smtpd.Server{
|
||||
Hostname: *hostName,
|
||||
WelcomeMessage: *welcomeMsg,
|
||||
ReadTimeout: readTimeout,
|
||||
WriteTimeout: writeTimeout,
|
||||
DataTimeout: dataTimeout,
|
||||
MaxConnections: *maxConnections,
|
||||
MaxMessageSize: *maxMessageSize,
|
||||
MaxRecipients: *maxRecipients,
|
||||
ConnectionChecker: connectionChecker,
|
||||
SenderChecker: senderChecker,
|
||||
RecipientChecker: recipientChecker,
|
||||
Handler: mailHandler,
|
||||
}
|
||||
|
||||
if localAuthRequired() {
|
||||
if *allowedUsers != "" {
|
||||
server.Authenticator = authChecker
|
||||
}
|
||||
|
||||
var lsnr net.Listener
|
||||
var err error
|
||||
|
||||
switch listen.protocol {
|
||||
case "":
|
||||
logger.Info("listening on address")
|
||||
lsnr, err = net.Listen("tcp", listen.address)
|
||||
if strings.Index(listenAddr, "://") == -1 {
|
||||
log.WithField("address", listenAddr).
|
||||
Info("listening on address")
|
||||
|
||||
lsnr, err = net.Listen("tcp", listenAddr)
|
||||
} else if strings.HasPrefix(listenAddr, "starttls://") {
|
||||
listenAddr = strings.TrimPrefix(listenAddr, "starttls://")
|
||||
|
||||
case "starttls":
|
||||
server.TLSConfig = getTLSConfig()
|
||||
server.ForceTLS = *localForceTLS
|
||||
|
||||
logger.Info("listening on address (STARTTLS)")
|
||||
lsnr, err = net.Listen("tcp", listen.address)
|
||||
log.WithField("address", listenAddr).
|
||||
Info("listening on address (STARTTLS)")
|
||||
lsnr, err = net.Listen("tcp", listenAddr)
|
||||
} else if strings.HasPrefix(listenAddr, "tls://") {
|
||||
listenAddr = strings.TrimPrefix(listenAddr, "tls://")
|
||||
|
||||
case "tls":
|
||||
server.TLSConfig = getTLSConfig()
|
||||
|
||||
logger.Info("listening on address (TLS)")
|
||||
lsnr, err = tls.Listen("tcp", listen.address, server.TLSConfig)
|
||||
|
||||
default:
|
||||
logger.WithField("protocol", listen.protocol).
|
||||
log.WithField("address", listenAddr).
|
||||
Info("listening on address (TLS)")
|
||||
lsnr, err = tls.Listen("tcp", listenAddr, server.TLSConfig)
|
||||
} else {
|
||||
log.WithField("address", listenAddr).
|
||||
Fatal("unknown protocol in listen address")
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
logger.WithError(err).Fatal("error starting listener")
|
||||
log.WithFields(logrus.Fields{
|
||||
"address": listenAddr,
|
||||
}).WithError(err).Fatal("error starting listener")
|
||||
}
|
||||
servers = append(servers, server)
|
||||
|
||||
|
||||
83
remotes.go
83
remotes.go
@@ -1,83 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/smtp"
|
||||
"net/url"
|
||||
)
|
||||
|
||||
type Remote struct {
|
||||
SkipVerify bool
|
||||
Auth smtp.Auth
|
||||
Scheme string
|
||||
Hostname string
|
||||
Port string
|
||||
Addr string
|
||||
Sender string
|
||||
}
|
||||
|
||||
// ParseRemote creates a remote from a given url in the following format:
|
||||
//
|
||||
// smtp://[user[:password]@][netloc][:port][/remote_sender][?param1=value1&...]
|
||||
// smtps://[user[:password]@][netloc][:port][/remote_sender][?param1=value1&...]
|
||||
// starttls://[user[:password]@][netloc][:port][/remote_sender][?param1=value1&...]
|
||||
//
|
||||
// Supported Params:
|
||||
// - skipVerify: can be "true" or empty to prevent ssl verification of remote server's certificate.
|
||||
// - auth: can be "login" to trigger "LOGIN" auth instead of "PLAIN" auth
|
||||
func ParseRemote(remoteURL string) (*Remote, error) {
|
||||
u, err := url.Parse(remoteURL)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if u.Scheme != "smtp" && u.Scheme != "smtps" && u.Scheme != "starttls" {
|
||||
return nil, fmt.Errorf("'%s' is not a supported relay scheme", u.Scheme)
|
||||
}
|
||||
|
||||
hostname, port := u.Hostname(), u.Port()
|
||||
|
||||
if port == "" {
|
||||
switch u.Scheme {
|
||||
case "smtp":
|
||||
port = "25"
|
||||
case "smtps":
|
||||
port = "465"
|
||||
case "starttls":
|
||||
port = "587"
|
||||
}
|
||||
}
|
||||
|
||||
q := u.Query()
|
||||
r := &Remote{
|
||||
Scheme: u.Scheme,
|
||||
Hostname: hostname,
|
||||
Port: port,
|
||||
Addr: fmt.Sprintf("%s:%s", hostname, port),
|
||||
}
|
||||
|
||||
if u.User != nil {
|
||||
pass, _ := u.User.Password()
|
||||
user := u.User.Username()
|
||||
|
||||
if hasAuth, authVal := q.Has("auth"), q.Get("auth"); hasAuth {
|
||||
if authVal != "login" {
|
||||
return nil, fmt.Errorf("Auth must be login or not present, received '%s'", authVal)
|
||||
}
|
||||
|
||||
r.Auth = LoginAuth(user, pass)
|
||||
} else {
|
||||
r.Auth = smtp.PlainAuth("", user, pass, u.Hostname())
|
||||
}
|
||||
}
|
||||
|
||||
if hasVal, skipVerify := q.Has("skipVerify"), q.Get("skipVerify"); hasVal && skipVerify != "false" {
|
||||
r.SkipVerify = true
|
||||
}
|
||||
|
||||
if u.Path != "" {
|
||||
r.Sender = u.Path[1:]
|
||||
}
|
||||
|
||||
return r, nil
|
||||
}
|
||||
114
remotes_test.go
114
remotes_test.go
@@ -1,114 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"net/smtp"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func AssertRemoteUrlEquals(t *testing.T, expected *Remote, remotUrl string) {
|
||||
actual, err := ParseRemote(remotUrl)
|
||||
assert.Nil(t, err)
|
||||
assert.NotNil(t, actual)
|
||||
assert.Equal(t, expected.Scheme, actual.Scheme, "Scheme %s", remotUrl)
|
||||
assert.Equal(t, expected.Addr, actual.Addr, "Addr %s", remotUrl)
|
||||
assert.Equal(t, expected.Hostname, actual.Hostname, "Hostname %s", remotUrl)
|
||||
assert.Equal(t, expected.Port, actual.Port, "Port %s", remotUrl)
|
||||
assert.Equal(t, expected.Sender, actual.Sender, "Sender %s", remotUrl)
|
||||
assert.Equal(t, expected.SkipVerify, actual.SkipVerify, "SkipVerify %s", remotUrl)
|
||||
|
||||
if expected.Auth != nil || actual.Auth != nil {
|
||||
assert.NotNil(t, expected, "Auth %s", remotUrl)
|
||||
assert.NotNil(t, actual, "Auth %s", remotUrl)
|
||||
assert.IsType(t, expected.Auth, actual.Auth)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidRemoteUrls(t *testing.T) {
|
||||
AssertRemoteUrlEquals(t, &Remote{
|
||||
Scheme: "smtp",
|
||||
SkipVerify: false,
|
||||
Auth: nil,
|
||||
Hostname: "email.com",
|
||||
Port: "25",
|
||||
Addr: "email.com:25",
|
||||
Sender: "",
|
||||
}, "smtp://email.com")
|
||||
|
||||
AssertRemoteUrlEquals(t, &Remote{
|
||||
Scheme: "smtp",
|
||||
SkipVerify: true,
|
||||
Auth: nil,
|
||||
Hostname: "email.com",
|
||||
Port: "25",
|
||||
Addr: "email.com:25",
|
||||
Sender: "",
|
||||
}, "smtp://email.com?skipVerify")
|
||||
|
||||
AssertRemoteUrlEquals(t, &Remote{
|
||||
Scheme: "smtp",
|
||||
SkipVerify: false,
|
||||
Auth: smtp.PlainAuth("", "user", "pass", ""),
|
||||
Hostname: "email.com",
|
||||
Port: "25",
|
||||
Addr: "email.com:25",
|
||||
Sender: "",
|
||||
}, "smtp://user:pass@email.com")
|
||||
|
||||
AssertRemoteUrlEquals(t, &Remote{
|
||||
Scheme: "smtp",
|
||||
SkipVerify: false,
|
||||
Auth: LoginAuth("user", "pass"),
|
||||
Hostname: "email.com",
|
||||
Port: "25",
|
||||
Addr: "email.com:25",
|
||||
Sender: "",
|
||||
}, "smtp://user:pass@email.com?auth=login")
|
||||
|
||||
AssertRemoteUrlEquals(t, &Remote{
|
||||
Scheme: "smtp",
|
||||
SkipVerify: false,
|
||||
Auth: LoginAuth("user", "pass"),
|
||||
Hostname: "email.com",
|
||||
Port: "25",
|
||||
Addr: "email.com:25",
|
||||
Sender: "sender@website.com",
|
||||
}, "smtp://user:pass@email.com/sender@website.com?auth=login")
|
||||
|
||||
AssertRemoteUrlEquals(t, &Remote{
|
||||
Scheme: "smtps",
|
||||
SkipVerify: false,
|
||||
Auth: LoginAuth("user", "pass"),
|
||||
Hostname: "email.com",
|
||||
Port: "465",
|
||||
Addr: "email.com:465",
|
||||
Sender: "sender@website.com",
|
||||
}, "smtps://user:pass@email.com/sender@website.com?auth=login")
|
||||
|
||||
AssertRemoteUrlEquals(t, &Remote{
|
||||
Scheme: "smtps",
|
||||
SkipVerify: true,
|
||||
Auth: LoginAuth("user", "pass"),
|
||||
Hostname: "email.com",
|
||||
Port: "8425",
|
||||
Addr: "email.com:8425",
|
||||
Sender: "sender@website.com",
|
||||
}, "smtps://user:pass@email.com:8425/sender@website.com?auth=login&skipVerify")
|
||||
|
||||
AssertRemoteUrlEquals(t, &Remote{
|
||||
Scheme: "starttls",
|
||||
SkipVerify: true,
|
||||
Auth: LoginAuth("user", "pass"),
|
||||
Hostname: "email.com",
|
||||
Port: "8425",
|
||||
Addr: "email.com:8425",
|
||||
Sender: "sender@website.com",
|
||||
}, "starttls://user:pass@email.com:8425/sender@website.com?auth=login&skipVerify")
|
||||
}
|
||||
|
||||
func TestMissingScheme(t *testing.T) {
|
||||
_, err := ParseRemote("http://user:pass@email.com:8425/sender@website.com")
|
||||
assert.NotNil(t, err, "Err must be present")
|
||||
assert.Equal(t, err.Error(), "'http' is not a supported relay scheme")
|
||||
}
|
||||
11
service_files/smtprelay.service
Normal file
11
service_files/smtprelay.service
Normal file
@@ -0,0 +1,11 @@
|
||||
[Unit]
|
||||
Description=SMTP Relay
|
||||
After=network-online.target
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
ExecStart=/opt/smtprelay/bin/smtprelay -config /etc/smtprelay/smtprelay.ini
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
49
smtp.go
49
smtp.go
@@ -4,17 +4,15 @@
|
||||
|
||||
// Package smtp implements the Simple Mail Transfer Protocol as defined in RFC 5321.
|
||||
// It also implements the following extensions:
|
||||
//
|
||||
// 8BITMIME RFC 1652
|
||||
// AUTH RFC 2554
|
||||
// STARTTLS RFC 3207
|
||||
//
|
||||
// Additional extensions may be handled by clients.
|
||||
//
|
||||
// The smtp package is frozen and is not accepting new features.
|
||||
// Some external packages provide more functionality. See:
|
||||
//
|
||||
// https://godoc.org/?q=smtp
|
||||
// https://godoc.org/?q=smtp
|
||||
package main
|
||||
|
||||
import (
|
||||
@@ -108,7 +106,7 @@ func (c *Client) Hello(localName string) error {
|
||||
}
|
||||
|
||||
// cmd is a convenience function that sends a command and returns the response
|
||||
func (c *Client) cmd(expectCode int, format string, args ...any) (int, string, error) {
|
||||
func (c *Client) cmd(expectCode int, format string, args ...interface{}) (int, string, error) {
|
||||
id, err := c.Text.Cmd(format, args...)
|
||||
if err != nil {
|
||||
return 0, "", err
|
||||
@@ -139,8 +137,12 @@ func (c *Client) ehlo() error {
|
||||
if len(extList) > 1 {
|
||||
extList = extList[1:]
|
||||
for _, line := range extList {
|
||||
k, v, _ := strings.Cut(line, " ")
|
||||
ext[k] = v
|
||||
args := strings.SplitN(line, " ", 2)
|
||||
if len(args) > 1 {
|
||||
ext[args[0]] = args[1]
|
||||
} else {
|
||||
ext[args[0]] = ""
|
||||
}
|
||||
}
|
||||
}
|
||||
if mechs, ok := ext["AUTH"]; ok {
|
||||
@@ -320,11 +322,7 @@ var testHookStartTLS func(*tls.Config) // nil, except for tests
|
||||
// attachments (see the mime/multipart package), or other mail
|
||||
// functionality. Higher-level packages exist outside of the standard
|
||||
// library.
|
||||
func SendMail(r *Remote, from string, to []string, msg []byte) error {
|
||||
if r.Sender != "" {
|
||||
from = r.Sender
|
||||
}
|
||||
|
||||
func SendMail(addr string, a smtp.Auth, from string, to []string, msg []byte) error {
|
||||
if err := validateLine(from); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -333,19 +331,19 @@ func SendMail(r *Remote, from string, to []string, msg []byte) error {
|
||||
return err
|
||||
}
|
||||
}
|
||||
host, port, err := net.SplitHostPort(addr)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var c *Client
|
||||
var err error
|
||||
if r.Scheme == "smtps" {
|
||||
config := &tls.Config{
|
||||
ServerName: r.Hostname,
|
||||
InsecureSkipVerify: r.SkipVerify,
|
||||
}
|
||||
conn, err := tls.Dial("tcp", r.Addr, config)
|
||||
if port == "465" || port == "smtps" {
|
||||
config := &tls.Config{ServerName: host}
|
||||
conn, err := tls.Dial("tcp", addr, config)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer conn.Close()
|
||||
c, err = NewClient(conn, r.Hostname)
|
||||
c, err = NewClient(conn, host)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -353,7 +351,7 @@ func SendMail(r *Remote, from string, to []string, msg []byte) error {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
c, err = Dial(r.Addr)
|
||||
c, err = Dial(addr)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -362,25 +360,20 @@ func SendMail(r *Remote, from string, to []string, msg []byte) error {
|
||||
return err
|
||||
}
|
||||
if ok, _ := c.Extension("STARTTLS"); ok {
|
||||
config := &tls.Config{
|
||||
ServerName: c.serverName,
|
||||
InsecureSkipVerify: r.SkipVerify,
|
||||
}
|
||||
config := &tls.Config{ServerName: c.serverName}
|
||||
if testHookStartTLS != nil {
|
||||
testHookStartTLS(config)
|
||||
}
|
||||
if err = c.StartTLS(config); err != nil {
|
||||
return err
|
||||
}
|
||||
} else if r.Scheme == "starttls" {
|
||||
return errors.New("starttls: server does not support extension, check remote scheme")
|
||||
}
|
||||
}
|
||||
if r.Auth != nil && c.ext != nil {
|
||||
if a != nil && c.ext != nil {
|
||||
if _, ok := c.ext["AUTH"]; !ok {
|
||||
return errors.New("smtp: server doesn't support AUTH")
|
||||
}
|
||||
if err = c.Auth(r.Auth); err != nil {
|
||||
if err = c.Auth(a); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,23 +1,19 @@
|
||||
; smtprelay configuration
|
||||
;
|
||||
; All config parameters can also be provided as environment
|
||||
; variables in uppercase and the prefix "SMTPRELAY_".
|
||||
; (eg. SMTPRELAY_LOGFILE, SMTPRELAY_LOG_FORMAT)
|
||||
|
||||
; Logfile (blank/default is stderr)
|
||||
;logfile =
|
||||
|
||||
; Log format: default, plain (no timestamp), json
|
||||
;log_format = default
|
||||
;log_format = "default"
|
||||
|
||||
; Log level: panic, fatal, error, warn, info, debug, trace
|
||||
;log_level = info
|
||||
;log_level = "info"
|
||||
|
||||
; Hostname for this SMTP server
|
||||
;hostname = localhost.localdomain
|
||||
;hostname = "localhost.localdomain"
|
||||
|
||||
; Welcome message for clients
|
||||
;welcome_msg = <hostname> ESMTP ready.
|
||||
;welcome_msg = "<hostname> ESMTP ready."
|
||||
|
||||
; Listen on the following addresses for incoming
|
||||
; unencrypted connections.
|
||||
@@ -34,33 +30,6 @@
|
||||
; accepting mails from client.
|
||||
;local_forcetls = false
|
||||
|
||||
; Socket timeout for read operations
|
||||
; Duration string as sequence of decimal numbers,
|
||||
; each with optional fraction and a unit suffix.
|
||||
; Valid time units are "ns", "us", "ms", "s", "m", "h".
|
||||
;read_timeout = 60s
|
||||
|
||||
; Socket timeout for write operations
|
||||
; Duration string as sequence of decimal numbers,
|
||||
; each with optional fraction and a unit suffix.
|
||||
; Valid time units are "ns", "us", "ms", "s", "m", "h".
|
||||
;write_timeout = 60s
|
||||
|
||||
; Socket timeout for DATA command
|
||||
; Duration string as sequence of decimal numbers,
|
||||
; each with optional fraction and a unit suffix.
|
||||
; Valid time units are "ns", "us", "ms", "s", "m", "h".
|
||||
;data_timeout = 5m
|
||||
|
||||
; Max concurrent connections, use -1 to disable
|
||||
;max_connections = 100
|
||||
|
||||
; Max message size in bytes
|
||||
;max_message_size = 10240000
|
||||
|
||||
; Max RCPT TO calls for each envelope
|
||||
;max_recipients = 100
|
||||
|
||||
; Networks that are allowed to send mails to us
|
||||
; Defaults to localhost. If set to "", then any address is allowed.
|
||||
;allowed_nets = 127.0.0.0/8 ::1/128
|
||||
@@ -87,40 +56,25 @@
|
||||
; E.g. "app@example.com,@appsrv.example.com"
|
||||
;allowed_users =
|
||||
|
||||
; Relay all mails to this SMTP servers.
|
||||
; Relay all mails to this SMTP server.
|
||||
; If not set, mails are discarded.
|
||||
;
|
||||
; Format:
|
||||
; protocol://[user[:password]@][netloc][:port][/remote_sender][?param1=value1&...]
|
||||
;
|
||||
; protocol: smtp (unencrypted), smtps (TLS), starttls (STARTTLS)
|
||||
; user: Username for authentication
|
||||
; password: Password for authentication
|
||||
; remote_sender: Email address to use as FROM
|
||||
; params:
|
||||
; skipVerify: "true" or empty to prevent ssl verification of remote server's certificate
|
||||
; auth: "login" to use LOGIN authentication
|
||||
|
||||
; GMail
|
||||
;remotes = starttls://user:pass@smtp.gmail.com:587
|
||||
;remote_host = smtp.gmail.com:587
|
||||
|
||||
; Mailgun.org
|
||||
;remotes = starttls://user:pass@smtp.mailgun.org:587
|
||||
;remote_host = smtp.mailgun.org:587
|
||||
|
||||
; Mailjet.com
|
||||
;remotes = starttls://user:pass@in-v3.mailjet.com:587
|
||||
;remote_host = in-v3.mailjet.com:587
|
||||
|
||||
; Ignore remote host certificates
|
||||
;remotes = starttls://user:pass@server:587?skipVerify
|
||||
; Authentication credentials on outgoing SMTP server
|
||||
;remote_user =
|
||||
;remote_pass =
|
||||
|
||||
; Login Authentication method on outgoing SMTP server
|
||||
;remotes = smtp://user:pass@server:2525?auth=login
|
||||
; Authentication method on outgoing SMTP server
|
||||
; (none, plain, login)
|
||||
;remote_auth = none
|
||||
|
||||
; Sender e-mail address on outgoing SMTP server
|
||||
;remotes = smtp://user:pass@server:2525/overridden@email.com?auth=login
|
||||
|
||||
; Multiple remotes, space delimited
|
||||
;remotes = smtp://127.0.0.1:1025 starttls://user:pass@smtp.mailgun.org:587
|
||||
|
||||
; Pipe messages to external command
|
||||
;command = /usr/local/bin/script
|
||||
;remote_sender =
|
||||
|
||||
Reference in New Issue
Block a user