2
0
forked from drew/smtprelay

58 Commits

Author SHA1 Message Date
Bernhard Froehlich
7b199cc6ae Bump Go version for CI builds to 1.16 2021-04-02 18:51:23 +00:00
Bernhard Froehlich
184d5f8611 Bump Go version for builds to 1.16.3 2021-04-02 18:49:53 +00:00
Bernhard Fröhlich
9e8b5517a6 Merge pull request #27 from decke/26-tls-reqd-for-auth
Don't allow configuration requiring authentication with non-TLS listener
2021-04-02 20:41:38 +02:00
Bernhard Fröhlich
65f0cfcfbd Merge pull request #28 from decke/dependabot/github_actions/wangyoucao577/go-release-action-v1.16
Bump wangyoucao577/go-release-action from v1.15 to v1.16
2021-04-02 20:29:02 +02:00
dependabot[bot]
410c70d86f Bump wangyoucao577/go-release-action from v1.15 to v1.16
Bumps [wangyoucao577/go-release-action](https://github.com/wangyoucao577/go-release-action) from v1.15 to v1.16.
- [Release notes](https://github.com/wangyoucao577/go-release-action/releases)
- [Commits](https://github.com/wangyoucao577/go-release-action/compare/v1.15...d00bb7360b2dd6a39f1a7ca198b8289582eee2df)

Signed-off-by: dependabot[bot] <support@github.com>
2021-04-01 07:35:56 +00:00
Jonathon Reinhart
247d187576 Don't allow a configuration requiring auth with a non-TLS listener
This fixes #26
2021-04-01 01:12:34 -04:00
Jonathon Reinhart
45a676e274 Add localAuthRequired() helper function
This just makes the configuration state a little more obvious.
2021-04-01 01:12:34 -04:00
Jonathon Reinhart
ca1ccd85e3 Refactor parsing of -listen string out into separate config function
This makes the "for each listen address" loop in main() look even cleaner.
2021-04-01 01:12:34 -04:00
Jonathon Reinhart
42abf27c1f Merge pull request #22 from decke/smtpd-shutdown
Handle signals and gracefully shut down, waiting for clients
2021-04-01 01:11:48 -04:00
Jonathon Reinhart
1b7b551f65 Handle signals and gracefully shut down server 2021-04-01 01:07:30 -04:00
Bernhard Fröhlich
2cd636c082 Merge pull request #19 from decke/allow-any-sender-recipient
Move remaining config option parsing to ConfigLoad()
2021-04-01 06:05:52 +02:00
Jonathon Reinhart
3debf4127d Adjust remote auth disabled check syntax 2021-03-31 17:18:13 -04:00
Bernhard Fröhlich
03b8b78f53 Merge pull request #24 from decke/dependabot/go_modules/github.com/chrj/smtpd-0.3.0
Bump github.com/chrj/smtpd from 0.2.0 to 0.3.0
2021-03-29 22:26:38 +02:00
dependabot[bot]
49c6880175 Bump github.com/chrj/smtpd from 0.2.0 to 0.3.0
Bumps [github.com/chrj/smtpd](https://github.com/chrj/smtpd) from 0.2.0 to 0.3.0.
- [Release notes](https://github.com/chrj/smtpd/releases)
- [Commits](https://github.com/chrj/smtpd/compare/v0.2.0...v0.3.0)

Signed-off-by: dependabot[bot] <support@github.com>
2021-03-29 20:24:57 +00:00
Bernhard Fröhlich
5470132251 Merge pull request #23 from decke/dependabot/github_actions/wangyoucao577/go-release-action-v1.15
Bump wangyoucao577/go-release-action from v1.14 to v1.15
2021-03-18 15:41:11 +01:00
dependabot[bot]
898f8e44cf Bump wangyoucao577/go-release-action from v1.14 to v1.15
Bumps [wangyoucao577/go-release-action](https://github.com/wangyoucao577/go-release-action) from v1.14 to v1.15.
- [Release notes](https://github.com/wangyoucao577/go-release-action/releases)
- [Commits](https://github.com/wangyoucao577/go-release-action/compare/v1.14...1caa775ade7bd6692dd752d506f106792e76843d)

Signed-off-by: dependabot[bot] <support@github.com>
2021-03-18 07:16:46 +00:00
Jonathon Reinhart
22ef0c2ee6 Move SMTP auth setup to ConfigLoad()
This has several benefits:
- Configuration errors are caught at startup rather than upon a connection
- mailHandler() has less work to do for each connection

Rather than relying on remote_user and remote_pass to control whether
authentication is used, introduce an explicit "none" type for
remote_auth, and make that the default. (This is effectively the same
default behavior since remote_user and remote_pass default to empty.)

Also, we are in a better position to more thoroughly check for
configuration errors or mismatches:
- If remote_auth is given, remote_user and remote_pass are required.
- If remote_auth is given, remote_host is also required (because it
  makes no sense to say we're going to authenticate if we have no server
  to which to authenticate.)
- If remote_user or remote_pass are given, remote_auth cannot be "none".
2021-03-14 18:41:54 -04:00
Bernhard Fröhlich
8eea677a3d Merge pull request #20 from decke/dependabot/go_modules/github.com/sirupsen/logrus-1.8.1
Bump github.com/sirupsen/logrus from 1.7.0 to 1.8.1
2021-03-14 21:27:11 +01:00
dependabot[bot]
9f2497d948 Bump github.com/sirupsen/logrus from 1.7.0 to 1.8.1
Bumps [github.com/sirupsen/logrus](https://github.com/sirupsen/logrus) from 1.7.0 to 1.8.1.
- [Release notes](https://github.com/sirupsen/logrus/releases)
- [Changelog](https://github.com/sirupsen/logrus/blob/master/CHANGELOG.md)
- [Commits](https://github.com/sirupsen/logrus/compare/v1.7.0...v1.8.1)

Signed-off-by: dependabot[bot] <support@github.com>
2021-03-14 20:23:53 +00:00
Jonathon Reinhart
76ef135d33 Clarify allowed_sender/allowed_recipient empty string behavior 2021-03-14 12:36:34 -04:00
Jonathon Reinhart
7c0ba34025 Move compilation of allowed_recipients to ConfigLoad()
This has several benefits:
- Configuration errors are caught at startup rather than upon a connection
- recipientChecker() has less work to do for each connection
2021-03-14 12:31:38 -04:00
Jonathon Reinhart
a896ab2847 Move compilation of allowed_sender to ConfigLoad()
This has several benefits:
- Configuration errors are caught at startup rather than upon a connection
- senderChecker() has less work to do for each connection
2021-03-14 12:31:38 -04:00
Jonathon Reinhart
c9b55b833b Merge pull request #18 from decke/allow-any-net
Allow any network and related enhancements
2021-03-13 20:47:09 -05:00
Jonathon Reinhart
918df65a3a Require that networks in allowed_nets are networks and not hosts 2021-03-13 20:40:25 -05:00
Jonathon Reinhart
0503c12ccd Allow "allowed_nets" to be empty, meaning any network is allowed 2021-03-13 20:34:48 -05:00
Jonathon Reinhart
ef3f9c8ea0 Move parsing of "allowed_nets" out to ConfigLoad()
This has several benefits:
- Configuration errors are caught at startup rather than upon a connection
- connectionChecker() has less work to do for each connection
2021-03-13 20:34:48 -05:00
Jonathon Reinhart
4036213dd5 Simplify peerIP determination in connectionChecker()
peerIP = net.ParseIP(addr.IP.String())

can be simplified to just:

    peerIP = addr.IP

but we can also skip the safe cast since we know the net.Addr will always
be net.TCPAddr because we only have TCP listeners.
2021-03-13 20:19:07 -05:00
Bernhard Fröhlich
2475cadbad Merge pull request #16 from decke/discard
Discard mail if remote_host is not set
2021-03-13 19:06:08 +01:00
Jonathon Reinhart
20ca816160 Discard mail if remote_host is not set
This is useful for test environments.
2021-03-13 09:28:04 -05:00
Bernhard Fröhlich
d1933a2e35 Merge pull request #15 from decke/structured-logging
Add structured logging via logrus
2021-03-13 11:02:19 +01:00
Jonathon Reinhart
9921b38046 Explicitly configure default logfile for stderr 2021-03-13 03:25:57 -05:00
Jonathon Reinhart
095fba119a Change default logfile to empty string (meaning stderr)
The causes logrus to write to stderr.
2021-03-13 03:25:57 -05:00
Jonathon Reinhart
34cb47c364 Implement structured logs using logrus
This was based loosely on an earlier implementation by
Danny Kopping <danny.kopping@grafana.com>
2021-03-13 03:25:57 -05:00
Bernhard Froehlich
b36ed8eddb net/smtp: adds support for the SMTPUTF8 extension
Obtained from:	https://github.com/golang/go/issues/19860
2021-02-25 21:15:16 +00:00
Bernhard Froehlich
822dbbce7d Bump Go to 1.15 for CI builds 2021-02-17 19:31:36 +00:00
Bernhard Fröhlich
42f5c68f0b Merge pull request #12 from decke/dependabot/github_actions/actions/setup-go-v2.1.3
Bump actions/setup-go from v1 to v2.1.3
2021-02-17 20:30:36 +01:00
dependabot[bot]
cd2dab8f8f Bump actions/setup-go from v1 to v2.1.3
Bumps [actions/setup-go](https://github.com/actions/setup-go) from v1 to v2.1.3.
- [Release notes](https://github.com/actions/setup-go/releases)
- [Commits](https://github.com/actions/setup-go/compare/v1...37335c7bb261b353407cff977110895fa0b4f7d8)

Signed-off-by: dependabot[bot] <support@github.com>
2021-02-17 19:29:13 +00:00
Bernhard Froehlich
f2af99dc52 Add github-actions to dependabot config 2021-02-17 19:28:08 +00:00
Bernhard Froehlich
23e10bb03e Add dependabot.yml for automatic Go dependency checking 2021-02-17 19:23:20 +00:00
Bernhard Froehlich
5ba64c5c6e Add new Release Workflow using Github Actions and wangyoucao577/go-release-action 2021-02-17 12:49:24 +00:00
Bernhard Froehlich
7f34fcbc99 gofmt: Fix formatting 2021-02-16 15:57:50 +00:00
Bernhard Froehlich
97943c87e7 Update go dependencies 2021-02-16 15:33:12 +00:00
Bernhard Froehlich
fefeccec39 Remove weak CBC cipher suites and bump minimum TLS version to TLS 1.2 2021-02-16 15:31:53 +00:00
Bernhard Fröhlich
c781938999 Merge pull request #11 from JonathonReinhart/minor-cleanup-fixes
Minor cleanup and fixes
2021-02-16 15:36:52 +01:00
Jonathon Reinhart
009ae8f73a hasher: Check number of arguments
This makes for a better user experience than a go segfault.
2021-02-15 00:18:15 -05:00
Jonathon Reinhart
70dfe6b128 Only call AuthLoadFile() once at startup 2021-02-15 00:08:37 -05:00
Jonathon Reinhart
7fa0eebf95 Simplify range code for setting up listeners 2021-02-15 00:00:38 -05:00
Jonathon Reinhart
ecf830865c Add helpful log messages for various error cases 2021-02-14 23:49:17 -05:00
Jonathon Reinhart
4fd6bb1004 Refactor common code in listener setup 2021-02-14 23:30:31 -05:00
Jonathon Reinhart
fd3f513b18 Don't run ListenAndServe in a goroutine
Any errors returned in ListenAndServe() (e.g. port already in use) will be
swallowed and not evident to the user.
2021-02-14 23:24:25 -05:00
Jonathon Reinhart
b202a2209e Refactor out getTLSConfig() 2021-02-14 23:21:42 -05:00
Jonathon Reinhart
0e8986ca79 Expand allowedUsers email field to support comma-separated and domains (#9)
* Expand allowedUsers email field to support comma-separated and domains

Closes #8

* Refactor AuthFetch() to return AuthUser struct

Also, this breaks out a parseLine() function which can be easily tested.

* Ignore empty addrs after splitting commas

This ignores a trailing comma

* Add tests for auth parseLine()

* Update documentation in smtprelay.ini

* Fix bug where addrAllowed() was incorrectly case-sensitive

* Update allowedUsers allowed domain format to require leading @

This disambiguates a local user ('john.smith') from a domain ('example.com')
2021-02-14 22:16:18 +01:00
Bernhard Fröhlich
5c2e28ac36 Merge pull request #7 from JonathonReinhart/allow-empty-auth-email
Allow email field to be empty in allowedUsers file to accept any sending address
2021-02-09 14:18:06 +01:00
Jonathon Reinhart
f33105f83c Allow email field to be empty in allowedUsers file
In this case, it is not checked.
2021-02-09 00:00:36 -05:00
Bernhard Fröhlich
9040a456cf Create codeql-analysis.yml 2020-09-28 21:26:31 +02:00
Bernhard Fröhlich
d5c5e25d03 Merge pull request #4 from simon04/addresses
Fix typo "addresses"
2020-09-04 15:14:35 +02:00
Simon Legner
999cfea307 Fix typo "addresses" 2020-09-03 14:06:20 +02:00
Bernhard Froehlich
f166c13350 Bump Version string 2020-06-14 18:51:16 +00:00
17 changed files with 892 additions and 212 deletions

11
.github/dependabot.yml vendored Normal file
View File

@@ -0,0 +1,11 @@
version: 2
updates:
- package-ecosystem: "gomod"
directory: "/"
schedule:
interval: "daily"
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "daily"

66
.github/workflows/codeql-analysis.yml vendored Normal file
View File

@@ -0,0 +1,66 @@
name: "CodeQL"
on:
push:
branches: [master]
pull_request:
# The branches below must be a subset of the branches above
branches: [master]
schedule:
- cron: '0 15 * * 5'
jobs:
analyze:
name: Analyze
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
# Override automatic language detection by changing the below list
# Supported options are ['csharp', 'cpp', 'go', 'java', 'javascript', 'python']
language: ['go']
# Learn more...
# https://docs.github.com/en/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#overriding-automatic-language-detection
steps:
- name: Checkout repository
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.
fetch-depth: 2
# If this run was triggered by a pull request event, then checkout
# the head of the pull request instead of the merge commit.
- run: git checkout HEAD^2
if: ${{ github.event_name == 'pull_request' }}
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
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.
# By default, queries listed here will override any specified in a config file.
# Prefix the list here with "+" to use these queries and those in the config file.
# queries: ./path/to/local/query, your-org/your-repo/queries@main
# 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@v1
# Command-line programs to run using the OS shell.
# 📚 https://git.io/JvXDl
# ✏️ If the Autobuild fails above, remove it and uncomment the following three lines
# and modify them (or add more) to build your code if your project
# uses a compiled language
#- run: |
# make bootstrap
# make release
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v1

View File

@@ -7,10 +7,10 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Set up Go 1.14
uses: actions/setup-go@v1
- name: Set up Go 1.16
uses: actions/setup-go@v2.1.3
with:
go-version: 1.14
go-version: 1.16
id: go
- name: Check out code into the Go module directory

30
.github/workflows/release.yaml vendored Normal file
View File

@@ -0,0 +1,30 @@
name: Release Go Binaries
on:
release:
types: [created]
jobs:
releases-matrix:
name: Release Go Binary
runs-on: ubuntu-latest
strategy:
matrix:
goos: [freebsd, linux, windows]
goarch: ["386", amd64]
steps:
- 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.16
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
goos: ${{ matrix.goos }}
goarch: ${{ matrix.goarch }}
goversion: "https://golang.org/dl/go1.16.3.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 }}"

55
auth.go
View File

@@ -13,6 +13,12 @@ var (
filename string
)
type AuthUser struct {
username string
passwordHash string
allowedAddresses []string
}
func AuthLoadFile(file string) error {
f, err := os.Open(file)
if err != nil {
@@ -28,39 +34,66 @@ func AuthReady() bool {
return (filename != "")
}
func AuthFetch(username string) (string, string, error) {
// Split a string and ignore empty results
// https://stackoverflow.com/a/46798310/119527
func splitstr(s string, sep rune) []string {
return strings.FieldsFunc(s, func(c rune) bool { return c == sep })
}
func parseLine(line string) *AuthUser {
parts := strings.Fields(line)
if len(parts) < 2 || len(parts) > 3 {
return nil
}
user := AuthUser{
username: parts[0],
passwordHash: parts[1],
allowedAddresses: nil,
}
if len(parts) >= 3 {
user.allowedAddresses = splitstr(parts[2], ',')
}
return &user
}
func AuthFetch(username string) (*AuthUser, error) {
if !AuthReady() {
return "", "", errors.New("Authentication file not specified. Call LoadFile() first")
return nil, errors.New("Authentication file not specified. Call LoadFile() first")
}
file, err := os.Open(filename)
if err != nil {
return "", "", err
return nil, err
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
parts := strings.Fields(scanner.Text())
if len(parts) != 3 {
user := parseLine(scanner.Text())
if user == nil {
continue
}
if strings.ToLower(username) == strings.ToLower(parts[0]) {
return parts[1], parts[2], nil
if strings.ToLower(username) != strings.ToLower(user.username) {
continue
}
return user, nil
}
return "", "", errors.New("User not found")
return nil, errors.New("User not found")
}
func AuthCheckPassword(username string, secret string) error {
hash, _, err := AuthFetch(username)
user, err := AuthFetch(username)
if err != nil {
return err
}
if bcrypt.CompareHashAndPassword([]byte(hash), []byte(secret)) == nil {
if bcrypt.CompareHashAndPassword([]byte(user.passwordHash), []byte(secret)) == nil {
return nil
}
return errors.New("Password invalid")

89
auth_test.go Normal file
View File

@@ -0,0 +1,89 @@
package main
import (
"testing"
)
func stringsEqual(a, b []string) bool {
if len(a) != len(b) {
return false
}
for i := range a {
if a[i] != b[i] {
return false
}
}
return true
}
func TestParseLine(t *testing.T) {
var tests = []struct {
name string
expectFail bool
line string
username string
addrs []string
}{
{
name: "Empty line",
expectFail: true,
line: "",
},
{
name: "Too few fields",
expectFail: true,
line: "joe",
},
{
name: "Too many fields",
expectFail: true,
line: "joe xxx joe@example.com whatsthis",
},
{
name: "Normal case",
line: "joe xxx joe@example.com",
username: "joe",
addrs: []string{"joe@example.com"},
},
{
name: "No allowed addrs given",
line: "joe xxx",
username: "joe",
addrs: []string{},
},
{
name: "Trailing comma",
line: "joe xxx joe@example.com,",
username: "joe",
addrs: []string{"joe@example.com"},
},
{
name: "Multiple allowed addrs",
line: "joe xxx joe@example.com,@foo.example.com",
username: "joe",
addrs: []string{"joe@example.com", "@foo.example.com"},
},
}
for i, test := range tests {
t.Run(test.name, func(t *testing.T) {
user := parseLine(test.line)
if user == nil {
if !test.expectFail {
t.Errorf("parseLine() returned nil unexpectedly")
}
return
}
if user.username != test.username {
t.Errorf("Testcase %d: Incorrect username: expected %v, got %v",
i, test.username, user.username)
}
if !stringsEqual(user.allowedAddresses, test.addrs) {
t.Errorf("Testcase %d: Incorrect addresses: expected %v, got %v",
i, test.addrs, user.allowedAddresses)
}
})
}
}

View File

@@ -8,11 +8,15 @@ import (
)
func main() {
if len(os.Args) != 2 {
fmt.Fprintln(os.Stderr, "Usage: hasher PASSWORD")
os.Exit(1)
}
password := os.Args[1]
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
fmt.Println("Error generating hash: %s", err)
fmt.Fprintln(os.Stderr, "Error generating hash: %s", err)
}
fmt.Println(string(hash))
}

173
config.go
View File

@@ -2,34 +2,185 @@ package main
import (
"flag"
"net"
"net/smtp"
"regexp"
"strings"
"github.com/vharitonsky/iniflags"
)
const (
VERSION = "1.3.0"
"github.com/sirupsen/logrus"
)
var (
logFile = flag.String("logfile", "/var/log/smtprelay.log", "Path to logfile")
appVersion = "unknown"
buildTime = "unknown"
)
var (
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")
listenStr = flag.String("listen", "127.0.0.1:25 [::1]:25", "Address and port to listen for incoming SMTP")
listenAddrs = []protoAddr{}
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)")
allowedNets = flag.String("allowed_nets", "127.0.0.1/8 ::1/128", "Networks allowed to send mails")
allowedSender = flag.String("allowed_sender", "", "Regular expression for valid FROM EMail adresses")
allowedRecipients = flag.String("allowed_recipients", "", "Regular expression for valid TO EMail adresses")
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
allowedUsers = flag.String("allowed_users", "", "Path to file with valid users/passwords")
remoteHost = flag.String("remote_host", "smtp.gmail.com:587", "Outgoing SMTP server")
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")
remoteAuth = flag.String("remote_auth", "plain", "Auth method on outgoing SMTP server (plain, login)")
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, ' ') {
baseIP, allowedNet, err := net.ParseCIDR(netstr)
if err != nil {
log.WithField("netstr", netstr).
WithError(err).
Fatal("Invalid CIDR notation in allowed_nets")
}
// Reject any network specification where any host bits are set,
// meaning the address refers to a host and not a network.
if !allowedNet.IP.Equal(baseIP) {
log.WithFields(logrus.Fields{
"given_net": netstr,
"proper_net": allowedNet,
}).Fatal("Invalid network in allowed_nets (host bits set)")
}
allowedNets = append(allowedNets, allowedNet)
}
}
func setupAllowedPatterns() {
var err error
if (*allowedSenderStr != "") {
allowedSender, err = regexp.Compile(*allowedSenderStr)
if err != nil {
log.WithField("allowed_sender", *allowedSenderStr).
WithError(err).
Fatal("allowed_sender pattern invalid")
}
}
if (*allowedRecipStr != "") {
allowedRecipients, err = regexp.Compile(*allowedRecipStr)
if err != nil {
log.WithField("allowed_recipients", *allowedRecipStr).
WithError(err).
Fatal("allowed_recipients pattern invalid")
}
}
}
func setupRemoteAuth() {
logger := log.WithField("remote_auth", *remoteAuthStr)
// Remote auth disabled?
if *remoteAuthStr == "" || *remoteAuthStr == "none" {
if *remoteUser != "" {
logger.Fatal("remote_user given but not used")
}
if *remotePass != "" {
logger.Fatal("remote_pass given but not used")
}
// No auth; use empty default
return
}
// 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")
}
host, _, err := net.SplitHostPort(*remoteHost)
if err != nil {
logger.WithField("remote_host", *remoteHost).
Fatal("Invalid remote_host")
}
switch *remoteAuthStr {
case "plain":
remoteAuth = smtp.PlainAuth("", *remoteUser, *remotePass, host)
case "login":
remoteAuth = LoginAuth(*remoteUser, *remotePass)
default:
logger.Fatal("Invalid remote_auth type")
}
}
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 : len(s)],
}
}
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")
}
listenAddrs = append(listenAddrs, pa)
}
}
func ConfigLoad() {
iniflags.Parse()
// Set up logging as soon as possible
setupLogger()
if (*remoteHost == "") {
log.Warn("remote_host not set; mail will not be forwarded!")
}
setupAllowedNetworks()
setupAllowedPatterns()
setupRemoteAuth()
setupListeners()
}

44
config_test.go Normal file
View File

@@ -0,0 +1,44 @@
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)
}
})
}
}

6
go.mod
View File

@@ -1,9 +1,11 @@
module github.com/decke/smtprelay
require (
github.com/chrj/smtpd v0.2.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-20200604202706-70a84ac30bf9
golang.org/x/crypto v0.0.0-20201221181555-eec23a3978ad
)
go 1.13

22
go.sum
View File

@@ -1,12 +1,24 @@
github.com/chrj/smtpd v0.2.0 h1:QGbE4UQz7sKjvXpRgNLuiBOjcWTzBKu/dj0hyDLpD14=
github.com/chrj/smtpd v0.2.0/go.mod h1:1hmG9KbrE10JG1SmvG79Krh4F6713oUrw2+gRp1oSYk=
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/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/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-20200604202706-70a84ac30bf9 h1:vEg9joUBmeBcK9iSJftGNf3coIG4HqZElCPehJsfAYM=
golang.org/x/crypto v0.0.0-20200604202706-70a84ac30bf9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
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-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
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=

60
logger.go Normal file
View File

@@ -0,0 +1,60 @@
package main
import (
"fmt"
"os"
"time"
"github.com/sirupsen/logrus"
)
var (
log *logrus.Logger
)
func setupLogger() {
log = logrus.New()
// Handle logfile
if (*logFile == "") {
log.SetOutput(os.Stderr)
} else {
writer, err := os.OpenFile(*logFile, os.O_CREATE|os.O_RDWR|os.O_APPEND, 0600)
if err != nil {
fmt.Printf("cannot open log file: %s\n", err)
os.Exit(1)
}
log.SetOutput(writer)
}
// Handle log_format
switch *logFormat {
case "json":
log.SetFormatter(&logrus.JSONFormatter{
TimestampFormat: time.RFC3339Nano,
DisableHTMLEscape: true,
})
case "plain":
log.SetFormatter(&logrus.TextFormatter{
DisableTimestamp: true,
})
case "", "default":
log.SetFormatter(&logrus.TextFormatter{
FullTimestamp: true,
})
default:
fmt.Fprintf(os.Stderr, "Invalid log_format: %s\n", *logFormat)
os.Exit(1)
}
// Handle log_level
level, err := logrus.ParseLevel(*logLevel)
if err != nil {
level = logrus.InfoLevel
log.WithField("given_level", *logLevel).
Warn("could not parse log level, defaulting to 'info'")
}
log.SetLevel(level)
}

367
main.go
View File

@@ -3,91 +3,147 @@ package main
import (
"crypto/tls"
"fmt"
"io"
"log"
"net"
"net/smtp"
"net/textproto"
"os"
"regexp"
"os/signal"
"strings"
"time"
"syscall"
"github.com/chrj/smtpd"
"github.com/google/uuid"
"github.com/sirupsen/logrus"
)
func connectionChecker(peer smtpd.Peer) error {
var peerIP net.IP
if addr, ok := peer.Addr.(*net.TCPAddr); ok {
peerIP = net.ParseIP(addr.IP.String())
} else {
return smtpd.Error{Code: 421, Message: "Denied"}
// This can't panic because we only have TCP listeners
peerIP := peer.Addr.(*net.TCPAddr).IP
if len(allowedNets) == 0 {
// Special case: empty string means allow everything
return nil
}
nets := strings.Split(*allowedNets, " ")
for i := range nets {
_, allowedNet, _ := net.ParseCIDR(nets[i])
for _, allowedNet := range allowedNets {
if allowedNet.Contains(peerIP) {
return nil
}
}
log.WithFields(logrus.Fields{
"ip": peerIP,
}).Warn("Connection refused from address outside of allowed_nets")
return smtpd.Error{Code: 421, Message: "Denied"}
}
func addrAllowed(addr string, allowedAddrs []string) bool {
if allowedAddrs == nil {
// If absent, all addresses are allowed
return true
}
addr = strings.ToLower(addr)
// Extract optional domain part
domain := ""
if idx := strings.LastIndex(addr, "@"); idx != -1 {
domain = strings.ToLower(addr[idx+1:])
}
// Test each address from allowedUsers file
for _, allowedAddr := range allowedAddrs {
allowedAddr = strings.ToLower(allowedAddr)
// Three cases for allowedAddr format:
if idx := strings.Index(allowedAddr, "@"); idx == -1 {
// 1. local address (no @) -- must match exactly
if allowedAddr == addr {
return true
}
} else {
if idx != 0 {
// 2. email address (user@domain.com) -- must match exactly
if allowedAddr == addr {
return true
}
} else {
// 3. domain (@domain.com) -- must match addr domain
allowedDomain := allowedAddr[idx+1:]
if allowedDomain == domain {
return true
}
}
}
}
return false
}
func senderChecker(peer smtpd.Peer, addr string) error {
// check sender address from auth file if user is authenticated
if *allowedUsers != "" && peer.Username != "" {
_, email, err := AuthFetch(peer.Username)
if localAuthRequired() && 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,
"username": peer.Username,
}).WithError(err).Warn("could not fetch auth user")
return smtpd.Error{Code: 451, Message: "Bad sender address"}
}
if strings.ToLower(addr) != strings.ToLower(email) {
if !addrAllowed(addr, user.allowedAddresses) {
log.WithFields(logrus.Fields{
"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"}
}
}
if *allowedSender == "" {
if allowedSender == nil {
// Any sender is permitted
return nil
}
re, err := regexp.Compile(*allowedSender)
if err != nil {
log.Printf("allowed_sender invalid: %v\n", err)
return smtpd.Error{Code: 451, Message: "Bad sender address"}
}
if re.MatchString(addr) {
if allowedSender.MatchString(addr) {
// Permitted by regex
return nil
}
log.WithFields(logrus.Fields{
"sender_address": addr,
"peer": peer.Addr,
}).Warn("sender address not allowed by allowed_sender pattern")
return smtpd.Error{Code: 451, Message: "Bad sender address"}
}
func recipientChecker(peer smtpd.Peer, addr string) error {
if *allowedRecipients == "" {
if allowedRecipients == nil {
// Any recipient is permitted
return nil
}
re, err := regexp.Compile(*allowedRecipients)
if err != nil {
log.Printf("allowed_recipients invalid: %v\n", err)
return smtpd.Error{Code: 451, Message: "Bad recipient address"}
}
if re.MatchString(addr) {
if allowedRecipients.MatchString(addr) {
// Permitted by regex
return nil
}
log.WithFields(logrus.Fields{
"peer": peer.Addr,
"recipient_address": addr,
}).Warn("recipient address not allowed by allowed_recipients pattern")
return smtpd.Error{Code: 451, Message: "Bad recipient address"}
}
func authChecker(peer smtpd.Peer, username string, password string) error {
err := AuthCheckPassword(username, password)
if err != nil {
log.Printf("Auth error: %v\n", err)
log.WithFields(logrus.Fields{
"peer": peer.Addr,
"username": username,
}).WithError(err).Warn("auth error")
return smtpd.Error{Code: 535, Message: "Authentication credentials invalid"}
}
return nil
@@ -99,26 +155,22 @@ func mailHandler(peer smtpd.Peer, env smtpd.Envelope) error {
peerIP = addr.IP.String()
}
log.Printf("new mail from=<%s> to=%s peer=[%s]\n", env.Sender,
env.Recipients, peerIP)
logger := log.WithFields(logrus.Fields{
"from": env.Sender,
"to": env.Recipients,
"peer": peerIP,
"host": *remoteHost,
"uuid": generateUUID(),
})
var auth smtp.Auth
host, _, _ := net.SplitHostPort(*remoteHost)
if *remoteUser != "" && *remotePass != "" {
switch *remoteAuth {
case "plain":
auth = smtp.PlainAuth("", *remoteUser, *remotePass, host)
case "login":
auth = LoginAuth(*remoteUser, *remotePass)
default:
return smtpd.Error{Code: 530, Message: "Authentication method not supported"}
}
if (*remoteHost == "") {
logger.Warning("remote_host not set; discarding mail")
return nil
}
env.AddReceivedLine(peer)
logger.Info("delivering mail from peer using smarthost")
log.Printf("delivering using smarthost %s\n", *remoteHost)
env.AddReceivedLine(peer)
var sender string
@@ -130,22 +182,51 @@ func mailHandler(peer smtpd.Peer, env smtpd.Envelope) error {
err := SendMail(
*remoteHost,
auth,
remoteAuth,
sender,
env.Recipients,
env.Data,
)
if err != nil {
log.Printf("delivery failed: %v\n", err)
return smtpd.Error{Code: 554, Message: "Forwarding failed"}
var smtpError smtpd.Error
switch err.(type) {
case *textproto.Error:
err := err.(*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.WithError(err).
Error("delivery failed")
}
return smtpError
}
log.Printf("%s delivery successful\n", env.Recipients)
logger.Debug("delivery successful")
return nil
}
func main() {
func generateUUID() string {
uniqueID, err := uuid.NewRandom()
if err != nil {
log.WithError(err).
Error("could not generate UUIDv4")
return ""
}
return uniqueID.String()
}
func getTLSConfig() *tls.Config {
// Ciphersuites as defined in stock Go but without 3DES and RC4
// https://golang.org/src/crypto/tls/cipher_suites.go
var tlsCipherSuites = []uint16{
@@ -158,40 +239,57 @@ func main() {
tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,
tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256,
tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
tls.TLS_RSA_WITH_AES_128_GCM_SHA256, // does not provide PFS
tls.TLS_RSA_WITH_AES_256_GCM_SHA384, // does not provide PFS
tls.TLS_RSA_WITH_AES_128_CBC_SHA256,
tls.TLS_RSA_WITH_AES_128_CBC_SHA,
tls.TLS_RSA_WITH_AES_256_CBC_SHA,
}
if *localCert == "" || *localKey == "" {
log.WithFields(logrus.Fields{
"cert_file": *localCert,
"key_file": *localKey,
}).Fatal("TLS certificate/key file not defined in config")
}
cert, err := tls.LoadX509KeyPair(*localCert, *localKey)
if err != nil {
log.WithField("error", err).
Fatal("cannot load X509 keypair")
}
return &tls.Config{
PreferServerCipherSuites: true,
MinVersion: tls.VersionTLS12,
CipherSuites: tlsCipherSuites,
Certificates: []tls.Certificate{cert},
}
}
func main() {
ConfigLoad()
if *versionInfo {
fmt.Printf("smtprelay/%s\n", VERSION)
fmt.Printf("smtprelay/%s (%s)\n", appVersion, buildTime)
os.Exit(0)
}
if *logFile != "" {
f, err := os.OpenFile(*logFile, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0600)
if err != nil {
log.Fatalf("Error opening logfile: %v", err)
}
defer f.Close()
log.WithField("version", appVersion).
Debug("starting smtprelay")
log.SetOutput(io.MultiWriter(os.Stdout, f))
// Load allowed users file
if localAuthRequired() {
err := AuthLoadFile(*allowedUsers)
if err != nil {
log.WithField("file", *allowedUsers).
WithError(err).
Fatal("cannot load allowed users file")
}
}
listeners := strings.Split(*listen, " ")
var servers []*smtpd.Server
for i := range listeners {
listener := listeners[i]
// Create a server for each desired listen address
for _, listen := range listenAddrs {
logger := log.WithField("address", listen.address)
server := &smtpd.Server{
Hostname: *hostName,
@@ -202,80 +300,79 @@ func main() {
Handler: mailHandler,
}
if *allowedUsers != "" {
err := AuthLoadFile(*allowedUsers)
if err != nil {
log.Fatalf("Authentication file: %s\n", err)
}
if localAuthRequired() {
server.Authenticator = authChecker
}
if strings.Index(listeners[i], "://") == -1 {
log.Printf("Listen on %s ...\n", listener)
go server.ListenAndServe(listener)
} else if strings.HasPrefix(listeners[i], "starttls://") {
listener = strings.TrimPrefix(listener, "starttls://")
var lsnr net.Listener
var err error
if *localCert == "" || *localKey == "" {
log.Fatal("TLS certificate/key not defined in config")
}
switch listen.protocol {
case "":
logger.Info("listening on address")
lsnr, err = net.Listen("tcp", listen.address)
cert, err := tls.LoadX509KeyPair(*localCert, *localKey)
if err != nil {
log.Fatal(err)
}
server.TLSConfig = &tls.Config{
PreferServerCipherSuites: true,
MinVersion: tls.VersionTLS11,
CipherSuites: tlsCipherSuites,
Certificates: []tls.Certificate{cert},
}
case "starttls":
server.TLSConfig = getTLSConfig()
server.ForceTLS = *localForceTLS
log.Printf("Listen on %s (STARTSSL) ...\n", listener)
lsnr, err := net.Listen("tcp", listener)
if err != nil {
log.Fatal(err)
}
defer lsnr.Close()
logger.Info("listening on address (STARTTLS)")
lsnr, err = net.Listen("tcp", listen.address)
go server.Serve(lsnr)
} else if strings.HasPrefix(listeners[i], "tls://") {
case "tls":
server.TLSConfig = getTLSConfig()
listener = strings.TrimPrefix(listener, "tls://")
logger.Info("listening on address (TLS)")
lsnr, err = tls.Listen("tcp", listen.address, server.TLSConfig)
if *localCert == "" || *localKey == "" {
log.Fatal("TLS certificate/key not defined in config")
}
default:
logger.WithField("protocol", listen.protocol).
Fatal("unknown protocol in listen address")
}
cert, err := tls.LoadX509KeyPair(*localCert, *localKey)
if err != nil {
log.Fatal(err)
}
if err != nil {
logger.WithError(err).Fatal("error starting listener")
}
servers = append(servers, server)
server.TLSConfig = &tls.Config{
PreferServerCipherSuites: true,
MinVersion: tls.VersionTLS11,
CipherSuites: tlsCipherSuites,
Certificates: []tls.Certificate{cert},
}
go func() {
server.Serve(lsnr)
}()
}
log.Printf("Listen on %s (TLS) ...\n", listener)
lsnr, err := tls.Listen("tcp", listener, server.TLSConfig)
if err != nil {
log.Fatal(err)
}
defer lsnr.Close()
handleSignals()
go server.Serve(lsnr)
} else {
log.Fatal("Unknown protocol in listener ", listener)
// First close the listeners
for _, server := range servers {
logger := log.WithField("address", server.Address())
logger.Debug("Shutting down server")
err := server.Shutdown(false)
if err != nil {
logger.WithError(err).
Warning("Shutdown failed")
}
}
for true {
time.Sleep(time.Minute)
// Then wait for the clients to exit
for _, server := range servers {
logger := log.WithField("address", server.Address())
logger.Debug("Waiting for server")
err := server.Wait()
if err != nil {
logger.WithError(err).
Warning("Wait failed")
}
}
log.Debug("done")
}
func handleSignals() {
// Wait for SIGINT, SIGQUIT, or SIGTERM
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGQUIT, syscall.SIGTERM)
sig := <-sigs
log.WithField("signal", sig).
Info("shutting down in response to received signal")
}

94
main_test.go Normal file
View File

@@ -0,0 +1,94 @@
package main
import (
"testing"
)
func TestAddrAllowedNoDomain(t *testing.T) {
allowedAddrs := []string{"joe@abc.com"}
if addrAllowed("bob.com", allowedAddrs) {
t.FailNow()
}
}
func TestAddrAllowedSingle(t *testing.T) {
allowedAddrs := []string{"joe@abc.com"}
if !addrAllowed("joe@abc.com", allowedAddrs) {
t.FailNow()
}
if addrAllowed("bob@abc.com", allowedAddrs) {
t.FailNow()
}
}
func TestAddrAllowedDifferentCase(t *testing.T) {
allowedAddrs := []string{"joe@abc.com"}
testAddrs := []string{
"joe@ABC.com",
"Joe@abc.com",
"JOE@abc.com",
"JOE@ABC.COM",
}
for _, addr := range testAddrs {
if !addrAllowed(addr, allowedAddrs) {
t.Errorf("Address %v not allowed, but should be", addr)
}
}
}
func TestAddrAllowedLocal(t *testing.T) {
allowedAddrs := []string{"joe"}
if !addrAllowed("joe", allowedAddrs) {
t.FailNow()
}
if addrAllowed("bob", allowedAddrs) {
t.FailNow()
}
}
func TestAddrAllowedMulti(t *testing.T) {
allowedAddrs := []string{"joe@abc.com", "bob@def.com"}
if !addrAllowed("joe@abc.com", allowedAddrs) {
t.FailNow()
}
if !addrAllowed("bob@def.com", allowedAddrs) {
t.FailNow()
}
if addrAllowed("bob@abc.com", allowedAddrs) {
t.FailNow()
}
}
func TestAddrAllowedSingleDomain(t *testing.T) {
allowedAddrs := []string{"@abc.com"}
if !addrAllowed("joe@abc.com", allowedAddrs) {
t.FailNow()
}
if addrAllowed("joe@def.com", allowedAddrs) {
t.FailNow()
}
}
func TestAddrAllowedMixed(t *testing.T) {
allowedAddrs := []string{"app", "app@example.com", "@appsrv.example.com"}
if !addrAllowed("app", allowedAddrs) {
t.FailNow()
}
if !addrAllowed("app@example.com", allowedAddrs) {
t.FailNow()
}
if addrAllowed("ceo@example.com", allowedAddrs) {
t.FailNow()
}
if !addrAllowed("root@appsrv.example.com", allowedAddrs) {
t.FailNow()
}
if !addrAllowed("dev@appsrv.example.com", allowedAddrs) {
t.FailNow()
}
if addrAllowed("appsrv@example.com", allowedAddrs) {
t.FailNow()
}
}

View File

@@ -1,34 +0,0 @@
#!/bin/sh
PROJECT=smtprelay
VERSION=1.3.0
for goos in freebsd linux windows
do
for goarch in 386 amd64
do
export GOOS=${goos}
export GOARCH=${goarch}
RELDIR=${PROJECT}-${VERSION}-${GOOS}-${GOARCH}
rm -rf ${RELDIR}
mkdir ${RELDIR} || exit 1
cp -p README.md LICENSE ${PROJECT}.ini ${RELDIR}/ || exit 1
if [ ${GOOS} = "windows" ]; then
BINARY=${PROJECT}.exe
sed -I '' -e 's/;logfile =.*/logfile =/g' ${RELDIR}/${PROJECT}.ini
sed -I '' -e 's/$/^M/' ${RELDIR}/${PROJECT}.ini
else
BINARY=${PROJECT}
fi
go build -ldflags="-s -w" -o ${RELDIR}/${BINARY} || exit 1
chown -R root:wheel ${RELDIR} || exit 1
tar cvfJ ${RELDIR}.tar.xz ${RELDIR} || exit 1
rm -rf ${RELDIR}
done
done

View File

@@ -242,7 +242,8 @@ func (c *Client) Auth(a smtp.Auth) error {
// Mail issues a MAIL command to the server using the provided email address.
// If the server supports the 8BITMIME extension, Mail adds the BODY=8BITMIME
// parameter.
// parameter. If the server supports the SMTPUTF8 extension, Mail adds the
// SMTPUTF8 parameter.
// This initiates a mail transaction and is followed by one or more Rcpt calls.
func (c *Client) Mail(from string) error {
if err := validateLine(from); err != nil {
@@ -256,6 +257,9 @@ func (c *Client) Mail(from string) error {
if _, ok := c.ext["8BITMIME"]; ok {
cmdStr += " BODY=8BITMIME"
}
if _, ok := c.ext["SMTPUTF8"]; ok {
cmdStr += " SMTPUTF8"
}
}
_, _, err := c.cmd(250, cmdStr, from)
return err

View File

@@ -1,7 +1,13 @@
; smtprelay configuration
; Logfile
;logfile = /var/log/smtprelay.log
; Logfile (blank/default is stderr)
;logfile =
; Log format: default, plain (no timestamp), json
;log_format = "default"
; Log level: panic, fatal, error, warn, info, debug, trace
;log_level = "info"
; Hostname for this SMTP server
;hostname = "localhost.localdomain"
@@ -25,22 +31,33 @@
;local_forcetls = false
; Networks that are allowed to send mails to us
;allowed_nets = 127.0.0.1/8 ::1/128
; Defaults to localhost. If set to "", then any address is allowed.
;allowed_nets = 127.0.0.0/8 ::1/128
; Regular expression for valid FROM EMail adresses
; Regular expression for valid FROM EMail addresses
; If set to "", then any sender is permitted.
; Example: ^(.*)@localhost.localdomain$
;allowed_sender =
; Regular expression for valid TO EMail adresses
; Regular expression for valid TO EMail addresses
; If set to "", then any recipient is permitted.
; Example: ^(.*)@localhost.localdomain$
;allowed_recipients =
; File which contains username and password used for
; authentication before they can send mail.
; File format: username bcrypt-hash email
; File format: username bcrypt-hash [email[,email[,...]]]
; username: The SMTP auth username
; bcrypt-hash: The bcrypt hash of the pasword (generate with "./hasher password")
; email: Comma-separated list of allowed "from" addresses:
; - If omitted, user can send from any address
; - If @domain.com is given, user can send from any address @domain.com
; - Otherwise, email address must match exactly (case-insensitive)
; E.g. "app@example.com,@appsrv.example.com"
;allowed_users =
; Relay all mails to this SMTP server
; Relay all mails to this SMTP server.
; If not set, mails are discarded.
; GMail
;remote_host = smtp.gmail.com:587
@@ -56,8 +73,8 @@
;remote_pass =
; Authentication method on outgoing SMTP server
; (plain, login)
;remote_auth = plain
; (none, plain, login)
;remote_auth = none
; Sender e-mail address on outgoing SMTP server
;remote_sender =