mirror of
https://github.com/decke/smtprelay.git
synced 2025-12-25 07:43:06 -07:00
Compare commits
84 Commits
v1.2.0
...
add-servic
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
190c615029 | ||
|
|
42abf27c1f | ||
|
|
1b7b551f65 | ||
|
|
2cd636c082 | ||
|
|
3debf4127d | ||
|
|
03b8b78f53 | ||
|
|
49c6880175 | ||
|
|
5470132251 | ||
|
|
898f8e44cf | ||
|
|
22ef0c2ee6 | ||
|
|
8eea677a3d | ||
|
|
9f2497d948 | ||
|
|
76ef135d33 | ||
|
|
7c0ba34025 | ||
|
|
a896ab2847 | ||
|
|
c9b55b833b | ||
|
|
918df65a3a | ||
|
|
0503c12ccd | ||
|
|
ef3f9c8ea0 | ||
|
|
4036213dd5 | ||
|
|
2475cadbad | ||
|
|
20ca816160 | ||
|
|
d1933a2e35 | ||
|
|
9921b38046 | ||
|
|
095fba119a | ||
|
|
34cb47c364 | ||
|
|
b36ed8eddb | ||
|
|
822dbbce7d | ||
|
|
42f5c68f0b | ||
|
|
cd2dab8f8f | ||
|
|
f2af99dc52 | ||
|
|
23e10bb03e | ||
|
|
5ba64c5c6e | ||
|
|
7f34fcbc99 | ||
|
|
97943c87e7 | ||
|
|
fefeccec39 | ||
|
|
c781938999 | ||
|
|
009ae8f73a | ||
|
|
70dfe6b128 | ||
|
|
7fa0eebf95 | ||
|
|
ecf830865c | ||
|
|
4fd6bb1004 | ||
|
|
fd3f513b18 | ||
|
|
b202a2209e | ||
|
|
0e8986ca79 | ||
|
|
5c2e28ac36 | ||
|
|
f33105f83c | ||
|
|
9040a456cf | ||
|
|
d5c5e25d03 | ||
|
|
999cfea307 | ||
|
|
f166c13350 | ||
|
|
ed1c3a9888 | ||
|
|
6f3bd16988 | ||
|
|
4e0bf0908d | ||
|
|
6662fb7155 | ||
|
|
076fd65dea | ||
|
|
880c3c365c | ||
|
|
36673ae3f0 | ||
|
|
b42ad6ddc9 | ||
|
|
999ccab778 | ||
|
|
53c2c27647 | ||
|
|
2afbe67407 | ||
|
|
00b96161b3 | ||
|
|
e10cbcdbb0 | ||
|
|
0e643f7230 | ||
|
|
324585c63c | ||
|
|
92cb02e46b | ||
|
|
62fcc11f61 | ||
|
|
bfe8d39bb3 | ||
|
|
cbb6f523c5 | ||
|
|
eb4a6b9eb6 | ||
|
|
45db4ef786 | ||
|
|
946effcbcf | ||
|
|
118d1b88c2 | ||
|
|
5fd6aad9b1 | ||
|
|
21b597f351 | ||
|
|
5f82b4736c | ||
|
|
de430286b3 | ||
|
|
769193ea4d | ||
|
|
0b65e904d8 | ||
|
|
2c9645ac68 | ||
|
|
770e819e2b | ||
|
|
d11f8d81ea | ||
|
|
6270d75571 |
11
.github/dependabot.yml
vendored
Normal file
11
.github/dependabot.yml
vendored
Normal 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
66
.github/workflows/codeql-analysis.yml
vendored
Normal 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
|
||||
24
.github/workflows/go.yml
vendored
Normal file
24
.github/workflows/go.yml
vendored
Normal file
@@ -0,0 +1,24 @@
|
||||
name: Go
|
||||
on: [push]
|
||||
jobs:
|
||||
|
||||
build:
|
||||
name: Build
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
|
||||
- name: Set up Go 1.15
|
||||
uses: actions/setup-go@v2.1.3
|
||||
with:
|
||||
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 .
|
||||
30
.github/workflows/release.yaml
vendored
Normal file
30
.github/workflows/release.yaml
vendored
Normal 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.15
|
||||
with:
|
||||
github_token: ${{ secrets.GITHUB_TOKEN }}
|
||||
goos: ${{ matrix.goos }}
|
||||
goarch: ${{ matrix.goarch }}
|
||||
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 }}"
|
||||
@@ -1,5 +1,7 @@
|
||||
# smtprelay
|
||||
|
||||
[](https://goreportcard.com/report/github.com/decke/smtprelay)
|
||||
|
||||
Simple Golang based SMTP relay/proxy server that accepts mail via SMTP
|
||||
and forwards it directly to another SMTP server.
|
||||
|
||||
|
||||
58
auth.go
58
auth.go
@@ -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,41 +34,67 @@ func AuthReady() bool {
|
||||
return (filename != "")
|
||||
}
|
||||
|
||||
func AuthFetch(username string) (string, string, error) {
|
||||
if ! AuthReady() {
|
||||
return "", "", errors.New("Authentication file not specified. Call LoadFile() first")
|
||||
// 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 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
89
auth_test.go
Normal 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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
6
cmd/README.md
Normal file
6
cmd/README.md
Normal file
@@ -0,0 +1,6 @@
|
||||
|
||||
To run the hasher, do like this
|
||||
|
||||
```bash
|
||||
$ go run hasher.go hunter2
|
||||
```
|
||||
22
cmd/hasher.go
Normal file
22
cmd/hasher.go
Normal file
@@ -0,0 +1,22 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
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.Fprintln(os.Stderr, "Error generating hash: %s", err)
|
||||
}
|
||||
fmt.Println(string(hash))
|
||||
}
|
||||
151
config.go
151
config.go
@@ -2,32 +2,145 @@ package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"net"
|
||||
"regexp"
|
||||
"net/smtp"
|
||||
|
||||
"github.com/vharitonsky/iniflags"
|
||||
)
|
||||
|
||||
const (
|
||||
VERSION = "1.2.0"
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
var (
|
||||
logFile = flag.String("logfile", "/var/log/smtprelay.log", "Path to logfile")
|
||||
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)")
|
||||
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")
|
||||
allowedUsers = flag.String("allowed_users", "", "Path to file with valid users/passwords")
|
||||
remoteHost = flag.String("remote_host", "smtp.gmail.com:587", "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")
|
||||
versionInfo= flag.Bool("version", false, "Show version information")
|
||||
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")
|
||||
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
|
||||
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 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")
|
||||
}
|
||||
}
|
||||
|
||||
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()
|
||||
}
|
||||
|
||||
10
go.mod
10
go.mod
@@ -1,7 +1,11 @@
|
||||
module code.bluelife.at/decke/smtprelay
|
||||
module github.com/decke/smtprelay
|
||||
|
||||
require (
|
||||
github.com/chrj/smtpd v0.1.2
|
||||
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-20181203042331-505ab145d0a9
|
||||
golang.org/x/crypto v0.0.0-20201221181555-eec23a3978ad
|
||||
)
|
||||
|
||||
go 1.13
|
||||
|
||||
25
go.sum
25
go.sum
@@ -1,7 +1,24 @@
|
||||
github.com/chrj/smtpd v0.1.2 h1:yWaMOCmnPlcNgJzkak1TBhhkObAfomd+NmZG5epdO88=
|
||||
github.com/chrj/smtpd v0.1.2/go.mod h1:jt4ydELuZmqhn9hn3YpEPV1dY00aOB+Q1nWXnBDFKeY=
|
||||
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-20181203042331-505ab145d0a9 h1:mKdxBk7AujPs8kU4m80U72y/zjbZ3UcXC7dClwKbUI0=
|
||||
golang.org/x/crypto v0.0.0-20181203042331-505ab145d0a9/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
|
||||
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=
|
||||
|
||||
60
logger.go
Normal file
60
logger.go
Normal 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)
|
||||
}
|
||||
374
main.go
374
main.go
@@ -3,161 +3,292 @@ 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)
|
||||
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
|
||||
}
|
||||
|
||||
func mailHandler(peer smtpd.Peer, env smtpd.Envelope) error {
|
||||
if *allowedUsers != "" && peer.Username == "" {
|
||||
return smtpd.Error{Code: 530, Message: "Authentication Required"}
|
||||
}
|
||||
|
||||
peerIP := ""
|
||||
if addr, ok := peer.Addr.(*net.TCPAddr); ok {
|
||||
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 != "" {
|
||||
auth = smtp.PlainAuth("", *remoteUser, *remotePass, host)
|
||||
if (*remoteHost == "") {
|
||||
logger.Warning("remote_host not set; discarding mail")
|
||||
return nil
|
||||
}
|
||||
|
||||
logger.Info("delivering mail from peer using smarthost")
|
||||
|
||||
env.AddReceivedLine(peer)
|
||||
|
||||
log.Printf("delivering using smarthost %s\n", *remoteHost)
|
||||
var sender string
|
||||
|
||||
if *remoteSender == "" {
|
||||
sender = env.Sender
|
||||
} else {
|
||||
sender = *remoteSender
|
||||
}
|
||||
|
||||
err := SendMail(
|
||||
*remoteHost,
|
||||
auth,
|
||||
env.Sender,
|
||||
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{
|
||||
tls.TLS_AES_128_GCM_SHA256,
|
||||
tls.TLS_AES_256_GCM_SHA384,
|
||||
tls.TLS_CHACHA20_POLY1305_SHA256,
|
||||
tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
|
||||
tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256,
|
||||
tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
|
||||
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_RSA_WITH_AES_128_GCM_SHA256, // does not provide PFS
|
||||
tls.TLS_RSA_WITH_AES_256_GCM_SHA384, // does not provide PFS
|
||||
}
|
||||
|
||||
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 *allowedUsers != "" {
|
||||
err := AuthLoadFile(*allowedUsers)
|
||||
if err != nil {
|
||||
log.WithField("file", *allowedUsers).
|
||||
WithError(err).
|
||||
Fatal("cannot load allowed users file")
|
||||
}
|
||||
}
|
||||
|
||||
listeners := strings.Split(*listen, " ")
|
||||
|
||||
for i := range(listeners) {
|
||||
listener := listeners[i]
|
||||
var servers []*smtpd.Server
|
||||
|
||||
// Create a server for each desired listen address
|
||||
for _, listenAddr := range strings.Split(*listen, " ") {
|
||||
server := &smtpd.Server{
|
||||
Hostname: *hostName,
|
||||
WelcomeMessage: *welcomeMsg,
|
||||
@@ -168,67 +299,84 @@ func main() {
|
||||
}
|
||||
|
||||
if *allowedUsers != "" {
|
||||
err := AuthLoadFile(*allowedUsers)
|
||||
if err != nil {
|
||||
log.Fatalf("Authentication file: %s\n", err)
|
||||
}
|
||||
|
||||
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")
|
||||
}
|
||||
if strings.Index(listenAddr, "://") == -1 {
|
||||
log.WithField("address", listenAddr).
|
||||
Info("listening on address")
|
||||
|
||||
cert, err := tls.LoadX509KeyPair(*localCert, *localKey)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
lsnr, err = net.Listen("tcp", listenAddr)
|
||||
} else if strings.HasPrefix(listenAddr, "starttls://") {
|
||||
listenAddr = strings.TrimPrefix(listenAddr, "starttls://")
|
||||
|
||||
server.TLSConfig = &tls.Config {
|
||||
Certificates: [] tls.Certificate{cert},
|
||||
}
|
||||
server.TLSConfig = getTLSConfig()
|
||||
server.ForceTLS = *localForceTLS
|
||||
|
||||
log.Printf("Listen on %s (STARTSSL) ...\n", listener)
|
||||
lsnr, err := net.Listen("tcp", listener)
|
||||
defer lsnr.Close()
|
||||
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://")
|
||||
|
||||
go server.Serve(lsnr)
|
||||
} else if strings.HasPrefix(listeners[i], "tls://") {
|
||||
server.TLSConfig = getTLSConfig()
|
||||
|
||||
listener = strings.TrimPrefix(listener, "tls://")
|
||||
|
||||
if *localCert == "" || *localKey == "" {
|
||||
log.Fatal("TLS certificate/key not defined in config")
|
||||
}
|
||||
|
||||
cert, err := tls.LoadX509KeyPair(*localCert, *localKey)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
server.TLSConfig = &tls.Config {
|
||||
Certificates: [] tls.Certificate{cert},
|
||||
}
|
||||
|
||||
log.Printf("Listen on %s (TLS) ...\n", listener)
|
||||
lsnr, err := tls.Listen("tcp", listener, server.TLSConfig)
|
||||
defer lsnr.Close()
|
||||
|
||||
go server.Serve(lsnr)
|
||||
log.WithField("address", listenAddr).
|
||||
Info("listening on address (TLS)")
|
||||
lsnr, err = tls.Listen("tcp", listenAddr, server.TLSConfig)
|
||||
} else {
|
||||
log.Fatal("Unknown protocol in listener ", listener)
|
||||
log.WithField("address", listenAddr).
|
||||
Fatal("unknown protocol in listen address")
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
log.WithFields(logrus.Fields{
|
||||
"address": listenAddr,
|
||||
}).WithError(err).Fatal("error starting listener")
|
||||
}
|
||||
servers = append(servers, server)
|
||||
|
||||
go func() {
|
||||
server.Serve(lsnr)
|
||||
}()
|
||||
}
|
||||
|
||||
handleSignals()
|
||||
|
||||
// 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
94
main_test.go
Normal 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()
|
||||
}
|
||||
}
|
||||
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
|
||||
33
smtp.go
33
smtp.go
@@ -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
|
||||
@@ -451,3 +455,30 @@ func validateLine(line string) error {
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// LOGIN authentication
|
||||
type loginAuth struct {
|
||||
username, password string
|
||||
}
|
||||
|
||||
func LoginAuth(username, password string) smtp.Auth {
|
||||
return &loginAuth{username, password}
|
||||
}
|
||||
|
||||
func (a *loginAuth) Start(server *smtp.ServerInfo) (string, []byte, error) {
|
||||
return "LOGIN", []byte{}, nil
|
||||
}
|
||||
|
||||
func (a *loginAuth) Next(fromServer []byte, more bool) ([]byte, error) {
|
||||
if more {
|
||||
switch string(fromServer) {
|
||||
case "Username:":
|
||||
return []byte(a.username), nil
|
||||
case "Password:":
|
||||
return []byte(a.password), nil
|
||||
default:
|
||||
return nil, errors.New("Unknown fromServer")
|
||||
}
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
@@ -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
|
||||
@@ -54,3 +71,10 @@
|
||||
; Authentication credentials on outgoing SMTP server
|
||||
;remote_user =
|
||||
;remote_pass =
|
||||
|
||||
; Authentication method on outgoing SMTP server
|
||||
; (none, plain, login)
|
||||
;remote_auth = none
|
||||
|
||||
; Sender e-mail address on outgoing SMTP server
|
||||
;remote_sender =
|
||||
|
||||
Reference in New Issue
Block a user