mirror of
https://github.com/decke/smtprelay.git
synced 2025-12-26 08:52:33 -07:00
Compare commits
160 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
813bd9ebe7 | ||
|
|
ee8a5dd989 | ||
|
|
6602836166 | ||
|
|
cdc0fe931b | ||
|
|
e5f27e02e5 | ||
|
|
dffe0bb5bb | ||
|
|
20ad1e84f9 | ||
|
|
db1238bf2d | ||
|
|
d9167eece5 | ||
|
|
e98a1c6f25 | ||
|
|
f0aefc194d | ||
|
|
bfd156e5f3 | ||
|
|
682feef610 | ||
|
|
eea3c4edaa | ||
|
|
cf25c2d0a0 | ||
|
|
774651b0f6 | ||
|
|
5cd3729b1f | ||
|
|
5b38a30349 | ||
|
|
d7585bec9b | ||
|
|
c8f62e42c8 | ||
|
|
00df491340 | ||
|
|
1bf205e7d8 | ||
|
|
c83544bd90 | ||
|
|
e3ba45ede2 | ||
|
|
f69d1f0114 | ||
|
|
e9a2b9ad5a | ||
|
|
7e3dbd515d | ||
|
|
8cc31a918b | ||
|
|
26477177fe | ||
|
|
44560c9a0c | ||
|
|
c21c13cc7a | ||
|
|
1617155f1e | ||
|
|
81ea0c7944 | ||
|
|
d9a09a20da | ||
|
|
d5d4e7a821 | ||
|
|
77ab4485b2 | ||
|
|
ce97293e33 | ||
|
|
5cd81cd7e4 | ||
|
|
62bb2becbc | ||
|
|
a2826e949e | ||
|
|
64872c0bea | ||
|
|
cdc4e572db | ||
|
|
5e78bbe643 | ||
|
|
b134e426d7 | ||
|
|
9c230182da | ||
|
|
39b8e01226 | ||
|
|
bf8c222ac1 | ||
|
|
875264837e | ||
|
|
32d0206af0 | ||
|
|
b7f3701502 | ||
|
|
cf927508dd | ||
|
|
4221919689 | ||
|
|
4f1148d77b | ||
|
|
32c43efd0c | ||
|
|
362a64dd8a | ||
|
|
bf58b2b4c8 | ||
|
|
ed13816dcd | ||
|
|
dd7905e60e | ||
|
|
5076988ddf | ||
|
|
dafbc327aa | ||
|
|
48926964bf | ||
|
|
5757db3a37 | ||
|
|
a527a147be | ||
|
|
8c0a6aab20 | ||
|
|
5be2f3aa4b | ||
|
|
2b046297ea | ||
|
|
f0d39401d4 | ||
|
|
b5fcf8e0bb | ||
|
|
016ef762fb | ||
|
|
6afc87968c | ||
|
|
b32b5690bf | ||
|
|
38aa05c9f4 | ||
|
|
03d109ff8b | ||
|
|
6c691f3cea | ||
|
|
c6b5e244eb | ||
|
|
0ee982ea31 | ||
|
|
287395ad91 | ||
|
|
3aecd3c6d6 | ||
|
|
f8960053e8 | ||
|
|
db5512d47b | ||
|
|
fd063ad879 | ||
|
|
85bdd060e3 | ||
|
|
5be6165865 | ||
|
|
b64a34becf | ||
|
|
a2ea5ab49e | ||
|
|
94957d944f | ||
|
|
a5db5e1ff5 | ||
|
|
94776b27d9 | ||
|
|
81bc7addc7 | ||
|
|
e9bfe53f18 | ||
|
|
32032c297c | ||
|
|
53e52de279 | ||
|
|
02810c0a50 | ||
|
|
6b21f52037 | ||
|
|
544bd081ff | ||
|
|
6a28f939de | ||
|
|
f0392bdf09 | ||
|
|
3f627d3281 | ||
|
|
d8860fc917 | ||
|
|
ebb53ea1b6 | ||
|
|
a5ee525825 | ||
|
|
441a53cfd9 | ||
|
|
7b199cc6ae | ||
|
|
184d5f8611 | ||
|
|
9e8b5517a6 | ||
|
|
65f0cfcfbd | ||
|
|
410c70d86f | ||
|
|
247d187576 | ||
|
|
45a676e274 | ||
|
|
ca1ccd85e3 | ||
|
|
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 |
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@v3
|
||||||
|
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@v2
|
||||||
|
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@v2
|
||||||
|
|
||||||
|
# ℹ️ 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@v2
|
||||||
13
.github/workflows/go.yml
vendored
13
.github/workflows/go.yml
vendored
@@ -1,5 +1,5 @@
|
|||||||
name: Go
|
name: Go
|
||||||
on: [push]
|
on: [push, pull_request]
|
||||||
jobs:
|
jobs:
|
||||||
|
|
||||||
build:
|
build:
|
||||||
@@ -7,14 +7,14 @@ jobs:
|
|||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
|
|
||||||
- name: Set up Go 1.14
|
- name: Set up Go 1.18
|
||||||
uses: actions/setup-go@v1
|
uses: actions/setup-go@v3
|
||||||
with:
|
with:
|
||||||
go-version: 1.14
|
go-version: 1.18
|
||||||
id: go
|
id: go
|
||||||
|
|
||||||
- name: Check out code into the Go module directory
|
- name: Check out code into the Go module directory
|
||||||
uses: actions/checkout@v1
|
uses: actions/checkout@v3
|
||||||
|
|
||||||
- name: Get dependencies
|
- name: Get dependencies
|
||||||
run: |
|
run: |
|
||||||
@@ -22,3 +22,6 @@ jobs:
|
|||||||
|
|
||||||
- name: Build
|
- name: Build
|
||||||
run: go build -v .
|
run: go build -v .
|
||||||
|
|
||||||
|
- name: Test
|
||||||
|
run: go test -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: [amd64, arm64]
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v3
|
||||||
|
|
||||||
|
- 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.30
|
||||||
|
with:
|
||||||
|
github_token: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
goos: ${{ matrix.goos }}
|
||||||
|
goarch: ${{ matrix.goarch }}
|
||||||
|
goversion: 1.18
|
||||||
|
extra_files: LICENSE README.md smtprelay.ini
|
||||||
|
ldflags: -s -w -X "main.appVersion=${{ env.APP_VERSION }}" -X "main.buildTime=${{ env.BUILD_TIME }}"
|
||||||
@@ -16,16 +16,17 @@ configure.
|
|||||||
|
|
||||||
My use case is simple. I need to send automatically generated mails from
|
My use case is simple. I need to send automatically generated mails from
|
||||||
cron via msmtp/sSMTP/dma, mails from various services and network printers
|
cron via msmtp/sSMTP/dma, mails from various services and network printers
|
||||||
to GMail without giving away my GMail credentials to each device which
|
via a remote SMTP server without giving away my mail credentials to each
|
||||||
produces mail.
|
device which produces mail.
|
||||||
|
|
||||||
|
|
||||||
## Main features
|
## Main features
|
||||||
|
|
||||||
|
* Simple configuration with ini file .env file or environment variables
|
||||||
* Supports SMTPS/TLS (465), STARTTLS (587) and unencrypted SMTP (25)
|
* Supports SMTPS/TLS (465), STARTTLS (587) and unencrypted SMTP (25)
|
||||||
* Checks for sender, receiver, client IP
|
* Checks for sender, receiver, client IP
|
||||||
* Authentication support with file (LOGIN, PLAIN)
|
* Authentication support with file (LOGIN, PLAIN)
|
||||||
* Enforce encryption for authentication
|
* Enforce encryption for authentication
|
||||||
* Forwards all mail to a smarthost (GMail, MailGun or any other SMTP server)
|
* Forwards all mail to a smarthost (any SMTP server)
|
||||||
* Small codebase
|
* Small codebase
|
||||||
* IPv6 support
|
* IPv6 support
|
||||||
|
|||||||
57
auth.go
57
auth.go
@@ -13,6 +13,12 @@ var (
|
|||||||
filename string
|
filename string
|
||||||
)
|
)
|
||||||
|
|
||||||
|
type AuthUser struct {
|
||||||
|
username string
|
||||||
|
passwordHash string
|
||||||
|
allowedAddresses []string
|
||||||
|
}
|
||||||
|
|
||||||
func AuthLoadFile(file string) error {
|
func AuthLoadFile(file string) error {
|
||||||
f, err := os.Open(file)
|
f, err := os.Open(file)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -28,39 +34,66 @@ func AuthReady() bool {
|
|||||||
return (filename != "")
|
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() {
|
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)
|
file, err := os.Open(filename)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", "", err
|
return nil, err
|
||||||
}
|
}
|
||||||
defer file.Close()
|
defer file.Close()
|
||||||
|
|
||||||
scanner := bufio.NewScanner(file)
|
scanner := bufio.NewScanner(file)
|
||||||
for scanner.Scan() {
|
for scanner.Scan() {
|
||||||
parts := strings.Fields(scanner.Text())
|
user := parseLine(scanner.Text())
|
||||||
|
if user == nil {
|
||||||
if len(parts) != 3 {
|
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
if strings.ToLower(username) == strings.ToLower(parts[0]) {
|
if strings.ToLower(username) != strings.ToLower(user.username) {
|
||||||
return parts[1], parts[2], nil
|
continue
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return "", "", errors.New("User not found")
|
return user, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil, errors.New("User not found")
|
||||||
}
|
}
|
||||||
|
|
||||||
func AuthCheckPassword(username string, secret string) error {
|
func AuthCheckPassword(username string, secret string) error {
|
||||||
hash, _, err := AuthFetch(username)
|
user, err := AuthFetch(username)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if bcrypt.CompareHashAndPassword([]byte(hash), []byte(secret)) == nil {
|
if bcrypt.CompareHashAndPassword([]byte(user.passwordHash), []byte(secret)) == nil {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
return errors.New("Password invalid")
|
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)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -8,11 +8,15 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
|
if len(os.Args) != 2 {
|
||||||
|
fmt.Fprintln(os.Stderr, "Usage: hasher PASSWORD")
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
password := os.Args[1]
|
password := os.Args[1]
|
||||||
|
|
||||||
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Println("Error generating hash: %s", err)
|
fmt.Fprintln(os.Stderr, "Error generating hash: %s", err)
|
||||||
}
|
}
|
||||||
fmt.Println(string(hash))
|
fmt.Println(string(hash))
|
||||||
}
|
}
|
||||||
|
|||||||
288
config.go
288
config.go
@@ -1,35 +1,275 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bufio"
|
||||||
"flag"
|
"flag"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net"
|
||||||
|
"os"
|
||||||
|
"regexp"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
"github.com/vharitonsky/iniflags"
|
"github.com/peterbourgon/ff/v3"
|
||||||
)
|
"github.com/sirupsen/logrus"
|
||||||
|
|
||||||
const (
|
|
||||||
VERSION = "1.3.0"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
logFile = flag.String("logfile", "/var/log/smtprelay.log", "Path to logfile")
|
appVersion = "unknown"
|
||||||
hostName = flag.String("hostname", "localhost.localdomain", "Server hostname")
|
buildTime = "unknown"
|
||||||
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")
|
|
||||||
remoteAuth = flag.String("remote_auth", "plain", "Auth method on outgoing SMTP server (plain, login)")
|
|
||||||
remoteSender = flag.String("remote_sender", "", "Sender e-mail address on outgoing SMTP server")
|
|
||||||
versionInfo = flag.Bool("version", false, "Show version information")
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func ConfigLoad() {
|
var (
|
||||||
iniflags.Parse()
|
flagset = flag.NewFlagSet("smtprelay", flag.ContinueOnError)
|
||||||
|
|
||||||
|
// config flags
|
||||||
|
logFile = flagset.String("logfile", "", "Path to logfile")
|
||||||
|
logFormat = flagset.String("log_format", "default", "Log output format")
|
||||||
|
logLevel = flagset.String("log_level", "info", "Minimum log level to output")
|
||||||
|
hostName = flagset.String("hostname", "localhost.localdomain", "Server hostname")
|
||||||
|
welcomeMsg = flagset.String("welcome_msg", "", "Welcome message for SMTP session")
|
||||||
|
listenStr = flagset.String("listen", "127.0.0.1:25 [::1]:25", "Address and port to listen for incoming SMTP")
|
||||||
|
localCert = flagset.String("local_cert", "", "SSL certificate for STARTTLS/TLS")
|
||||||
|
localKey = flagset.String("local_key", "", "SSL private key for STARTTLS/TLS")
|
||||||
|
localForceTLS = flagset.Bool("local_forcetls", false, "Force STARTTLS (needs local_cert and local_key)")
|
||||||
|
readTimeoutStr = flagset.String("read_timeout", "60s", "Socket timeout for read operations")
|
||||||
|
writeTimeoutStr = flagset.String("write_timeout", "60s", "Socket timeout for write operations")
|
||||||
|
dataTimeoutStr = flagset.String("data_timeout", "5m", "Socket timeout for DATA command")
|
||||||
|
maxConnections = flagset.Int("max_connections", 100, "Max concurrent connections, use -1 to disable")
|
||||||
|
maxMessageSize = flagset.Int("max_message_size", 10240000, "Max message size in bytes")
|
||||||
|
maxRecipients = flagset.Int("max_recipients", 100, "Max RCPT TO calls for each envelope")
|
||||||
|
allowedNetsStr = flagset.String("allowed_nets", "127.0.0.0/8 ::1/128", "Networks allowed to send mails")
|
||||||
|
allowedSenderStr = flagset.String("allowed_sender", "", "Regular expression for valid FROM EMail addresses")
|
||||||
|
allowedRecipStr = flagset.String("allowed_recipients", "", "Regular expression for valid TO EMail addresses")
|
||||||
|
allowedUsers = flagset.String("allowed_users", "", "Path to file with valid users/passwords")
|
||||||
|
command = flagset.String("command", "", "Path to pipe command")
|
||||||
|
remotesStr = flagset.String("remotes", "", "Outgoing SMTP servers")
|
||||||
|
|
||||||
|
// additional flags
|
||||||
|
_ = flagset.String("config", "", "Path to config file (ini format)")
|
||||||
|
versionInfo = flagset.Bool("version", false, "Show version information")
|
||||||
|
|
||||||
|
// internal
|
||||||
|
listenAddrs = []protoAddr{}
|
||||||
|
readTimeout time.Duration
|
||||||
|
writeTimeout time.Duration
|
||||||
|
dataTimeout time.Duration
|
||||||
|
allowedNets = []*net.IPNet{}
|
||||||
|
allowedSender *regexp.Regexp
|
||||||
|
allowedRecipients *regexp.Regexp
|
||||||
|
remotes = []*Remote{}
|
||||||
|
)
|
||||||
|
|
||||||
|
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 setupRemotes() {
|
||||||
|
logger := log.WithField("remotes", *remotesStr)
|
||||||
|
|
||||||
|
if *remotesStr != "" {
|
||||||
|
for _, remoteURL := range strings.Split(*remotesStr, " ") {
|
||||||
|
r, err := ParseRemote(remoteURL)
|
||||||
|
if err != nil {
|
||||||
|
logger.Fatal(fmt.Sprintf("error parsing url: '%s': %v", remoteURL, err))
|
||||||
|
}
|
||||||
|
|
||||||
|
remotes = append(remotes, r)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type protoAddr struct {
|
||||||
|
protocol string
|
||||||
|
address string
|
||||||
|
}
|
||||||
|
|
||||||
|
func splitProto(s string) protoAddr {
|
||||||
|
idx := strings.Index(s, "://")
|
||||||
|
if idx == -1 {
|
||||||
|
return protoAddr{
|
||||||
|
address: s,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return protoAddr{
|
||||||
|
protocol: s[0:idx],
|
||||||
|
address: s[idx+3:],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func setupListeners() {
|
||||||
|
for _, listenAddr := range strings.Split(*listenStr, " ") {
|
||||||
|
pa := splitProto(listenAddr)
|
||||||
|
|
||||||
|
if localAuthRequired() && pa.protocol == "" {
|
||||||
|
log.WithField("address", pa.address).
|
||||||
|
Fatal("Local authentication (via allowed_users file) " +
|
||||||
|
"not allowed with non-TLS listener")
|
||||||
|
}
|
||||||
|
|
||||||
|
listenAddrs = append(listenAddrs, pa)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func setupTimeouts() {
|
||||||
|
var err error
|
||||||
|
|
||||||
|
readTimeout, err = time.ParseDuration(*readTimeoutStr)
|
||||||
|
if err != nil {
|
||||||
|
log.WithField("read_timeout", *readTimeoutStr).
|
||||||
|
WithError(err).
|
||||||
|
Fatal("read_timeout duration string invalid")
|
||||||
|
}
|
||||||
|
if readTimeout.Seconds() < 1 {
|
||||||
|
log.WithField("read_timeout", *readTimeoutStr).
|
||||||
|
Fatal("read_timeout less than one second")
|
||||||
|
}
|
||||||
|
|
||||||
|
writeTimeout, err = time.ParseDuration(*writeTimeoutStr)
|
||||||
|
if err != nil {
|
||||||
|
log.WithField("write_timeout", *writeTimeoutStr).
|
||||||
|
WithError(err).
|
||||||
|
Fatal("write_timeout duration string invalid")
|
||||||
|
}
|
||||||
|
if writeTimeout.Seconds() < 1 {
|
||||||
|
log.WithField("write_timeout", *writeTimeoutStr).
|
||||||
|
Fatal("write_timeout less than one second")
|
||||||
|
}
|
||||||
|
|
||||||
|
dataTimeout, err = time.ParseDuration(*dataTimeoutStr)
|
||||||
|
if err != nil {
|
||||||
|
log.WithField("data_timeout", *dataTimeoutStr).
|
||||||
|
WithError(err).
|
||||||
|
Fatal("data_timeout duration string invalid")
|
||||||
|
}
|
||||||
|
if dataTimeout.Seconds() < 1 {
|
||||||
|
log.WithField("data_timeout", *dataTimeoutStr).
|
||||||
|
Fatal("data_timeout less than one second")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func ConfigLoad() {
|
||||||
|
// use .env file if it exists
|
||||||
|
if _, err := os.Stat(".env"); err == nil {
|
||||||
|
if err := ff.Parse(flagset, os.Args[1:],
|
||||||
|
ff.WithEnvVarPrefix("smtprelay"),
|
||||||
|
ff.WithConfigFile(".env"),
|
||||||
|
ff.WithConfigFileParser(ff.EnvParser),
|
||||||
|
); err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "error: %v\n", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// use env variables and smtprelay.ini file
|
||||||
|
if err := ff.Parse(flagset, os.Args[1:],
|
||||||
|
ff.WithEnvVarPrefix("smtprelay"),
|
||||||
|
ff.WithConfigFileFlag("config"),
|
||||||
|
ff.WithConfigFileParser(IniParser),
|
||||||
|
); err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "error: %v\n", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Set up logging as soon as possible
|
||||||
|
setupLogger()
|
||||||
|
|
||||||
|
if *versionInfo {
|
||||||
|
fmt.Printf("smtprelay/%s (%s)\n", appVersion, buildTime)
|
||||||
|
os.Exit(0)
|
||||||
|
}
|
||||||
|
|
||||||
|
if *remotesStr == "" && *command == "" {
|
||||||
|
log.Warn("no remotes or command set; mail will not be forwarded!")
|
||||||
|
}
|
||||||
|
|
||||||
|
setupAllowedNetworks()
|
||||||
|
setupAllowedPatterns()
|
||||||
|
setupRemotes()
|
||||||
|
setupListeners()
|
||||||
|
setupTimeouts()
|
||||||
|
}
|
||||||
|
|
||||||
|
// IniParser is a parser for config files in classic key/value style format. Each
|
||||||
|
// line is tokenized as a single key/value pair. The first "=" delimited
|
||||||
|
// token in the line is interpreted as the flag name, and all remaining tokens
|
||||||
|
// are interpreted as the value. Any leading hyphens on the flag name are
|
||||||
|
// ignored.
|
||||||
|
func IniParser(r io.Reader, set func(name, value string) error) error {
|
||||||
|
s := bufio.NewScanner(r)
|
||||||
|
for s.Scan() {
|
||||||
|
line := strings.TrimSpace(s.Text())
|
||||||
|
if line == "" {
|
||||||
|
continue // skip empties
|
||||||
|
}
|
||||||
|
|
||||||
|
if line[0] == '#' || line[0] == ';' {
|
||||||
|
continue // skip comments
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
name string
|
||||||
|
value string
|
||||||
|
index = strings.IndexRune(line, '=')
|
||||||
|
)
|
||||||
|
if index < 0 {
|
||||||
|
name, value = line, "true" // boolean option
|
||||||
|
} else {
|
||||||
|
name, value = strings.TrimSpace(line[:index]), strings.Trim(strings.TrimSpace(line[index+1:]), "\"")
|
||||||
|
}
|
||||||
|
|
||||||
|
if i := strings.Index(value, " #"); i >= 0 {
|
||||||
|
value = strings.TrimSpace(value[:i])
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := set(name, value); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
|
|||||||
44
config_test.go
Normal file
44
config_test.go
Normal 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)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
18
go.mod
18
go.mod
@@ -1,9 +1,19 @@
|
|||||||
module github.com/decke/smtprelay
|
module github.com/decke/smtprelay
|
||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/chrj/smtpd v0.2.0
|
github.com/chrj/smtpd v0.3.1
|
||||||
github.com/vharitonsky/iniflags v0.0.0-20180513140207-a33cd0b5f3de
|
github.com/google/uuid v1.3.0
|
||||||
golang.org/x/crypto v0.0.0-20200604202706-70a84ac30bf9
|
github.com/peterbourgon/ff/v3 v3.3.0
|
||||||
|
github.com/sirupsen/logrus v1.9.0
|
||||||
|
github.com/stretchr/testify v1.8.0
|
||||||
|
golang.org/x/crypto v0.0.0-20220411220226-7b82a4e95df4
|
||||||
)
|
)
|
||||||
|
|
||||||
go 1.13
|
require (
|
||||||
|
github.com/davecgh/go-spew v1.1.1 // indirect
|
||||||
|
github.com/pmezard/go-difflib v1.0.0 // indirect
|
||||||
|
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8 // indirect
|
||||||
|
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||||
|
)
|
||||||
|
|
||||||
|
go 1.18
|
||||||
|
|||||||
40
go.sum
40
go.sum
@@ -1,12 +1,28 @@
|
|||||||
github.com/chrj/smtpd v0.2.0 h1:QGbE4UQz7sKjvXpRgNLuiBOjcWTzBKu/dj0hyDLpD14=
|
github.com/chrj/smtpd v0.3.1 h1:kogHFkbFdKaoH3bgZkqNC9uVtKYOFfM3uV3rroBdooE=
|
||||||
github.com/chrj/smtpd v0.2.0/go.mod h1:1hmG9KbrE10JG1SmvG79Krh4F6713oUrw2+gRp1oSYk=
|
github.com/chrj/smtpd v0.3.1/go.mod h1:JtABvV/LzvLmEIzy0NyDnrfMGOMd8wy5frAokwf6J9Q=
|
||||||
github.com/eaigner/dkim v0.0.0-20150301120808-6fe4a7ee9cfb/go.mod h1:FSCIHbrqk7D01Mj8y/jW+NS1uoCerr+ad+IckTHTFf4=
|
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
github.com/vharitonsky/iniflags v0.0.0-20180513140207-a33cd0b5f3de h1:fkw+7JkxF3U1GzQoX9h69Wvtvxajo5Rbzy6+YMMzPIg=
|
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||||
github.com/vharitonsky/iniflags v0.0.0-20180513140207-a33cd0b5f3de/go.mod h1:irMhzlTz8+fVFj6CH2AN2i+WI5S6wWFtK3MBCIxIpyI=
|
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I=
|
||||||
golang.org/x/crypto v0.0.0-20200604202706-70a84ac30bf9 h1:vEg9joUBmeBcK9iSJftGNf3coIG4HqZElCPehJsfAYM=
|
github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||||
golang.org/x/crypto v0.0.0-20200604202706-70a84ac30bf9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
github.com/peterbourgon/ff/v3 v3.3.0 h1:PaKe7GW8orVFh8Unb5jNHS+JZBwWUMa2se0HM6/BI24=
|
||||||
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
github.com/peterbourgon/ff/v3 v3.3.0/go.mod h1:zjJVUhx+twciwfDl0zBcFzl4dW8axCRyXE/eKY9RztQ=
|
||||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||||
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
github.com/sirupsen/logrus v1.9.0 h1:trlNQbNUG3OdDrDil03MCb1H2o9nJ1x4/5LYw7byDE0=
|
||||||
|
github.com/sirupsen/logrus v1.9.0/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
|
||||||
|
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||||
|
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||||
|
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||||
|
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||||
|
github.com/stretchr/testify v1.8.0 h1:pSgiaMZlXftHpm5L7V1+rVB+AZJydKsMxsQBIJw4PKk=
|
||||||
|
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||||
|
golang.org/x/crypto v0.0.0-20220411220226-7b82a4e95df4 h1:kUhD7nTDoI3fVd9G4ORWrbV5NY0liEs/Jg2pv5f+bBA=
|
||||||
|
golang.org/x/crypto v0.0.0-20220411220226-7b82a4e95df4/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
|
||||||
|
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8 h1:0A+M6Uqn+Eje4kHMK80dtF3JCXC4ykBgQG4Fe06QRhQ=
|
||||||
|
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
||||||
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
|
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
|
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||||
|
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
|
|||||||
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)
|
||||||
|
}
|
||||||
396
main.go
396
main.go
@@ -1,93 +1,150 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bytes"
|
||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
"log"
|
|
||||||
"net"
|
"net"
|
||||||
"net/smtp"
|
"net/textproto"
|
||||||
"os"
|
"os"
|
||||||
"regexp"
|
"os/exec"
|
||||||
|
"os/signal"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"syscall"
|
||||||
|
|
||||||
"github.com/chrj/smtpd"
|
"github.com/chrj/smtpd"
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"github.com/sirupsen/logrus"
|
||||||
)
|
)
|
||||||
|
|
||||||
func connectionChecker(peer smtpd.Peer) error {
|
func connectionChecker(peer smtpd.Peer) error {
|
||||||
var peerIP net.IP
|
// This can't panic because we only have TCP listeners
|
||||||
if addr, ok := peer.Addr.(*net.TCPAddr); ok {
|
peerIP := peer.Addr.(*net.TCPAddr).IP
|
||||||
peerIP = net.ParseIP(addr.IP.String())
|
|
||||||
} else {
|
if len(allowedNets) == 0 {
|
||||||
return smtpd.Error{Code: 421, Message: "Denied"}
|
// Special case: empty string means allow everything
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
nets := strings.Split(*allowedNets, " ")
|
for _, allowedNet := range allowedNets {
|
||||||
|
|
||||||
for i := range nets {
|
|
||||||
_, allowedNet, _ := net.ParseCIDR(nets[i])
|
|
||||||
|
|
||||||
if allowedNet.Contains(peerIP) {
|
if allowedNet.Contains(peerIP) {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
log.WithFields(logrus.Fields{
|
||||||
|
"ip": peerIP,
|
||||||
|
}).Warn("Connection refused from address outside of allowed_nets")
|
||||||
return smtpd.Error{Code: 421, Message: "Denied"}
|
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 {
|
func senderChecker(peer smtpd.Peer, addr string) error {
|
||||||
// check sender address from auth file if user is authenticated
|
// check sender address from auth file if user is authenticated
|
||||||
if *allowedUsers != "" && peer.Username != "" {
|
if localAuthRequired() && peer.Username != "" {
|
||||||
_, email, err := AuthFetch(peer.Username)
|
user, err := AuthFetch(peer.Username)
|
||||||
if err != nil {
|
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"}
|
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"}
|
return smtpd.Error{Code: 451, Message: "Bad sender address"}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if *allowedSender == "" {
|
if allowedSender == nil {
|
||||||
|
// Any sender is permitted
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
re, err := regexp.Compile(*allowedSender)
|
if allowedSender.MatchString(addr) {
|
||||||
if err != nil {
|
// Permitted by regex
|
||||||
log.Printf("allowed_sender invalid: %v\n", err)
|
|
||||||
return smtpd.Error{Code: 451, Message: "Bad sender address"}
|
|
||||||
}
|
|
||||||
|
|
||||||
if re.MatchString(addr) {
|
|
||||||
return nil
|
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"}
|
return smtpd.Error{Code: 451, Message: "Bad sender address"}
|
||||||
}
|
}
|
||||||
|
|
||||||
func recipientChecker(peer smtpd.Peer, addr string) error {
|
func recipientChecker(peer smtpd.Peer, addr string) error {
|
||||||
if *allowedRecipients == "" {
|
if allowedRecipients == nil {
|
||||||
|
// Any recipient is permitted
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
re, err := regexp.Compile(*allowedRecipients)
|
if allowedRecipients.MatchString(addr) {
|
||||||
if err != nil {
|
// Permitted by regex
|
||||||
log.Printf("allowed_recipients invalid: %v\n", err)
|
|
||||||
return smtpd.Error{Code: 451, Message: "Bad recipient address"}
|
|
||||||
}
|
|
||||||
|
|
||||||
if re.MatchString(addr) {
|
|
||||||
return nil
|
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"}
|
return smtpd.Error{Code: 451, Message: "Bad recipient address"}
|
||||||
}
|
}
|
||||||
|
|
||||||
func authChecker(peer smtpd.Peer, username string, password string) error {
|
func authChecker(peer smtpd.Peer, username string, password string) error {
|
||||||
err := AuthCheckPassword(username, password)
|
err := AuthCheckPassword(username, password)
|
||||||
if err != nil {
|
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 smtpd.Error{Code: 535, Message: "Authentication credentials invalid"}
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
@@ -99,53 +156,91 @@ func mailHandler(peer smtpd.Peer, env smtpd.Envelope) error {
|
|||||||
peerIP = addr.IP.String()
|
peerIP = addr.IP.String()
|
||||||
}
|
}
|
||||||
|
|
||||||
log.Printf("new mail from=<%s> to=%s peer=[%s]\n", env.Sender,
|
logger := log.WithFields(logrus.Fields{
|
||||||
env.Recipients, peerIP)
|
"from": env.Sender,
|
||||||
|
"to": env.Recipients,
|
||||||
|
"peer": peerIP,
|
||||||
|
"uuid": generateUUID(),
|
||||||
|
})
|
||||||
|
|
||||||
var auth smtp.Auth
|
if *remotesStr == "" && *command == "" {
|
||||||
host, _, _ := net.SplitHostPort(*remoteHost)
|
logger.Warning("no remote_host or command set; discarding mail")
|
||||||
|
return nil
|
||||||
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"}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
env.AddReceivedLine(peer)
|
env.AddReceivedLine(peer)
|
||||||
|
|
||||||
log.Printf("delivering using smarthost %s\n", *remoteHost)
|
if *command != "" {
|
||||||
|
cmdLogger := logger.WithField("command", *command)
|
||||||
|
|
||||||
var sender string
|
var stdout bytes.Buffer
|
||||||
|
var stderr bytes.Buffer
|
||||||
|
|
||||||
if *remoteSender == "" {
|
cmd := exec.Command(*command)
|
||||||
sender = env.Sender
|
cmd.Stdin = bytes.NewReader(env.Data)
|
||||||
} else {
|
cmd.Stdout = &stdout
|
||||||
sender = *remoteSender
|
cmd.Stderr = &stderr
|
||||||
|
|
||||||
|
err := cmd.Run()
|
||||||
|
if err != nil {
|
||||||
|
cmdLogger.WithError(err).Error(stderr.String())
|
||||||
|
return smtpd.Error{Code: 554, Message: "External command failed"}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
cmdLogger.Info("pipe command successful: " + stdout.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, remote := range remotes {
|
||||||
|
logger = logger.WithField("host", remote.Addr)
|
||||||
|
logger.Info("delivering mail from peer using smarthost")
|
||||||
|
|
||||||
err := SendMail(
|
err := SendMail(
|
||||||
*remoteHost,
|
remote,
|
||||||
auth,
|
env.Sender,
|
||||||
sender,
|
|
||||||
env.Recipients,
|
env.Recipients,
|
||||||
env.Data,
|
env.Data,
|
||||||
)
|
)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Printf("delivery failed: %v\n", err)
|
var smtpError smtpd.Error
|
||||||
return smtpd.Error{Code: 554, Message: "Forwarding failed"}
|
|
||||||
|
switch err := err.(type) {
|
||||||
|
case *textproto.Error:
|
||||||
|
smtpError = smtpd.Error{Code: err.Code, Message: err.Msg}
|
||||||
|
|
||||||
|
logger.WithFields(logrus.Fields{
|
||||||
|
"err_code": err.Code,
|
||||||
|
"err_msg": err.Msg,
|
||||||
|
}).Error("delivery failed")
|
||||||
|
default:
|
||||||
|
smtpError = smtpd.Error{Code: 554, Message: "Forwarding failed"}
|
||||||
|
|
||||||
|
logger.WithError(err).
|
||||||
|
Error("delivery failed")
|
||||||
}
|
}
|
||||||
|
|
||||||
log.Printf("%s delivery successful\n", env.Recipients)
|
return smtpError
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.Debug("delivery successful")
|
||||||
|
}
|
||||||
|
|
||||||
return nil
|
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
|
// Ciphersuites as defined in stock Go but without 3DES and RC4
|
||||||
// https://golang.org/src/crypto/tls/cipher_suites.go
|
// https://golang.org/src/crypto/tls/cipher_suites.go
|
||||||
var tlsCipherSuites = []uint16{
|
var tlsCipherSuites = []uint16{
|
||||||
@@ -158,124 +253,141 @@ func main() {
|
|||||||
tls.TLS_ECDHE_ECDSA_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_RSA_WITH_AES_256_GCM_SHA384,
|
||||||
tls.TLS_ECDHE_ECDSA_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_128_GCM_SHA256, // does not provide PFS
|
||||||
tls.TLS_RSA_WITH_AES_256_GCM_SHA384, // 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()
|
ConfigLoad()
|
||||||
|
|
||||||
if *versionInfo {
|
log.WithField("version", appVersion).
|
||||||
fmt.Printf("smtprelay/%s\n", VERSION)
|
Debug("starting smtprelay")
|
||||||
os.Exit(0)
|
|
||||||
}
|
|
||||||
|
|
||||||
if *logFile != "" {
|
// Load allowed users file
|
||||||
f, err := os.OpenFile(*logFile, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0600)
|
if localAuthRequired() {
|
||||||
|
err := AuthLoadFile(*allowedUsers)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatalf("Error opening logfile: %v", err)
|
log.WithField("file", *allowedUsers).
|
||||||
|
WithError(err).
|
||||||
|
Fatal("cannot load allowed users file")
|
||||||
}
|
}
|
||||||
defer f.Close()
|
|
||||||
|
|
||||||
log.SetOutput(io.MultiWriter(os.Stdout, f))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
listeners := strings.Split(*listen, " ")
|
var servers []*smtpd.Server
|
||||||
|
|
||||||
for i := range listeners {
|
// Create a server for each desired listen address
|
||||||
listener := listeners[i]
|
for _, listen := range listenAddrs {
|
||||||
|
logger := log.WithField("address", listen.address)
|
||||||
|
|
||||||
server := &smtpd.Server{
|
server := &smtpd.Server{
|
||||||
Hostname: *hostName,
|
Hostname: *hostName,
|
||||||
WelcomeMessage: *welcomeMsg,
|
WelcomeMessage: *welcomeMsg,
|
||||||
|
ReadTimeout: readTimeout,
|
||||||
|
WriteTimeout: writeTimeout,
|
||||||
|
DataTimeout: dataTimeout,
|
||||||
|
MaxConnections: *maxConnections,
|
||||||
|
MaxMessageSize: *maxMessageSize,
|
||||||
|
MaxRecipients: *maxRecipients,
|
||||||
ConnectionChecker: connectionChecker,
|
ConnectionChecker: connectionChecker,
|
||||||
SenderChecker: senderChecker,
|
SenderChecker: senderChecker,
|
||||||
RecipientChecker: recipientChecker,
|
RecipientChecker: recipientChecker,
|
||||||
Handler: mailHandler,
|
Handler: mailHandler,
|
||||||
}
|
}
|
||||||
|
|
||||||
if *allowedUsers != "" {
|
if localAuthRequired() {
|
||||||
err := AuthLoadFile(*allowedUsers)
|
|
||||||
if err != nil {
|
|
||||||
log.Fatalf("Authentication file: %s\n", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
server.Authenticator = authChecker
|
server.Authenticator = authChecker
|
||||||
}
|
}
|
||||||
|
|
||||||
if strings.Index(listeners[i], "://") == -1 {
|
var lsnr net.Listener
|
||||||
log.Printf("Listen on %s ...\n", listener)
|
var err error
|
||||||
go server.ListenAndServe(listener)
|
|
||||||
} else if strings.HasPrefix(listeners[i], "starttls://") {
|
|
||||||
listener = strings.TrimPrefix(listener, "starttls://")
|
|
||||||
|
|
||||||
if *localCert == "" || *localKey == "" {
|
switch listen.protocol {
|
||||||
log.Fatal("TLS certificate/key not defined in config")
|
case "":
|
||||||
}
|
logger.Info("listening on address")
|
||||||
|
lsnr, err = net.Listen("tcp", listen.address)
|
||||||
|
|
||||||
cert, err := tls.LoadX509KeyPair(*localCert, *localKey)
|
case "starttls":
|
||||||
if err != nil {
|
server.TLSConfig = getTLSConfig()
|
||||||
log.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
server.TLSConfig = &tls.Config{
|
|
||||||
PreferServerCipherSuites: true,
|
|
||||||
MinVersion: tls.VersionTLS11,
|
|
||||||
CipherSuites: tlsCipherSuites,
|
|
||||||
Certificates: []tls.Certificate{cert},
|
|
||||||
}
|
|
||||||
server.ForceTLS = *localForceTLS
|
server.ForceTLS = *localForceTLS
|
||||||
|
|
||||||
log.Printf("Listen on %s (STARTSSL) ...\n", listener)
|
logger.Info("listening on address (STARTTLS)")
|
||||||
lsnr, err := net.Listen("tcp", listener)
|
lsnr, err = net.Listen("tcp", listen.address)
|
||||||
|
|
||||||
|
case "tls":
|
||||||
|
server.TLSConfig = getTLSConfig()
|
||||||
|
|
||||||
|
logger.Info("listening on address (TLS)")
|
||||||
|
lsnr, err = tls.Listen("tcp", listen.address, server.TLSConfig)
|
||||||
|
|
||||||
|
default:
|
||||||
|
logger.WithField("protocol", listen.protocol).
|
||||||
|
Fatal("unknown protocol in listen address")
|
||||||
|
}
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(err)
|
logger.WithError(err).Fatal("error starting listener")
|
||||||
}
|
}
|
||||||
defer lsnr.Close()
|
servers = append(servers, server)
|
||||||
|
|
||||||
go server.Serve(lsnr)
|
go func() {
|
||||||
} else if strings.HasPrefix(listeners[i], "tls://") {
|
server.Serve(lsnr)
|
||||||
|
}()
|
||||||
listener = strings.TrimPrefix(listener, "tls://")
|
|
||||||
|
|
||||||
if *localCert == "" || *localKey == "" {
|
|
||||||
log.Fatal("TLS certificate/key not defined in config")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
cert, err := tls.LoadX509KeyPair(*localCert, *localKey)
|
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 {
|
if err != nil {
|
||||||
log.Fatal(err)
|
logger.WithError(err).
|
||||||
|
Warning("Shutdown failed")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
server.TLSConfig = &tls.Config{
|
// Then wait for the clients to exit
|
||||||
PreferServerCipherSuites: true,
|
for _, server := range servers {
|
||||||
MinVersion: tls.VersionTLS11,
|
logger := log.WithField("address", server.Address())
|
||||||
CipherSuites: tlsCipherSuites,
|
logger.Debug("Waiting for server")
|
||||||
Certificates: []tls.Certificate{cert},
|
err := server.Wait()
|
||||||
}
|
|
||||||
|
|
||||||
log.Printf("Listen on %s (TLS) ...\n", listener)
|
|
||||||
lsnr, err := tls.Listen("tcp", listener, server.TLSConfig)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(err)
|
logger.WithError(err).
|
||||||
}
|
Warning("Wait failed")
|
||||||
defer lsnr.Close()
|
|
||||||
|
|
||||||
go server.Serve(lsnr)
|
|
||||||
} else {
|
|
||||||
log.Fatal("Unknown protocol in listener ", listener)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
for true {
|
log.Debug("done")
|
||||||
time.Sleep(time.Minute)
|
}
|
||||||
}
|
|
||||||
|
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()
|
||||||
|
}
|
||||||
|
}
|
||||||
83
remotes.go
Normal file
83
remotes.go
Normal file
@@ -0,0 +1,83 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"net/smtp"
|
||||||
|
"net/url"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Remote struct {
|
||||||
|
SkipVerify bool
|
||||||
|
Auth smtp.Auth
|
||||||
|
Scheme string
|
||||||
|
Hostname string
|
||||||
|
Port string
|
||||||
|
Addr string
|
||||||
|
Sender string
|
||||||
|
}
|
||||||
|
|
||||||
|
// ParseRemote creates a remote from a given url in the following format:
|
||||||
|
//
|
||||||
|
// smtp://[user[:password]@][netloc][:port][/remote_sender][?param1=value1&...]
|
||||||
|
// smtps://[user[:password]@][netloc][:port][/remote_sender][?param1=value1&...]
|
||||||
|
// starttls://[user[:password]@][netloc][:port][/remote_sender][?param1=value1&...]
|
||||||
|
//
|
||||||
|
// Supported Params:
|
||||||
|
// - skipVerify: can be "true" or empty to prevent ssl verification of remote server's certificate.
|
||||||
|
// - auth: can be "login" to trigger "LOGIN" auth instead of "PLAIN" auth
|
||||||
|
func ParseRemote(remoteURL string) (*Remote, error) {
|
||||||
|
u, err := url.Parse(remoteURL)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if u.Scheme != "smtp" && u.Scheme != "smtps" && u.Scheme != "starttls" {
|
||||||
|
return nil, fmt.Errorf("'%s' is not a supported relay scheme", u.Scheme)
|
||||||
|
}
|
||||||
|
|
||||||
|
hostname, port := u.Hostname(), u.Port()
|
||||||
|
|
||||||
|
if port == "" {
|
||||||
|
switch u.Scheme {
|
||||||
|
case "smtp":
|
||||||
|
port = "25"
|
||||||
|
case "smtps":
|
||||||
|
port = "465"
|
||||||
|
case "starttls":
|
||||||
|
port = "587"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
q := u.Query()
|
||||||
|
r := &Remote{
|
||||||
|
Scheme: u.Scheme,
|
||||||
|
Hostname: hostname,
|
||||||
|
Port: port,
|
||||||
|
Addr: fmt.Sprintf("%s:%s", hostname, port),
|
||||||
|
}
|
||||||
|
|
||||||
|
if u.User != nil {
|
||||||
|
pass, _ := u.User.Password()
|
||||||
|
user := u.User.Username()
|
||||||
|
|
||||||
|
if hasAuth, authVal := q.Has("auth"), q.Get("auth"); hasAuth {
|
||||||
|
if authVal != "login" {
|
||||||
|
return nil, fmt.Errorf("Auth must be login or not present, received '%s'", authVal)
|
||||||
|
}
|
||||||
|
|
||||||
|
r.Auth = LoginAuth(user, pass)
|
||||||
|
} else {
|
||||||
|
r.Auth = smtp.PlainAuth("", user, pass, u.Hostname())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if hasVal, skipVerify := q.Has("skipVerify"), q.Get("skipVerify"); hasVal && skipVerify != "false" {
|
||||||
|
r.SkipVerify = true
|
||||||
|
}
|
||||||
|
|
||||||
|
if u.Path != "" {
|
||||||
|
r.Sender = u.Path[1:]
|
||||||
|
}
|
||||||
|
|
||||||
|
return r, nil
|
||||||
|
}
|
||||||
114
remotes_test.go
Normal file
114
remotes_test.go
Normal file
@@ -0,0 +1,114 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/smtp"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
)
|
||||||
|
|
||||||
|
func AssertRemoteUrlEquals(t *testing.T, expected *Remote, remotUrl string) {
|
||||||
|
actual, err := ParseRemote(remotUrl)
|
||||||
|
assert.Nil(t, err)
|
||||||
|
assert.NotNil(t, actual)
|
||||||
|
assert.Equal(t, expected.Scheme, actual.Scheme, "Scheme %s", remotUrl)
|
||||||
|
assert.Equal(t, expected.Addr, actual.Addr, "Addr %s", remotUrl)
|
||||||
|
assert.Equal(t, expected.Hostname, actual.Hostname, "Hostname %s", remotUrl)
|
||||||
|
assert.Equal(t, expected.Port, actual.Port, "Port %s", remotUrl)
|
||||||
|
assert.Equal(t, expected.Sender, actual.Sender, "Sender %s", remotUrl)
|
||||||
|
assert.Equal(t, expected.SkipVerify, actual.SkipVerify, "SkipVerify %s", remotUrl)
|
||||||
|
|
||||||
|
if expected.Auth != nil || actual.Auth != nil {
|
||||||
|
assert.NotNil(t, expected, "Auth %s", remotUrl)
|
||||||
|
assert.NotNil(t, actual, "Auth %s", remotUrl)
|
||||||
|
assert.IsType(t, expected.Auth, actual.Auth)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestValidRemoteUrls(t *testing.T) {
|
||||||
|
AssertRemoteUrlEquals(t, &Remote{
|
||||||
|
Scheme: "smtp",
|
||||||
|
SkipVerify: false,
|
||||||
|
Auth: nil,
|
||||||
|
Hostname: "email.com",
|
||||||
|
Port: "25",
|
||||||
|
Addr: "email.com:25",
|
||||||
|
Sender: "",
|
||||||
|
}, "smtp://email.com")
|
||||||
|
|
||||||
|
AssertRemoteUrlEquals(t, &Remote{
|
||||||
|
Scheme: "smtp",
|
||||||
|
SkipVerify: true,
|
||||||
|
Auth: nil,
|
||||||
|
Hostname: "email.com",
|
||||||
|
Port: "25",
|
||||||
|
Addr: "email.com:25",
|
||||||
|
Sender: "",
|
||||||
|
}, "smtp://email.com?skipVerify")
|
||||||
|
|
||||||
|
AssertRemoteUrlEquals(t, &Remote{
|
||||||
|
Scheme: "smtp",
|
||||||
|
SkipVerify: false,
|
||||||
|
Auth: smtp.PlainAuth("", "user", "pass", ""),
|
||||||
|
Hostname: "email.com",
|
||||||
|
Port: "25",
|
||||||
|
Addr: "email.com:25",
|
||||||
|
Sender: "",
|
||||||
|
}, "smtp://user:pass@email.com")
|
||||||
|
|
||||||
|
AssertRemoteUrlEquals(t, &Remote{
|
||||||
|
Scheme: "smtp",
|
||||||
|
SkipVerify: false,
|
||||||
|
Auth: LoginAuth("user", "pass"),
|
||||||
|
Hostname: "email.com",
|
||||||
|
Port: "25",
|
||||||
|
Addr: "email.com:25",
|
||||||
|
Sender: "",
|
||||||
|
}, "smtp://user:pass@email.com?auth=login")
|
||||||
|
|
||||||
|
AssertRemoteUrlEquals(t, &Remote{
|
||||||
|
Scheme: "smtp",
|
||||||
|
SkipVerify: false,
|
||||||
|
Auth: LoginAuth("user", "pass"),
|
||||||
|
Hostname: "email.com",
|
||||||
|
Port: "25",
|
||||||
|
Addr: "email.com:25",
|
||||||
|
Sender: "sender@website.com",
|
||||||
|
}, "smtp://user:pass@email.com/sender@website.com?auth=login")
|
||||||
|
|
||||||
|
AssertRemoteUrlEquals(t, &Remote{
|
||||||
|
Scheme: "smtps",
|
||||||
|
SkipVerify: false,
|
||||||
|
Auth: LoginAuth("user", "pass"),
|
||||||
|
Hostname: "email.com",
|
||||||
|
Port: "465",
|
||||||
|
Addr: "email.com:465",
|
||||||
|
Sender: "sender@website.com",
|
||||||
|
}, "smtps://user:pass@email.com/sender@website.com?auth=login")
|
||||||
|
|
||||||
|
AssertRemoteUrlEquals(t, &Remote{
|
||||||
|
Scheme: "smtps",
|
||||||
|
SkipVerify: true,
|
||||||
|
Auth: LoginAuth("user", "pass"),
|
||||||
|
Hostname: "email.com",
|
||||||
|
Port: "8425",
|
||||||
|
Addr: "email.com:8425",
|
||||||
|
Sender: "sender@website.com",
|
||||||
|
}, "smtps://user:pass@email.com:8425/sender@website.com?auth=login&skipVerify")
|
||||||
|
|
||||||
|
AssertRemoteUrlEquals(t, &Remote{
|
||||||
|
Scheme: "starttls",
|
||||||
|
SkipVerify: true,
|
||||||
|
Auth: LoginAuth("user", "pass"),
|
||||||
|
Hostname: "email.com",
|
||||||
|
Port: "8425",
|
||||||
|
Addr: "email.com:8425",
|
||||||
|
Sender: "sender@website.com",
|
||||||
|
}, "starttls://user:pass@email.com:8425/sender@website.com?auth=login&skipVerify")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMissingScheme(t *testing.T) {
|
||||||
|
_, err := ParseRemote("http://user:pass@email.com:8425/sender@website.com")
|
||||||
|
assert.NotNil(t, err, "Err must be present")
|
||||||
|
assert.Equal(t, err.Error(), "'http' is not a supported relay scheme")
|
||||||
|
}
|
||||||
@@ -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
|
|
||||||
|
|
||||||
53
smtp.go
53
smtp.go
@@ -4,9 +4,11 @@
|
|||||||
|
|
||||||
// Package smtp implements the Simple Mail Transfer Protocol as defined in RFC 5321.
|
// Package smtp implements the Simple Mail Transfer Protocol as defined in RFC 5321.
|
||||||
// It also implements the following extensions:
|
// It also implements the following extensions:
|
||||||
|
//
|
||||||
// 8BITMIME RFC 1652
|
// 8BITMIME RFC 1652
|
||||||
// AUTH RFC 2554
|
// AUTH RFC 2554
|
||||||
// STARTTLS RFC 3207
|
// STARTTLS RFC 3207
|
||||||
|
//
|
||||||
// Additional extensions may be handled by clients.
|
// Additional extensions may be handled by clients.
|
||||||
//
|
//
|
||||||
// The smtp package is frozen and is not accepting new features.
|
// The smtp package is frozen and is not accepting new features.
|
||||||
@@ -106,7 +108,7 @@ func (c *Client) Hello(localName string) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// cmd is a convenience function that sends a command and returns the response
|
// cmd is a convenience function that sends a command and returns the response
|
||||||
func (c *Client) cmd(expectCode int, format string, args ...interface{}) (int, string, error) {
|
func (c *Client) cmd(expectCode int, format string, args ...any) (int, string, error) {
|
||||||
id, err := c.Text.Cmd(format, args...)
|
id, err := c.Text.Cmd(format, args...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, "", err
|
return 0, "", err
|
||||||
@@ -137,12 +139,8 @@ func (c *Client) ehlo() error {
|
|||||||
if len(extList) > 1 {
|
if len(extList) > 1 {
|
||||||
extList = extList[1:]
|
extList = extList[1:]
|
||||||
for _, line := range extList {
|
for _, line := range extList {
|
||||||
args := strings.SplitN(line, " ", 2)
|
k, v, _ := strings.Cut(line, " ")
|
||||||
if len(args) > 1 {
|
ext[k] = v
|
||||||
ext[args[0]] = args[1]
|
|
||||||
} else {
|
|
||||||
ext[args[0]] = ""
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if mechs, ok := ext["AUTH"]; ok {
|
if mechs, ok := ext["AUTH"]; ok {
|
||||||
@@ -242,7 +240,8 @@ func (c *Client) Auth(a smtp.Auth) error {
|
|||||||
|
|
||||||
// Mail issues a MAIL command to the server using the provided email address.
|
// 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
|
// 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.
|
// This initiates a mail transaction and is followed by one or more Rcpt calls.
|
||||||
func (c *Client) Mail(from string) error {
|
func (c *Client) Mail(from string) error {
|
||||||
if err := validateLine(from); err != nil {
|
if err := validateLine(from); err != nil {
|
||||||
@@ -256,6 +255,9 @@ func (c *Client) Mail(from string) error {
|
|||||||
if _, ok := c.ext["8BITMIME"]; ok {
|
if _, ok := c.ext["8BITMIME"]; ok {
|
||||||
cmdStr += " BODY=8BITMIME"
|
cmdStr += " BODY=8BITMIME"
|
||||||
}
|
}
|
||||||
|
if _, ok := c.ext["SMTPUTF8"]; ok {
|
||||||
|
cmdStr += " SMTPUTF8"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
_, _, err := c.cmd(250, cmdStr, from)
|
_, _, err := c.cmd(250, cmdStr, from)
|
||||||
return err
|
return err
|
||||||
@@ -318,7 +320,11 @@ var testHookStartTLS func(*tls.Config) // nil, except for tests
|
|||||||
// attachments (see the mime/multipart package), or other mail
|
// attachments (see the mime/multipart package), or other mail
|
||||||
// functionality. Higher-level packages exist outside of the standard
|
// functionality. Higher-level packages exist outside of the standard
|
||||||
// library.
|
// library.
|
||||||
func SendMail(addr string, a smtp.Auth, from string, to []string, msg []byte) error {
|
func SendMail(r *Remote, from string, to []string, msg []byte) error {
|
||||||
|
if r.Sender != "" {
|
||||||
|
from = r.Sender
|
||||||
|
}
|
||||||
|
|
||||||
if err := validateLine(from); err != nil {
|
if err := validateLine(from); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -327,19 +333,19 @@ func SendMail(addr string, a smtp.Auth, from string, to []string, msg []byte) er
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
host, port, err := net.SplitHostPort(addr)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
var c *Client
|
var c *Client
|
||||||
if port == "465" || port == "smtps" {
|
var err error
|
||||||
config := &tls.Config{ServerName: host}
|
if r.Scheme == "smtps" {
|
||||||
conn, err := tls.Dial("tcp", addr, config)
|
config := &tls.Config{
|
||||||
|
ServerName: r.Hostname,
|
||||||
|
InsecureSkipVerify: r.SkipVerify,
|
||||||
|
}
|
||||||
|
conn, err := tls.Dial("tcp", r.Addr, config)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
defer conn.Close()
|
defer conn.Close()
|
||||||
c, err = NewClient(conn, host)
|
c, err = NewClient(conn, r.Hostname)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -347,7 +353,7 @@ func SendMail(addr string, a smtp.Auth, from string, to []string, msg []byte) er
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
c, err = Dial(addr)
|
c, err = Dial(r.Addr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -356,20 +362,25 @@ func SendMail(addr string, a smtp.Auth, from string, to []string, msg []byte) er
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if ok, _ := c.Extension("STARTTLS"); ok {
|
if ok, _ := c.Extension("STARTTLS"); ok {
|
||||||
config := &tls.Config{ServerName: c.serverName}
|
config := &tls.Config{
|
||||||
|
ServerName: c.serverName,
|
||||||
|
InsecureSkipVerify: r.SkipVerify,
|
||||||
|
}
|
||||||
if testHookStartTLS != nil {
|
if testHookStartTLS != nil {
|
||||||
testHookStartTLS(config)
|
testHookStartTLS(config)
|
||||||
}
|
}
|
||||||
if err = c.StartTLS(config); err != nil {
|
if err = c.StartTLS(config); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
} else if r.Scheme == "starttls" {
|
||||||
|
return errors.New("starttls: server does not support extension, check remote scheme")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if a != nil && c.ext != nil {
|
if r.Auth != nil && c.ext != nil {
|
||||||
if _, ok := c.ext["AUTH"]; !ok {
|
if _, ok := c.ext["AUTH"]; !ok {
|
||||||
return errors.New("smtp: server doesn't support AUTH")
|
return errors.New("smtp: server doesn't support AUTH")
|
||||||
}
|
}
|
||||||
if err = c.Auth(a); err != nil {
|
if err = c.Auth(r.Auth); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
103
smtprelay.ini
103
smtprelay.ini
@@ -1,13 +1,23 @@
|
|||||||
; smtprelay configuration
|
; smtprelay configuration
|
||||||
|
;
|
||||||
|
; All config parameters can also be provided as environment
|
||||||
|
; variables in uppercase and the prefix "SMTPRELAY_".
|
||||||
|
; (eg. SMTPRELAY_LOGFILE, SMTPRELAY_LOG_FORMAT)
|
||||||
|
|
||||||
; Logfile
|
; Logfile (blank/default is stderr)
|
||||||
;logfile = /var/log/smtprelay.log
|
;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 for this SMTP server
|
||||||
;hostname = "localhost.localdomain"
|
;hostname = localhost.localdomain
|
||||||
|
|
||||||
; Welcome message for clients
|
; Welcome message for clients
|
||||||
;welcome_msg = "<hostname> ESMTP ready."
|
;welcome_msg = <hostname> ESMTP ready.
|
||||||
|
|
||||||
; Listen on the following addresses for incoming
|
; Listen on the following addresses for incoming
|
||||||
; unencrypted connections.
|
; unencrypted connections.
|
||||||
@@ -24,40 +34,93 @@
|
|||||||
; accepting mails from client.
|
; accepting mails from client.
|
||||||
;local_forcetls = false
|
;local_forcetls = false
|
||||||
|
|
||||||
; Networks that are allowed to send mails to us
|
; Socket timeout for read operations
|
||||||
;allowed_nets = 127.0.0.1/8 ::1/128
|
; Duration string as sequence of decimal numbers,
|
||||||
|
; each with optional fraction and a unit suffix.
|
||||||
|
; Valid time units are "ns", "us", "ms", "s", "m", "h".
|
||||||
|
;read_timeout = 60s
|
||||||
|
|
||||||
; Regular expression for valid FROM EMail adresses
|
; Socket timeout for write operations
|
||||||
|
; Duration string as sequence of decimal numbers,
|
||||||
|
; each with optional fraction and a unit suffix.
|
||||||
|
; Valid time units are "ns", "us", "ms", "s", "m", "h".
|
||||||
|
;write_timeout = 60s
|
||||||
|
|
||||||
|
; Socket timeout for DATA command
|
||||||
|
; Duration string as sequence of decimal numbers,
|
||||||
|
; each with optional fraction and a unit suffix.
|
||||||
|
; Valid time units are "ns", "us", "ms", "s", "m", "h".
|
||||||
|
;data_timeout = 5m
|
||||||
|
|
||||||
|
; Max concurrent connections, use -1 to disable
|
||||||
|
;max_connections = 100
|
||||||
|
|
||||||
|
; Max message size in bytes
|
||||||
|
;max_message_size = 10240000
|
||||||
|
|
||||||
|
; Max RCPT TO calls for each envelope
|
||||||
|
;max_recipients = 100
|
||||||
|
|
||||||
|
; Networks that are allowed to send mails to us
|
||||||
|
; Defaults to localhost. If set to "", then any address is allowed.
|
||||||
|
;allowed_nets = 127.0.0.0/8 ::1/128
|
||||||
|
|
||||||
|
; Regular expression for valid FROM EMail addresses
|
||||||
|
; If set to "", then any sender is permitted.
|
||||||
; Example: ^(.*)@localhost.localdomain$
|
; Example: ^(.*)@localhost.localdomain$
|
||||||
;allowed_sender =
|
;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$
|
; Example: ^(.*)@localhost.localdomain$
|
||||||
;allowed_recipients =
|
;allowed_recipients =
|
||||||
|
|
||||||
; File which contains username and password used for
|
; File which contains username and password used for
|
||||||
; authentication before they can send mail.
|
; 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 =
|
;allowed_users =
|
||||||
|
|
||||||
; Relay all mails to this SMTP server
|
; Relay all mails to this SMTP servers.
|
||||||
|
; If not set, mails are discarded.
|
||||||
|
;
|
||||||
|
; Format:
|
||||||
|
; protocol://[user[:password]@][netloc][:port][/remote_sender][?param1=value1&...]
|
||||||
|
;
|
||||||
|
; protocol: smtp (unencrypted), smtps (TLS), starttls (STARTTLS)
|
||||||
|
; user: Username for authentication
|
||||||
|
; password: Password for authentication
|
||||||
|
; remote_sender: Email address to use as FROM
|
||||||
|
; params:
|
||||||
|
; skipVerify: "true" or empty to prevent ssl verification of remote server's certificate
|
||||||
|
; auth: "login" to use LOGIN authentication
|
||||||
|
|
||||||
; GMail
|
; GMail
|
||||||
;remote_host = smtp.gmail.com:587
|
;remotes = starttls://user:pass@smtp.gmail.com:587
|
||||||
|
|
||||||
; Mailgun.org
|
; Mailgun.org
|
||||||
;remote_host = smtp.mailgun.org:587
|
;remotes = starttls://user:pass@smtp.mailgun.org:587
|
||||||
|
|
||||||
; Mailjet.com
|
; Mailjet.com
|
||||||
;remote_host = in-v3.mailjet.com:587
|
;remotes = starttls://user:pass@in-v3.mailjet.com:587
|
||||||
|
|
||||||
; Authentication credentials on outgoing SMTP server
|
; Ignore remote host certificates
|
||||||
;remote_user =
|
;remotes = starttls://user:pass@server:587?skipVerify
|
||||||
;remote_pass =
|
|
||||||
|
|
||||||
; Authentication method on outgoing SMTP server
|
; Login Authentication method on outgoing SMTP server
|
||||||
; (plain, login)
|
;remotes = smtp://user:pass@server:2525?auth=login
|
||||||
;remote_auth = plain
|
|
||||||
|
|
||||||
; Sender e-mail address on outgoing SMTP server
|
; Sender e-mail address on outgoing SMTP server
|
||||||
;remote_sender =
|
;remotes = smtp://user:pass@server:2525/overridden@email.com?auth=login
|
||||||
|
|
||||||
|
; Multiple remotes, space delimited
|
||||||
|
;remotes = smtp://127.0.0.1:1025 starttls://user:pass@smtp.mailgun.org:587
|
||||||
|
|
||||||
|
; Pipe messages to external command
|
||||||
|
;command = /usr/local/bin/script
|
||||||
|
|||||||
Reference in New Issue
Block a user