mirror of
https://github.com/decke/smtprelay.git
synced 2025-12-25 07:43:06 -07:00
Compare commits
131 Commits
v1.11.1
...
5a036a6638
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5a036a6638 | ||
|
|
17f906df1e | ||
|
|
a73b625e68 | ||
|
|
780ac71f74 | ||
|
|
88b425b63d | ||
|
|
42c8136071 | ||
|
|
b0dfe3e540 | ||
|
|
2cecffe562 | ||
|
|
b8f8214922 | ||
|
|
bc2e50b4d5 | ||
|
|
87976ae630 | ||
|
|
ccb70f5cf6 | ||
|
|
0b6681b7dc | ||
|
|
51a6fb7feb | ||
|
|
7e38262340 | ||
|
|
0febc5a07a | ||
|
|
6fce35c3f4 | ||
|
|
1130c9b6b0 | ||
|
|
515352042a | ||
|
|
946bf5ec90 | ||
|
|
8245a2987d | ||
|
|
d652d67542 | ||
|
|
ffc4db21e7 | ||
|
|
b0e4f0077f | ||
|
|
b164ce1387 | ||
|
|
381a9b334b | ||
|
|
d1feaaabbf | ||
|
|
58a2324071 | ||
|
|
7b6be95125 | ||
|
|
6e9c00e171 | ||
|
|
20f87c889d | ||
|
|
411e7171ea | ||
|
|
19de8da2ab | ||
|
|
be6407c90f | ||
|
|
b77374bba1 | ||
|
|
35b43ac527 | ||
|
|
8c3eef19f4 | ||
|
|
9440e63396 | ||
|
|
e78d9f3bcf | ||
|
|
c0aaea9ae8 | ||
|
|
f967b683b2 | ||
|
|
285f09bbb7 | ||
|
|
d9eadb04ae | ||
|
|
4057f8df89 | ||
|
|
6f2a184679 | ||
|
|
4cf2fdc492 | ||
|
|
5292f9e732 | ||
|
|
fec3776316 | ||
|
|
e2d6d906e5 | ||
|
|
c3c8f4f73d | ||
|
|
339bf2f3dd | ||
|
|
07cda244b0 | ||
|
|
eba80b7d48 | ||
|
|
b506a0e307 | ||
|
|
79cd7fdf58 | ||
|
|
7b9d97cda5 | ||
|
|
b24970c378 | ||
|
|
99c7d5db2d | ||
|
|
3259232275 | ||
|
|
d4077b9b5b | ||
|
|
0b2970ed90 | ||
|
|
19de223c55 | ||
|
|
deb569552a | ||
|
|
7a3d443754 | ||
|
|
b78cc0a5c0 | ||
|
|
15bc75513a | ||
|
|
17421a539e | ||
|
|
1cb95f0265 | ||
|
|
10f0f20004 | ||
|
|
843c02aa0e | ||
|
|
fcc77af3bc | ||
|
|
67bccd6fd8 | ||
|
|
8f12438b5a | ||
|
|
5b7a8ea783 | ||
|
|
b715e23541 | ||
|
|
4e1cfa7bc6 | ||
|
|
9f7aa1719e | ||
|
|
692c1bd3ac | ||
|
|
638f6558cc | ||
|
|
085052b96a | ||
|
|
2753d3670d | ||
|
|
68ddb8cbc0 | ||
|
|
0b6eff0eeb | ||
|
|
51ed156dad | ||
|
|
d4aedd2453 | ||
|
|
47361c9df0 | ||
|
|
ab9ddfc8aa | ||
|
|
e722c8288e | ||
|
|
c42bc9b3bb | ||
|
|
cafbc78e74 | ||
|
|
d20e3d201c | ||
|
|
11696737ee | ||
|
|
cc8d678e18 | ||
|
|
2a6a0ef76d | ||
|
|
dfdefc5e7d | ||
|
|
3c4f79dc89 | ||
|
|
82db571b02 | ||
|
|
a06d7a6296 | ||
|
|
a971995458 | ||
|
|
b8b668bbbb | ||
|
|
66f76ccae7 | ||
|
|
e2a4d646d9 | ||
|
|
9fdd6040bd | ||
|
|
5d00ff36f0 | ||
|
|
db79ed0ea9 | ||
|
|
40942a7f83 | ||
|
|
2795ce3230 | ||
|
|
307ce547ec | ||
|
|
ea911a0aaa | ||
|
|
99b72e32f1 | ||
|
|
a2f92daa41 | ||
|
|
b5dc7d1c5b | ||
|
|
2358b735b1 | ||
|
|
e4736a7544 | ||
|
|
ccaf614b6b | ||
|
|
effa1c9192 | ||
|
|
ddfd61bfd1 | ||
|
|
b6cbf2f82b | ||
|
|
687c793203 | ||
|
|
dfd7620a64 | ||
|
|
21eb505b7b | ||
|
|
0d4e43e723 | ||
|
|
27d21b2a5b | ||
|
|
f6a325289d | ||
|
|
233833b85b | ||
|
|
fae99cff0c | ||
|
|
ec27e905b7 | ||
|
|
1e65705bb8 | ||
|
|
5b6451b584 | ||
|
|
391c468f81 | ||
|
|
074cf4e1d9 |
43
.github/workflows/codeql-analysis.yml
vendored
43
.github/workflows/codeql-analysis.yml
vendored
@@ -1,44 +1,53 @@
|
||||
# For most projects, this workflow file will not need changing; you simply need
|
||||
# to commit it to your repository.
|
||||
#
|
||||
# You may wish to alter this file to override the set of languages analyzed,
|
||||
# or to provide custom queries or build logic.
|
||||
#
|
||||
# ******** NOTE ********
|
||||
# We have attempted to detect the languages in your repository. Please check
|
||||
# the `language` matrix defined below to confirm you have the correct set of
|
||||
# supported CodeQL languages.
|
||||
#
|
||||
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'
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
analyze:
|
||||
name: Analyze
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
actions: read
|
||||
contents: read
|
||||
security-events: write
|
||||
|
||||
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@v4
|
||||
- name: Harden Runner
|
||||
uses: step-security/harden-runner@20cf305ff2072d973412fa9b1e3a4f227bda3c76 # v2.14.0
|
||||
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
|
||||
egress-policy: audit
|
||||
|
||||
# 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' }}
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v6.0.1
|
||||
|
||||
# Initializes the CodeQL tools for scanning.
|
||||
- name: Initialize CodeQL
|
||||
uses: github/codeql-action/init@v3
|
||||
uses: github/codeql-action/init@5d4e8d1aca955e8d8589aabd499c5cae939e33c7 # v4.31.9
|
||||
with:
|
||||
languages: ${{ matrix.language }}
|
||||
# If you wish to specify custom queries, you can do so here or in a config file.
|
||||
@@ -49,7 +58,7 @@ jobs:
|
||||
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
|
||||
# If this step fails, then you should remove it and run the build manually (see below)
|
||||
- name: Autobuild
|
||||
uses: github/codeql-action/autobuild@v3
|
||||
uses: github/codeql-action/autobuild@5d4e8d1aca955e8d8589aabd499c5cae939e33c7 # v4.31.9
|
||||
|
||||
# ℹ️ Command-line programs to run using the OS shell.
|
||||
# 📚 https://git.io/JvXDl
|
||||
@@ -63,4 +72,4 @@ jobs:
|
||||
# make release
|
||||
|
||||
- name: Perform CodeQL Analysis
|
||||
uses: github/codeql-action/analyze@v3
|
||||
uses: github/codeql-action/analyze@5d4e8d1aca955e8d8589aabd499c5cae939e33c7 # v4.31.9
|
||||
|
||||
27
.github/workflows/dependency-review.yml
vendored
Normal file
27
.github/workflows/dependency-review.yml
vendored
Normal file
@@ -0,0 +1,27 @@
|
||||
# Dependency Review Action
|
||||
#
|
||||
# This Action will scan dependency manifest files that change as part of a Pull Request,
|
||||
# surfacing known-vulnerable versions of the packages declared or updated in the PR.
|
||||
# Once installed, if the workflow run is marked as required,
|
||||
# PRs introducing known-vulnerable packages will be blocked from merging.
|
||||
#
|
||||
# Source repository: https://github.com/actions/dependency-review-action
|
||||
name: 'Dependency Review'
|
||||
on: [pull_request]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
dependency-review:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Harden Runner
|
||||
uses: step-security/harden-runner@20cf305ff2072d973412fa9b1e3a4f227bda3c76 # v2.14.0
|
||||
with:
|
||||
egress-policy: audit
|
||||
|
||||
- name: 'Checkout Repository'
|
||||
uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v6.0.1
|
||||
- name: 'Dependency Review'
|
||||
uses: actions/dependency-review-action@3c4e3dcb1aa7874d2c16be7d79418e9b7efd6261 # v4.8.2
|
||||
12
.github/workflows/go.yml
vendored
12
.github/workflows/go.yml
vendored
@@ -1,13 +1,21 @@
|
||||
name: Go
|
||||
on: [push, pull_request]
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
|
||||
build:
|
||||
name: Build
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-go@v5
|
||||
- name: Harden Runner
|
||||
uses: step-security/harden-runner@20cf305ff2072d973412fa9b1e3a4f227bda3c76 # v2.14.0
|
||||
with:
|
||||
egress-policy: audit
|
||||
|
||||
- uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v6.0.1
|
||||
- uses: actions/setup-go@4dc6199c7b1a012772edbd06daecab0f50c9053c # v6.1.0
|
||||
with:
|
||||
go-version: 'stable'
|
||||
|
||||
|
||||
19
.github/workflows/release.yaml
vendored
19
.github/workflows/release.yaml
vendored
@@ -4,9 +4,8 @@ on:
|
||||
release:
|
||||
types: [created]
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
packages: write
|
||||
# Declare default permissions as read only.
|
||||
permissions: read-all
|
||||
|
||||
jobs:
|
||||
releases-matrix:
|
||||
@@ -16,19 +15,27 @@ jobs:
|
||||
matrix:
|
||||
goos: [freebsd, linux, windows]
|
||||
goarch: [amd64, arm64]
|
||||
permissions:
|
||||
contents: write
|
||||
packages: write
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Harden Runner
|
||||
uses: step-security/harden-runner@20cf305ff2072d973412fa9b1e3a4f227bda3c76 # v2.14.0
|
||||
with:
|
||||
egress-policy: audit
|
||||
|
||||
- uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v6.0.1
|
||||
|
||||
- name: Set APP_VERSION env
|
||||
run: echo APP_VERSION=$(echo ${GITHUB_REF} | rev | cut -d'/' -f 1 | rev ) >> ${GITHUB_ENV}
|
||||
- name: Set BUILD_TIME env
|
||||
run: echo BUILD_TIME=$(date) >> ${GITHUB_ENV}
|
||||
|
||||
- uses: wangyoucao577/go-release-action@v1
|
||||
- uses: wangyoucao577/go-release-action@279495102627de7960cbc33434ab01a12bae144b # v1.55
|
||||
with:
|
||||
github_token: ${{ secrets.GITHUB_TOKEN }}
|
||||
goos: ${{ matrix.goos }}
|
||||
goarch: ${{ matrix.goarch }}
|
||||
goversion: "1.22"
|
||||
extra_files: LICENSE README.md smtprelay.ini
|
||||
ldflags: -s -w -X "main.appVersion=${{ env.APP_VERSION }}" -X "main.buildTime=${{ env.BUILD_TIME }}"
|
||||
|
||||
81
.github/workflows/scorecards.yml
vendored
Normal file
81
.github/workflows/scorecards.yml
vendored
Normal file
@@ -0,0 +1,81 @@
|
||||
# This workflow uses actions that are not certified by GitHub. They are provided
|
||||
# by a third-party and are governed by separate terms of service, privacy
|
||||
# policy, and support documentation.
|
||||
|
||||
name: Scorecard supply-chain security
|
||||
on:
|
||||
# For Branch-Protection check. Only the default branch is supported. See
|
||||
# https://github.com/ossf/scorecard/blob/main/docs/checks.md#branch-protection
|
||||
branch_protection_rule:
|
||||
# To guarantee Maintained check is occasionally updated. See
|
||||
# https://github.com/ossf/scorecard/blob/main/docs/checks.md#maintained
|
||||
schedule:
|
||||
- cron: '20 7 * * 2'
|
||||
push:
|
||||
branches: ["master"]
|
||||
|
||||
# Declare default permissions as read only.
|
||||
permissions: read-all
|
||||
|
||||
jobs:
|
||||
analysis:
|
||||
name: Scorecard analysis
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
# Needed to upload the results to code-scanning dashboard.
|
||||
security-events: write
|
||||
# Needed to publish results and get a badge (see publish_results below).
|
||||
id-token: write
|
||||
contents: read
|
||||
actions: read
|
||||
# To allow GraphQL ListCommits to work
|
||||
issues: read
|
||||
pull-requests: read
|
||||
# To detect SAST tools
|
||||
checks: read
|
||||
|
||||
steps:
|
||||
- name: Harden Runner
|
||||
uses: step-security/harden-runner@20cf305ff2072d973412fa9b1e3a4f227bda3c76 # v2.14.0
|
||||
with:
|
||||
egress-policy: audit
|
||||
|
||||
- name: "Checkout code"
|
||||
uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v6.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: "Run analysis"
|
||||
uses: ossf/scorecard-action@4eaacf0543bb3f2c246792bd56e8cdeffafb205a # v2.4.3
|
||||
with:
|
||||
results_file: results.sarif
|
||||
results_format: sarif
|
||||
# (Optional) "write" PAT token. Uncomment the `repo_token` line below if:
|
||||
# - you want to enable the Branch-Protection check on a *public* repository, or
|
||||
# - you are installing Scorecards on a *private* repository
|
||||
# To create the PAT, follow the steps in https://github.com/ossf/scorecard-action#authentication-with-pat.
|
||||
# repo_token: ${{ secrets.SCORECARD_TOKEN }}
|
||||
|
||||
# Public repositories:
|
||||
# - Publish results to OpenSSF REST API for easy access by consumers
|
||||
# - Allows the repository to include the Scorecard badge.
|
||||
# - See https://github.com/ossf/scorecard-action#publishing-results.
|
||||
# For private repositories:
|
||||
# - `publish_results` will always be set to `false`, regardless
|
||||
# of the value entered here.
|
||||
publish_results: true
|
||||
|
||||
# Upload the results as artifacts (optional). Commenting out will disable uploads of run results in SARIF
|
||||
# format to the repository Actions tab.
|
||||
- name: "Upload artifact"
|
||||
uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
|
||||
with:
|
||||
name: SARIF file
|
||||
path: results.sarif
|
||||
retention-days: 5
|
||||
|
||||
# Upload the results to GitHub's code scanning dashboard.
|
||||
- name: "Upload to code-scanning"
|
||||
uses: github/codeql-action/upload-sarif@5d4e8d1aca955e8d8589aabd499c5cae939e33c7 # v4.31.9
|
||||
with:
|
||||
sarif_file: results.sarif
|
||||
@@ -1,6 +1,7 @@
|
||||
# smtprelay
|
||||
|
||||
[](https://goreportcard.com/report/github.com/decke/smtprelay)
|
||||
[](https://scorecard.dev/viewer/?uri=github.com/decke/smtprelay)
|
||||
|
||||
Simple Golang based SMTP relay/proxy server that accepts mail via SMTP
|
||||
and forwards it directly to another SMTP server.
|
||||
@@ -30,3 +31,4 @@ device which produces mail.
|
||||
* Forwards all mail to a smarthost (any SMTP server)
|
||||
* Small codebase
|
||||
* IPv6 support
|
||||
* Aliases support (dynamic reload when alias file changes)
|
||||
51
SECURITY.md
Normal file
51
SECURITY.md
Normal file
@@ -0,0 +1,51 @@
|
||||
# smtprelay Security Policy
|
||||
|
||||
This document outlines security procedures and general policies for the
|
||||
smtprelay project.
|
||||
|
||||
## Supported Versions
|
||||
|
||||
The latest release is the only supported release.
|
||||
|
||||
|
||||
## Disclosing a security issue
|
||||
|
||||
The smtprelay maintainers take all security issues in the project seriously.
|
||||
Thank you for improving the security of the project! We appreciate your
|
||||
dedication to responsible disclosure and will make every effort to acknowledge
|
||||
your contributions.
|
||||
|
||||
smtprelay leverages GitHub's private vulnerability reporting.
|
||||
|
||||
To learn more about this feature and how to submit a vulnerability report,
|
||||
review [GitHub's documentation on private reporting](https://docs.github.com/code-security/security-advisories/guidance-on-reporting-and-writing-information-about-vulnerabilities/privately-reporting-a-security-vulnerability).
|
||||
|
||||
Here are some helpful details to include in your report:
|
||||
|
||||
- a detailed description of the issue
|
||||
- the steps required to reproduce the issue
|
||||
- versions of the project that may be affected by the issue
|
||||
- if known, any mitigations for the issue
|
||||
|
||||
A maintainer will acknowledge the report within three (3) business days, and
|
||||
will send a more detailed response within an additional three (3) business days
|
||||
indicating the next steps in handling your report.
|
||||
|
||||
After the initial reply to your report, the maintainers will endeavor to keep
|
||||
you informed of the progress towards a fix and full announcement, and may ask
|
||||
for additional information or guidance.
|
||||
|
||||
## Vulnerability management
|
||||
|
||||
When the maintainers receive a disclosure report, they will coordinate the
|
||||
fix and release process, which involves the following steps:
|
||||
|
||||
- confirming the issue
|
||||
- determining affected versions of the project
|
||||
- auditing code to find any potential similar problems
|
||||
- preparing fixes for all releases under maintenance
|
||||
|
||||
## Suggesting changes
|
||||
|
||||
If you have suggestions on how this process could be improved please submit an
|
||||
issue or pull request.
|
||||
72
aliases.go
Normal file
72
aliases.go
Normal file
@@ -0,0 +1,72 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
)
|
||||
|
||||
type AliasMap map[string]string
|
||||
|
||||
var (
|
||||
aliasesMutex sync.RWMutex
|
||||
)
|
||||
|
||||
func AliasLoadFile(file string) (AliasMap, error) {
|
||||
aliasMap := make(AliasMap)
|
||||
count := 0
|
||||
log.Info().
|
||||
Str("file", file).
|
||||
Msg("Loading aliases file")
|
||||
|
||||
f, err := os.Open(file)
|
||||
if err != nil {
|
||||
log.Fatal().
|
||||
Str("file", file).
|
||||
Err(err).
|
||||
Msg("cannot load aliases file")
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
scanner := bufio.NewScanner(f)
|
||||
for scanner.Scan() {
|
||||
line := strings.TrimSpace(scanner.Text())
|
||||
if line == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
parts := strings.Fields(line)
|
||||
if len(parts) >= 2 {
|
||||
aliasMap[parts[0]] = parts[1]
|
||||
count++
|
||||
}
|
||||
}
|
||||
log.Info().
|
||||
Str("file", file).
|
||||
Msg(fmt.Sprintf("Loaded %d aliases from file", count))
|
||||
|
||||
if err := scanner.Err(); err != nil {
|
||||
log.Fatal().
|
||||
Str("file", file).
|
||||
Err(err).
|
||||
Msg("cannot load aliases file")
|
||||
}
|
||||
return aliasMap, nil
|
||||
}
|
||||
|
||||
func LoadAliases(filename string) error {
|
||||
newAliases, err := AliasLoadFile(filename)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
aliasesMutex.Lock()
|
||||
defer aliasesMutex.Unlock()
|
||||
|
||||
// Update the aliases map
|
||||
aliasesList = newAliases
|
||||
|
||||
return nil
|
||||
}
|
||||
315
aliases_test.go
Normal file
315
aliases_test.go
Normal file
@@ -0,0 +1,315 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"io"
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/rs/zerolog"
|
||||
)
|
||||
|
||||
func init() {
|
||||
// Initialize logger for tests to prevent nil pointer dereference
|
||||
logger := zerolog.New(io.Discard).With().Timestamp().Logger()
|
||||
log = &logger
|
||||
}
|
||||
func TestAliasLoadFile(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
content string
|
||||
expected AliasMap
|
||||
expectError bool
|
||||
}{
|
||||
{
|
||||
name: "valid aliases",
|
||||
content: "user1 alias1\nuser2 alias2\nuser3 alias3",
|
||||
expected: AliasMap{
|
||||
"user1": "alias1",
|
||||
"user2": "alias2",
|
||||
"user3": "alias3",
|
||||
},
|
||||
expectError: false,
|
||||
},
|
||||
{
|
||||
name: "empty file",
|
||||
content: "",
|
||||
expected: AliasMap{},
|
||||
expectError: false,
|
||||
},
|
||||
{
|
||||
name: "file with empty lines",
|
||||
content: "user1 alias1\n\nuser2 alias2\n\n",
|
||||
expected: AliasMap{
|
||||
"user1": "alias1",
|
||||
"user2": "alias2",
|
||||
},
|
||||
expectError: false,
|
||||
},
|
||||
{
|
||||
name: "file with whitespace",
|
||||
content: " user1 alias1 \n\t user2\talias2\t",
|
||||
expected: AliasMap{
|
||||
"user1": "alias1",
|
||||
"user2": "alias2",
|
||||
},
|
||||
expectError: false,
|
||||
},
|
||||
{
|
||||
name: "extra fields ignored",
|
||||
content: "user1 alias1 extra field\nuser2 alias2",
|
||||
expected: AliasMap{
|
||||
"user1": "alias1",
|
||||
"user2": "alias2",
|
||||
},
|
||||
expectError: false,
|
||||
},
|
||||
{
|
||||
name: "single field line ignored",
|
||||
content: "user1\nuser2 alias2",
|
||||
expected: AliasMap{"user2": "alias2"},
|
||||
expectError: false,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
tmpFile, err := os.CreateTemp("", "aliases-*.txt")
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create temp file: %v", err)
|
||||
}
|
||||
defer os.Remove(tmpFile.Name())
|
||||
|
||||
if _, err := tmpFile.WriteString(tt.content); err != nil {
|
||||
t.Fatalf("failed to write to temp file: %v", err)
|
||||
}
|
||||
tmpFile.Close()
|
||||
|
||||
result, err := AliasLoadFile(tmpFile.Name())
|
||||
|
||||
if tt.expectError && err == nil {
|
||||
t.Error("expected error but got none")
|
||||
}
|
||||
if !tt.expectError && err != nil {
|
||||
t.Errorf("unexpected error: %v", err)
|
||||
}
|
||||
|
||||
if len(result) != len(tt.expected) {
|
||||
t.Errorf("expected %d aliases, got %d", len(tt.expected), len(result))
|
||||
}
|
||||
|
||||
for key, expectedValue := range tt.expected {
|
||||
if actualValue, exists := result[key]; !exists {
|
||||
t.Errorf("expected key %q not found", key)
|
||||
} else if actualValue != expectedValue {
|
||||
t.Errorf("for key %q: expected %q, got %q", key, expectedValue, actualValue)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadAliases(t *testing.T) {
|
||||
tmpFile, err := os.CreateTemp("", "aliases-*.txt")
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create temp file: %v", err)
|
||||
}
|
||||
defer os.Remove(tmpFile.Name())
|
||||
|
||||
content := "user1 alias1\nuser2 alias2"
|
||||
if _, err := tmpFile.WriteString(content); err != nil {
|
||||
t.Fatalf("failed to write to temp file: %v", err)
|
||||
}
|
||||
tmpFile.Close()
|
||||
|
||||
err = LoadAliases(tmpFile.Name())
|
||||
if err != nil {
|
||||
t.Errorf("unexpected error: %v", err)
|
||||
}
|
||||
|
||||
aliasesMutex.RLock()
|
||||
defer aliasesMutex.RUnlock()
|
||||
|
||||
if len(aliasesList) != 2 {
|
||||
t.Errorf("expected 2 aliases, got %d", len(aliasesList))
|
||||
}
|
||||
|
||||
if aliasesList["user1"] != "alias1" {
|
||||
t.Errorf("expected user1 -> alias1, got %q", aliasesList["user1"])
|
||||
}
|
||||
if aliasesList["user2"] != "alias2" {
|
||||
t.Errorf("expected user2 -> alias2, got %q", aliasesList["user2"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadAliases_EmptyFile(t *testing.T) {
|
||||
tmpFile, err := os.CreateTemp("", "aliases-*.txt")
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create temp file: %v", err)
|
||||
}
|
||||
defer os.Remove(tmpFile.Name())
|
||||
tmpFile.Close()
|
||||
|
||||
err = LoadAliases(tmpFile.Name())
|
||||
if err != nil {
|
||||
t.Errorf("unexpected error: %v", err)
|
||||
}
|
||||
|
||||
aliasesMutex.RLock()
|
||||
defer aliasesMutex.RUnlock()
|
||||
|
||||
if len(aliasesList) != 0 {
|
||||
t.Errorf("expected 0 aliases, got %d", len(aliasesList))
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadAliases_UpdatesExistingAliases(t *testing.T) {
|
||||
// First load
|
||||
tmpFile1, err := os.CreateTemp("", "aliases-*.txt")
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create temp file: %v", err)
|
||||
}
|
||||
defer os.Remove(tmpFile1.Name())
|
||||
|
||||
content1 := "user1 alias1\nuser2 alias2"
|
||||
if _, err := tmpFile1.WriteString(content1); err != nil {
|
||||
t.Fatalf("failed to write to temp file: %v", err)
|
||||
}
|
||||
tmpFile1.Close()
|
||||
|
||||
err = LoadAliases(tmpFile1.Name())
|
||||
if err != nil {
|
||||
t.Errorf("unexpected error: %v", err)
|
||||
}
|
||||
|
||||
// Second load with different content
|
||||
tmpFile2, err := os.CreateTemp("", "aliases-*.txt")
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create temp file: %v", err)
|
||||
}
|
||||
defer os.Remove(tmpFile2.Name())
|
||||
|
||||
content2 := "user3 alias3"
|
||||
if _, err := tmpFile2.WriteString(content2); err != nil {
|
||||
t.Fatalf("failed to write to temp file: %v", err)
|
||||
}
|
||||
tmpFile2.Close()
|
||||
|
||||
err = LoadAliases(tmpFile2.Name())
|
||||
if err != nil {
|
||||
t.Errorf("unexpected error: %v", err)
|
||||
}
|
||||
|
||||
aliasesMutex.RLock()
|
||||
defer aliasesMutex.RUnlock()
|
||||
|
||||
if len(aliasesList) != 1 {
|
||||
t.Errorf("expected 1 alias after reload, got %d", len(aliasesList))
|
||||
}
|
||||
|
||||
if aliasesList["user3"] != "alias3" {
|
||||
t.Errorf("expected user3 -> alias3, got %q", aliasesList["user3"])
|
||||
}
|
||||
|
||||
if _, exists := aliasesList["user1"]; exists {
|
||||
t.Error("expected user1 to be removed after reload")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAliasLoadFile_MultipleSpaces(t *testing.T) {
|
||||
tmpFile, err := os.CreateTemp("", "aliases-*.txt")
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create temp file: %v", err)
|
||||
}
|
||||
defer os.Remove(tmpFile.Name())
|
||||
|
||||
content := "user1 alias1\nuser2 alias2"
|
||||
if _, err := tmpFile.WriteString(content); err != nil {
|
||||
t.Fatalf("failed to write to temp file: %v", err)
|
||||
}
|
||||
tmpFile.Close()
|
||||
|
||||
result, err := AliasLoadFile(tmpFile.Name())
|
||||
if err != nil {
|
||||
t.Errorf("unexpected error: %v", err)
|
||||
}
|
||||
|
||||
if result["user1"] != "alias1" {
|
||||
t.Errorf("expected user1 -> alias1, got %q", result["user1"])
|
||||
}
|
||||
if result["user2"] != "alias2" {
|
||||
t.Errorf("expected user2 -> alias2, got %q", result["user2"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestAliasLoadFile_TabSeparated(t *testing.T) {
|
||||
tmpFile, err := os.CreateTemp("", "aliases-*.txt")
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create temp file: %v", err)
|
||||
}
|
||||
defer os.Remove(tmpFile.Name())
|
||||
|
||||
content := "user1\talias1\nuser2\t\talias2"
|
||||
if _, err := tmpFile.WriteString(content); err != nil {
|
||||
t.Fatalf("failed to write to temp file: %v", err)
|
||||
}
|
||||
tmpFile.Close()
|
||||
|
||||
result, err := AliasLoadFile(tmpFile.Name())
|
||||
if err != nil {
|
||||
t.Errorf("unexpected error: %v", err)
|
||||
}
|
||||
|
||||
if len(result) != 2 {
|
||||
t.Errorf("expected 2 aliases, got %d", len(result))
|
||||
}
|
||||
}
|
||||
|
||||
func TestAliasLoadFile_DuplicateKeys(t *testing.T) {
|
||||
tmpFile, err := os.CreateTemp("", "aliases-*.txt")
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create temp file: %v", err)
|
||||
}
|
||||
defer os.Remove(tmpFile.Name())
|
||||
|
||||
content := "user1 alias1\nuser1 alias2\nuser1 alias3"
|
||||
if _, err := tmpFile.WriteString(content); err != nil {
|
||||
t.Fatalf("failed to write to temp file: %v", err)
|
||||
}
|
||||
tmpFile.Close()
|
||||
|
||||
result, err := AliasLoadFile(tmpFile.Name())
|
||||
if err != nil {
|
||||
t.Errorf("unexpected error: %v", err)
|
||||
}
|
||||
|
||||
if len(result) != 1 {
|
||||
t.Errorf("expected 1 alias (last one wins), got %d", len(result))
|
||||
}
|
||||
|
||||
if result["user1"] != "alias3" {
|
||||
t.Errorf("expected user1 -> alias3 (last one), got %q", result["user1"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestAliasLoadFile_OnlyWhitespace(t *testing.T) {
|
||||
tmpFile, err := os.CreateTemp("", "aliases-*.txt")
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create temp file: %v", err)
|
||||
}
|
||||
defer os.Remove(tmpFile.Name())
|
||||
|
||||
content := " \n\t\t\n \t \n"
|
||||
if _, err := tmpFile.WriteString(content); err != nil {
|
||||
t.Fatalf("failed to write to temp file: %v", err)
|
||||
}
|
||||
tmpFile.Close()
|
||||
|
||||
result, err := AliasLoadFile(tmpFile.Name())
|
||||
if err != nil {
|
||||
t.Errorf("unexpected error: %v", err)
|
||||
}
|
||||
|
||||
if len(result) != 0 {
|
||||
t.Errorf("expected 0 aliases, got %d", len(result))
|
||||
}
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
|
||||
To run the hasher, do like this
|
||||
|
||||
```bash
|
||||
$ go run hasher.go hunter2
|
||||
```
|
||||
@@ -1,22 +0,0 @@
|
||||
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))
|
||||
}
|
||||
94
config.go
94
config.go
@@ -12,7 +12,6 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/peterbourgon/ff/v3"
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -43,6 +42,7 @@ var (
|
||||
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")
|
||||
aliasFile = flagset.String("aliases_file", "", "Path to aliases file")
|
||||
command = flagset.String("command", "", "Path to pipe command")
|
||||
remotesStr = flagset.String("remotes", "", "Outgoing SMTP servers")
|
||||
strictSender = flagset.Bool("strict_sender", false, "Use only SMTP servers with Sender matches to From")
|
||||
@@ -60,28 +60,44 @@ var (
|
||||
allowedSender *regexp.Regexp
|
||||
allowedRecipients *regexp.Regexp
|
||||
remotes = []*Remote{}
|
||||
aliasesList = AliasMap{}
|
||||
)
|
||||
|
||||
func localAuthRequired() bool {
|
||||
return *allowedUsers != ""
|
||||
}
|
||||
|
||||
func setupAliases() {
|
||||
if *aliasFile != "" {
|
||||
aliases := make(AliasMap)
|
||||
aliases, err := AliasLoadFile(*aliasFile)
|
||||
if err != nil {
|
||||
log.Fatal().
|
||||
Str("file", *aliasFile).
|
||||
Err(err).
|
||||
Msg("cannot load aliases file")
|
||||
}
|
||||
aliasesList = aliases
|
||||
}
|
||||
}
|
||||
|
||||
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")
|
||||
log.Fatal().
|
||||
Str("netstr", netstr).
|
||||
Err(err).
|
||||
Msg("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)")
|
||||
log.Fatal().
|
||||
Str("given_net", netstr).
|
||||
Str("proper_net", allowedNet.String()).
|
||||
Msg("Invalid network in allowed_nets (host bits set)")
|
||||
}
|
||||
|
||||
allowedNets = append(allowedNets, allowedNet)
|
||||
@@ -94,30 +110,32 @@ func setupAllowedPatterns() {
|
||||
if *allowedSenderStr != "" {
|
||||
allowedSender, err = regexp.Compile(*allowedSenderStr)
|
||||
if err != nil {
|
||||
log.WithField("allowed_sender", *allowedSenderStr).
|
||||
WithError(err).
|
||||
Fatal("allowed_sender pattern invalid")
|
||||
log.Fatal().
|
||||
Str("allowed_sender", *allowedSenderStr).
|
||||
Err(err).
|
||||
Msg("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")
|
||||
log.Fatal().
|
||||
Str("allowed_recipients", *allowedRecipStr).
|
||||
Err(err).
|
||||
Msg("allowed_recipients pattern invalid")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func setupRemotes() {
|
||||
logger := log.WithField("remotes", *remotesStr)
|
||||
logger := log.With().Str("remotes", *remotesStr).Logger()
|
||||
|
||||
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))
|
||||
logger.Fatal().Msg(fmt.Sprintf("error parsing url: '%s': %v", remoteURL, err))
|
||||
}
|
||||
|
||||
remotes = append(remotes, r)
|
||||
@@ -148,8 +166,9 @@ func setupListeners() {
|
||||
pa := splitProto(listenAddr)
|
||||
|
||||
if localAuthRequired() && pa.protocol == "" {
|
||||
log.WithField("address", pa.address).
|
||||
Fatal("Local authentication (via allowed_users file) " +
|
||||
log.Fatal().
|
||||
Str("address", pa.address).
|
||||
Msg("Local authentication (via allowed_users file) " +
|
||||
"not allowed with non-TLS listener")
|
||||
}
|
||||
|
||||
@@ -162,35 +181,41 @@ func setupTimeouts() {
|
||||
|
||||
readTimeout, err = time.ParseDuration(*readTimeoutStr)
|
||||
if err != nil {
|
||||
log.WithField("read_timeout", *readTimeoutStr).
|
||||
WithError(err).
|
||||
Fatal("read_timeout duration string invalid")
|
||||
log.Fatal().
|
||||
Str("read_timeout", *readTimeoutStr).
|
||||
Err(err).
|
||||
Msg("read_timeout duration string invalid")
|
||||
}
|
||||
if readTimeout.Seconds() < 1 {
|
||||
log.WithField("read_timeout", *readTimeoutStr).
|
||||
Fatal("read_timeout less than one second")
|
||||
log.Fatal().
|
||||
Str("read_timeout", *readTimeoutStr).
|
||||
Msg("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")
|
||||
log.Fatal().
|
||||
Str("write_timeout", *writeTimeoutStr).
|
||||
Err(err).
|
||||
Msg("write_timeout duration string invalid")
|
||||
}
|
||||
if writeTimeout.Seconds() < 1 {
|
||||
log.WithField("write_timeout", *writeTimeoutStr).
|
||||
Fatal("write_timeout less than one second")
|
||||
log.Fatal().
|
||||
Str("write_timeout", *writeTimeoutStr).
|
||||
Msg("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")
|
||||
log.Fatal().
|
||||
Str("data_timeout", *dataTimeoutStr).
|
||||
Err(err).
|
||||
Msg("data_timeout duration string invalid")
|
||||
}
|
||||
if dataTimeout.Seconds() < 1 {
|
||||
log.WithField("data_timeout", *dataTimeoutStr).
|
||||
Fatal("data_timeout less than one second")
|
||||
log.Fatal().
|
||||
Str("data_timeout", *dataTimeoutStr).
|
||||
Msg("data_timeout less than one second")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -226,11 +251,12 @@ func ConfigLoad() {
|
||||
}
|
||||
|
||||
if *remotesStr == "" && *command == "" {
|
||||
log.Warn("no remotes or command set; mail will not be forwarded!")
|
||||
log.Warn().Msg("no remotes or command set; mail will not be forwarded!")
|
||||
}
|
||||
|
||||
setupAllowedNetworks()
|
||||
setupAllowedPatterns()
|
||||
setupAliases()
|
||||
setupRemotes()
|
||||
setupListeners()
|
||||
setupTimeouts()
|
||||
|
||||
17
go.mod
17
go.mod
@@ -1,21 +1,24 @@
|
||||
module github.com/decke/smtprelay
|
||||
|
||||
require (
|
||||
github.com/DeRuina/timberjack v1.3.9
|
||||
github.com/chrj/smtpd v0.3.1
|
||||
github.com/fsnotify/fsnotify v1.9.0
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/peterbourgon/ff/v3 v3.4.0
|
||||
github.com/sirupsen/logrus v1.9.3
|
||||
github.com/stretchr/testify v1.9.0
|
||||
golang.org/x/crypto v0.23.0
|
||||
github.com/rs/zerolog v1.34.0
|
||||
github.com/stretchr/testify v1.11.1
|
||||
golang.org/x/crypto v0.46.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/davecgh/go-spew v1.1.1 // indirect
|
||||
github.com/kr/pretty v0.3.1 // indirect
|
||||
github.com/klauspost/compress v1.18.1 // indirect
|
||||
github.com/mattn/go-colorable v0.1.14 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/pmezard/go-difflib v1.0.0 // indirect
|
||||
golang.org/x/sys v0.20.0 // indirect
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect
|
||||
golang.org/x/sys v0.39.0 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
)
|
||||
|
||||
go 1.20
|
||||
go 1.24.3
|
||||
|
||||
57
go.sum
57
go.sum
@@ -1,39 +1,44 @@
|
||||
github.com/DeRuina/timberjack v1.3.9 h1:6UXZ1I7ExPGTX/1UNYawR58LlOJUHKBPiYC7WQ91eBo=
|
||||
github.com/DeRuina/timberjack v1.3.9/go.mod h1:RLoeQrwrCGIEF8gO5nV5b/gMD0QIy7bzQhBUgpp1EqE=
|
||||
github.com/chrj/smtpd v0.3.1 h1:kogHFkbFdKaoH3bgZkqNC9uVtKYOFfM3uV3rroBdooE=
|
||||
github.com/chrj/smtpd v0.3.1/go.mod h1:JtABvV/LzvLmEIzy0NyDnrfMGOMd8wy5frAokwf6J9Q=
|
||||
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=
|
||||
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/fortytw2/leaktest v1.3.0 h1:u8491cBMTQ8ft8aeV+adlcytMZylmA5nnwwkRZjI8vw=
|
||||
github.com/fortytw2/leaktest v1.3.0/go.mod h1:jDsjWgpAGjm2CA7WthBh/CdZYEPF31XHquHwclZch5g=
|
||||
github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=
|
||||
github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=
|
||||
github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=
|
||||
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
||||
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
|
||||
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
|
||||
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
|
||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||
github.com/klauspost/compress v1.18.1 h1:bcSGx7UbpBqMChDtsF28Lw6v/G94LPrrbMbdC3JH2co=
|
||||
github.com/klauspost/compress v1.18.1/go.mod h1:ZQFFVG+MdnR0P+l6wpXgIL4NTtwiKIdBnrBd8Nrxr+0=
|
||||
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
|
||||
github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE=
|
||||
github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
|
||||
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
|
||||
github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/peterbourgon/ff/v3 v3.4.0 h1:QBvM/rizZM1cB0p0lGMdmR7HxZeI/ZrBWB4DqLkMUBc=
|
||||
github.com/peterbourgon/ff/v3 v3.4.0/go.mod h1:zjJVUhx+twciwfDl0zBcFzl4dW8axCRyXE/eKY9RztQ=
|
||||
github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA=
|
||||
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8=
|
||||
github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=
|
||||
github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
|
||||
github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
|
||||
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
||||
golang.org/x/crypto v0.23.0 h1:dIJU/v2J8Mdglj/8rJ6UUOM3Zc9zLZxVZwwxMooUSAI=
|
||||
golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8=
|
||||
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.20.0 h1:Od9JTbYCk261bKm4M/mw7AklTlFYIa0bIp9BgSm1S8Y=
|
||||
golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
github.com/rs/xid v1.6.0/go.mod h1:7XoLgs4eV+QndskICGsho+ADou8ySMSjJKDIan90Nz0=
|
||||
github.com/rs/zerolog v1.34.0 h1:k43nTLIwcTVQAncfCw4KZ2VY6ukYoZaBPNOE8txlOeY=
|
||||
github.com/rs/zerolog v1.34.0/go.mod h1:bJsvje4Z08ROH4Nhs5iH600c3IkWhwp44iRc54W6wYQ=
|
||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
golang.org/x/crypto v0.46.0 h1:cKRW/pmt1pKAfetfu+RCEvjvZkA9RimPbh7bhFjGVBU=
|
||||
golang.org/x/crypto v0.46.0/go.mod h1:Evb/oLKmMraqjZ2iQTwDwvCtJkczlDuTmdJXoZVzqU0=
|
||||
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.39.0 h1:CvCKL8MeisomCi6qNZ+wbb0DN9E5AATixKsvNtMoMFk=
|
||||
golang.org/x/sys v0.39.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||
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/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
|
||||
79
logger.go
79
logger.go
@@ -2,59 +2,84 @@ package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
"github.com/DeRuina/timberjack"
|
||||
"github.com/rs/zerolog"
|
||||
)
|
||||
|
||||
var (
|
||||
log *logrus.Logger
|
||||
rotator *timberjack.Logger
|
||||
log *zerolog.Logger
|
||||
)
|
||||
|
||||
func setupLogger() {
|
||||
log = logrus.New()
|
||||
zerolog.TimeFieldFormat = time.RFC3339
|
||||
|
||||
// Handle logfile
|
||||
var writer io.Writer
|
||||
if *logFile == "" {
|
||||
log.SetOutput(os.Stderr)
|
||||
writer = 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)
|
||||
rotator = &timberjack.Logger{
|
||||
Filename: *logFile,
|
||||
MaxSize: 10, // megabytes before rotation
|
||||
MaxBackups: 3,
|
||||
MaxAge: 30, // days
|
||||
Compress: true,
|
||||
BackupTimeFormat: "20060102150405",
|
||||
}
|
||||
|
||||
log.SetOutput(writer)
|
||||
writer = rotator
|
||||
}
|
||||
|
||||
// Handle log_format
|
||||
switch *logFormat {
|
||||
case "json":
|
||||
log.SetFormatter(&logrus.JSONFormatter{
|
||||
TimestampFormat: time.RFC3339Nano,
|
||||
DisableHTMLEscape: true,
|
||||
})
|
||||
// zerolog default is JSON
|
||||
case "plain":
|
||||
log.SetFormatter(&logrus.TextFormatter{
|
||||
DisableTimestamp: true,
|
||||
})
|
||||
writer = zerolog.ConsoleWriter{
|
||||
Out: writer,
|
||||
NoColor: true,
|
||||
TimeFormat: "",
|
||||
FormatTimestamp: func(i interface{}) string {
|
||||
return "" // avoid default time
|
||||
},
|
||||
}
|
||||
case "", "default":
|
||||
log.SetFormatter(&logrus.TextFormatter{
|
||||
FullTimestamp: true,
|
||||
})
|
||||
writer = zerolog.ConsoleWriter{
|
||||
Out: writer,
|
||||
NoColor: true,
|
||||
TimeFormat: time.RFC3339,
|
||||
}
|
||||
case "pretty":
|
||||
writer = zerolog.ConsoleWriter{
|
||||
Out: writer,
|
||||
TimeFormat: time.RFC3339Nano,
|
||||
}
|
||||
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
|
||||
l := zerolog.New(writer).With().Timestamp().Logger()
|
||||
log = &l
|
||||
|
||||
log.WithField("given_level", *logLevel).
|
||||
Warn("could not parse log level, defaulting to 'info'")
|
||||
// Handle log_level
|
||||
level, err := zerolog.ParseLevel(strings.ToLower(*logLevel))
|
||||
if err != nil {
|
||||
level = zerolog.InfoLevel
|
||||
log.Warn().Str("given_level", *logLevel).
|
||||
Msg("could not parse log level, defaulting to 'info'")
|
||||
}
|
||||
zerolog.SetGlobalLevel(level)
|
||||
}
|
||||
|
||||
// Call this on shutdown if you want to close the rotator and stop timers cleanly
|
||||
func closeLogger() {
|
||||
if rotator != nil {
|
||||
rotator.Close()
|
||||
}
|
||||
log.SetLevel(level)
|
||||
}
|
||||
|
||||
268
main.go
268
main.go
@@ -13,8 +13,8 @@ import (
|
||||
"syscall"
|
||||
|
||||
"github.com/chrj/smtpd"
|
||||
"github.com/fsnotify/fsnotify"
|
||||
"github.com/google/uuid"
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
func connectionChecker(peer smtpd.Peer) error {
|
||||
@@ -32,9 +32,9 @@ func connectionChecker(peer smtpd.Peer) error {
|
||||
}
|
||||
}
|
||||
|
||||
log.WithFields(logrus.Fields{
|
||||
"ip": peerIP,
|
||||
}).Warn("Connection refused from address outside of allowed_nets")
|
||||
log.Warn().
|
||||
Str("ip", peerIP.String()).
|
||||
Msg("Connection refused from address outside of allowed_nets")
|
||||
return smtpd.Error{Code: 421, Message: "Denied"}
|
||||
}
|
||||
|
||||
@@ -87,19 +87,21 @@ func senderChecker(peer smtpd.Peer, addr string) error {
|
||||
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")
|
||||
log.Warn().
|
||||
Str("peer", peer.Addr.String()).
|
||||
Str("username", peer.Username).
|
||||
Err(err).
|
||||
Msg("could not fetch auth user")
|
||||
return smtpd.Error{Code: 451, Message: "Bad sender address"}
|
||||
}
|
||||
|
||||
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")
|
||||
log.Warn().
|
||||
Str("peer", peer.Addr.String()).
|
||||
Str("username", peer.Username).
|
||||
Str("sender_address", addr).
|
||||
Err(err).
|
||||
Msg("sender address not allowed for authenticated user")
|
||||
return smtpd.Error{Code: 451, Message: "Bad sender address"}
|
||||
}
|
||||
}
|
||||
@@ -114,10 +116,10 @@ func senderChecker(peer smtpd.Peer, addr string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
log.WithFields(logrus.Fields{
|
||||
"sender_address": addr,
|
||||
"peer": peer.Addr,
|
||||
}).Warn("sender address not allowed by allowed_sender pattern")
|
||||
log.Warn().
|
||||
Str("sender_address", addr).
|
||||
Str("peer", peer.Addr.String()).
|
||||
Msg("sender address not allowed by allowed_sender pattern")
|
||||
return smtpd.Error{Code: 451, Message: "Bad sender address"}
|
||||
}
|
||||
|
||||
@@ -132,20 +134,21 @@ func recipientChecker(peer smtpd.Peer, addr string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
log.WithFields(logrus.Fields{
|
||||
"peer": peer.Addr,
|
||||
"recipient_address": addr,
|
||||
}).Warn("recipient address not allowed by allowed_recipients pattern")
|
||||
log.Warn().
|
||||
Str("peer", peer.Addr.String()).
|
||||
Str("recipient_address", addr).
|
||||
Msg("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.WithFields(logrus.Fields{
|
||||
"peer": peer.Addr,
|
||||
"username": username,
|
||||
}).WithError(err).Warn("auth error")
|
||||
log.Warn().
|
||||
Str("peer", peer.Addr.String()).
|
||||
Str("username", username).
|
||||
Err(err).
|
||||
Msg("auth error")
|
||||
return smtpd.Error{Code: 535, Message: "Authentication credentials invalid"}
|
||||
}
|
||||
return nil
|
||||
@@ -157,12 +160,25 @@ func mailHandler(peer smtpd.Peer, env smtpd.Envelope) error {
|
||||
peerIP = addr.IP.String()
|
||||
}
|
||||
|
||||
logger := log.WithFields(logrus.Fields{
|
||||
"from": env.Sender,
|
||||
"to": env.Recipients,
|
||||
"peer": peerIP,
|
||||
"uuid": generateUUID(),
|
||||
})
|
||||
// Check for aliases
|
||||
aliasesMutex.RLock()
|
||||
for i, recipient := range env.Recipients {
|
||||
if alias, exists := aliasesList[recipient]; exists {
|
||||
env.Recipients[i] = alias
|
||||
log.Info().
|
||||
Str("original_recipient", recipient).
|
||||
Str("aliased_recipient", alias).
|
||||
Msg("Recipient address aliased")
|
||||
}
|
||||
}
|
||||
aliasesMutex.RUnlock()
|
||||
|
||||
logger := log.With().
|
||||
Str("from", env.Sender).
|
||||
Strs("to", env.Recipients).
|
||||
Str("peer", peerIP).
|
||||
Str("uuid", generateUUID()).
|
||||
Logger()
|
||||
|
||||
var envRemotes []*Remote
|
||||
|
||||
@@ -177,14 +193,14 @@ func mailHandler(peer smtpd.Peer, env smtpd.Envelope) error {
|
||||
}
|
||||
|
||||
if len(envRemotes) == 0 && *command == "" {
|
||||
logger.Warning("no remote_host or command set; discarding mail")
|
||||
logger.Warn().Msg("no remote_host or command set; discarding mail")
|
||||
return smtpd.Error{Code: 554, Message: "There are no appropriate remote_host or command"}
|
||||
}
|
||||
|
||||
env.AddReceivedLine(peer)
|
||||
|
||||
if *command != "" {
|
||||
cmdLogger := logger.WithField("command", *command)
|
||||
cmdLogger := logger.With().Str("command", *command).Logger()
|
||||
|
||||
var stdout bytes.Buffer
|
||||
var stderr bytes.Buffer
|
||||
@@ -205,16 +221,16 @@ func mailHandler(peer smtpd.Peer, env smtpd.Envelope) error {
|
||||
|
||||
err := cmd.Run()
|
||||
if err != nil {
|
||||
cmdLogger.WithError(err).Error(stderr.String())
|
||||
cmdLogger.Error().Err(err).Msg(stderr.String())
|
||||
return smtpd.Error{Code: 554, Message: "External command failed"}
|
||||
}
|
||||
|
||||
cmdLogger.Info("pipe command successful: " + stdout.String())
|
||||
cmdLogger.Info().Msg("pipe command successful: " + stdout.String())
|
||||
}
|
||||
|
||||
for _, remote := range envRemotes {
|
||||
logger = logger.WithField("host", remote.Addr)
|
||||
logger.Info("delivering mail from peer using smarthost")
|
||||
logger = logger.With().Str("host", remote.Addr).Logger()
|
||||
logger.Info().Msg("delivering mail from peer using smarthost")
|
||||
|
||||
err := SendMail(
|
||||
remote,
|
||||
@@ -229,21 +245,22 @@ func mailHandler(peer smtpd.Peer, env smtpd.Envelope) error {
|
||||
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")
|
||||
logger.Error().
|
||||
Int("err_code", err.Code).
|
||||
Str("err_msg", err.Msg).
|
||||
Msg("delivery failed")
|
||||
default:
|
||||
smtpError = smtpd.Error{Code: 554, Message: "Forwarding failed"}
|
||||
smtpError = smtpd.Error{Code: 421, Message: "Forwarding failed"}
|
||||
|
||||
logger.WithError(err).
|
||||
Error("delivery failed")
|
||||
logger.Error().
|
||||
Err(err).
|
||||
Msg("delivery failed")
|
||||
}
|
||||
|
||||
return smtpError
|
||||
}
|
||||
|
||||
logger.Debug("delivery successful")
|
||||
logger.Debug().Msg("delivery successful")
|
||||
}
|
||||
|
||||
return nil
|
||||
@@ -253,8 +270,9 @@ func generateUUID() string {
|
||||
uniqueID, err := uuid.NewRandom()
|
||||
|
||||
if err != nil {
|
||||
log.WithError(err).
|
||||
Error("could not generate UUIDv4")
|
||||
log.Error().
|
||||
Err(err).
|
||||
Msg("could not generate UUIDv4")
|
||||
|
||||
return ""
|
||||
}
|
||||
@@ -263,64 +281,116 @@ func generateUUID() 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")
|
||||
log.Fatal().
|
||||
Str("cert_file", *localCert).
|
||||
Str("key_file", *localKey).
|
||||
Msg("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")
|
||||
log.Fatal().
|
||||
Err(err).
|
||||
Msg("cannot load X509 keypair")
|
||||
}
|
||||
|
||||
return &tls.Config{
|
||||
PreferServerCipherSuites: true,
|
||||
MinVersion: tls.VersionTLS12,
|
||||
CipherSuites: tlsCipherSuites,
|
||||
Certificates: []tls.Certificate{cert},
|
||||
}
|
||||
}
|
||||
|
||||
func watchAliasFile() {
|
||||
if *aliasFile == "" {
|
||||
return
|
||||
}
|
||||
|
||||
watcher, err := fsnotify.NewWatcher()
|
||||
if err != nil {
|
||||
log.Error().
|
||||
Err(err).
|
||||
Msg("failed to create file watcher for alias file")
|
||||
return
|
||||
}
|
||||
|
||||
go func() {
|
||||
defer watcher.Close()
|
||||
|
||||
for {
|
||||
select {
|
||||
case event, ok := <-watcher.Events:
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
if event.Has(fsnotify.Write) || event.Has(fsnotify.Create) {
|
||||
log.Info().
|
||||
Str("file", event.Name).
|
||||
Msg("alias file changed, reloading")
|
||||
|
||||
err := LoadAliases(*aliasFile)
|
||||
if err != nil {
|
||||
log.Error().
|
||||
Str("file", *aliasFile).
|
||||
Err(err).
|
||||
Msg("failed to reload alias file")
|
||||
} else {
|
||||
log.Info().
|
||||
Int("count", len(aliasesList)).
|
||||
Msg("alias file reloaded successfully")
|
||||
}
|
||||
}
|
||||
|
||||
case err, ok := <-watcher.Errors:
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
log.Error().
|
||||
Err(err).
|
||||
Msg("file watcher error")
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
err = watcher.Add(*aliasFile)
|
||||
if err != nil {
|
||||
log.Error().
|
||||
Str("file", *aliasFile).
|
||||
Err(err).
|
||||
Msg("failed to watch alias file")
|
||||
} else {
|
||||
log.Info().
|
||||
Str("file", *aliasFile).
|
||||
Msg("watching alias file for changes")
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
ConfigLoad()
|
||||
|
||||
log.WithField("version", appVersion).
|
||||
Debug("starting smtprelay")
|
||||
log.Debug().
|
||||
Str("version", appVersion).
|
||||
Msg("starting smtprelay")
|
||||
|
||||
// Load allowed users file
|
||||
if localAuthRequired() {
|
||||
err := AuthLoadFile(*allowedUsers)
|
||||
if err != nil {
|
||||
log.WithField("file", *allowedUsers).
|
||||
WithError(err).
|
||||
Fatal("cannot load allowed users file")
|
||||
log.Fatal().
|
||||
Str("file", *allowedUsers).
|
||||
Err(err).
|
||||
Msg("cannot load allowed users file")
|
||||
}
|
||||
}
|
||||
|
||||
// Start watching alias file for changes
|
||||
watchAliasFile()
|
||||
|
||||
var servers []*smtpd.Server
|
||||
|
||||
// Create a server for each desired listen address
|
||||
for _, listen := range listenAddrs {
|
||||
logger := log.WithField("address", listen.address)
|
||||
logger := log.With().Str("address", listen.address).Logger()
|
||||
|
||||
server := &smtpd.Server{
|
||||
Hostname: *hostName,
|
||||
@@ -346,29 +416,32 @@ func main() {
|
||||
|
||||
switch listen.protocol {
|
||||
case "":
|
||||
logger.Info("listening on address")
|
||||
logger.Info().Msg("listening on address")
|
||||
lsnr, err = net.Listen("tcp", listen.address)
|
||||
|
||||
case "starttls":
|
||||
server.TLSConfig = getTLSConfig()
|
||||
server.ForceTLS = *localForceTLS
|
||||
|
||||
logger.Info("listening on address (STARTTLS)")
|
||||
logger.Info().Msg("listening on address (STARTTLS)")
|
||||
lsnr, err = net.Listen("tcp", listen.address)
|
||||
|
||||
case "tls":
|
||||
server.TLSConfig = getTLSConfig()
|
||||
|
||||
logger.Info("listening on address (TLS)")
|
||||
logger.Info().Msg("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")
|
||||
logger.Fatal().
|
||||
Str("protocol", listen.protocol).
|
||||
Msg("unknown protocol in listen address")
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
logger.WithError(err).Fatal("error starting listener")
|
||||
logger.Fatal().
|
||||
Err(err).
|
||||
Msg("error starting listener")
|
||||
}
|
||||
servers = append(servers, server)
|
||||
|
||||
@@ -381,27 +454,31 @@ func main() {
|
||||
|
||||
// First close the listeners
|
||||
for _, server := range servers {
|
||||
logger := log.WithField("address", server.Address())
|
||||
logger.Debug("Shutting down server")
|
||||
logger := log.With().Str("address", server.Address().String()).Logger()
|
||||
logger.Debug().Msg("Shutting down server")
|
||||
err := server.Shutdown(false)
|
||||
if err != nil {
|
||||
logger.WithError(err).
|
||||
Warning("Shutdown failed")
|
||||
logger.Warn().
|
||||
Err(err).
|
||||
Msg("Shutdown failed")
|
||||
}
|
||||
}
|
||||
|
||||
// Then wait for the clients to exit
|
||||
for _, server := range servers {
|
||||
logger := log.WithField("address", server.Address())
|
||||
logger.Debug("Waiting for server")
|
||||
logger := log.With().Str("address", server.Address().String()).Logger()
|
||||
logger.Debug().Msg("Waiting for server")
|
||||
err := server.Wait()
|
||||
if err != nil {
|
||||
logger.WithError(err).
|
||||
Warning("Wait failed")
|
||||
logger.Warn().
|
||||
Err(err).
|
||||
Msg("Wait failed")
|
||||
}
|
||||
}
|
||||
|
||||
log.Debug("done")
|
||||
log.Debug().Msg("done")
|
||||
|
||||
closeLogger()
|
||||
}
|
||||
|
||||
func handleSignals() {
|
||||
@@ -410,6 +487,7 @@ func handleSignals() {
|
||||
signal.Notify(sigs, syscall.SIGINT, syscall.SIGQUIT, syscall.SIGTERM)
|
||||
sig := <-sigs
|
||||
|
||||
log.WithField("signal", sig).
|
||||
Info("shutting down in response to received signal")
|
||||
log.Info().
|
||||
Str("signal", sig.String()).
|
||||
Msg("shutting down in response to received signal")
|
||||
}
|
||||
|
||||
24
smtp.go
24
smtp.go
@@ -49,7 +49,7 @@ type Client struct {
|
||||
helloError error // the error from the hello
|
||||
}
|
||||
|
||||
// Dial returns a new Client connected to an SMTP server at addr.
|
||||
// Dial returns a new [Client] connected to an SMTP server at addr.
|
||||
// The addr must include a port, as in "mail.example.com:smtp".
|
||||
func Dial(addr string) (*Client, error) {
|
||||
conn, err := net.Dial("tcp", addr)
|
||||
@@ -60,7 +60,7 @@ func Dial(addr string) (*Client, error) {
|
||||
return NewClient(conn, host)
|
||||
}
|
||||
|
||||
// NewClient returns a new Client using an existing connection and host as a
|
||||
// NewClient returns a new [Client] using an existing connection and host as a
|
||||
// server name to be used when authenticating.
|
||||
func NewClient(conn net.Conn, host string) (*Client, error) {
|
||||
text := textproto.NewConn(conn)
|
||||
@@ -167,7 +167,7 @@ func (c *Client) StartTLS(config *tls.Config) error {
|
||||
}
|
||||
|
||||
// TLSConnectionState returns the client's TLS connection state.
|
||||
// The return values are their zero values if StartTLS did
|
||||
// The return values are their zero values if [Client.StartTLS] did
|
||||
// not succeed.
|
||||
func (c *Client) TLSConnectionState() (state tls.ConnectionState, ok bool) {
|
||||
tc, ok := c.conn.(*tls.Conn)
|
||||
@@ -207,7 +207,7 @@ func (c *Client) Auth(a smtp.Auth) error {
|
||||
}
|
||||
resp64 := make([]byte, encoding.EncodedLen(len(resp)))
|
||||
encoding.Encode(resp64, resp)
|
||||
code, msg64, err := c.cmd(0, strings.TrimSpace(fmt.Sprintf("AUTH %s %s", mech, resp64)))
|
||||
code, msg64, err := c.cmd(0, "%s", strings.TrimSpace(fmt.Sprintf("AUTH %s %s", mech, resp64)))
|
||||
for err == nil {
|
||||
var msg []byte
|
||||
switch code {
|
||||
@@ -233,7 +233,7 @@ func (c *Client) Auth(a smtp.Auth) error {
|
||||
}
|
||||
resp64 = make([]byte, encoding.EncodedLen(len(resp)))
|
||||
encoding.Encode(resp64, resp)
|
||||
code, msg64, err = c.cmd(0, string(resp64))
|
||||
code, msg64, err = c.cmd(0, "%s", resp64)
|
||||
}
|
||||
return err
|
||||
}
|
||||
@@ -242,7 +242,7 @@ func (c *Client) Auth(a smtp.Auth) error {
|
||||
// If the server supports the 8BITMIME extension, Mail adds the BODY=8BITMIME
|
||||
// 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 [Client.Rcpt] calls.
|
||||
func (c *Client) Mail(from string) error {
|
||||
if err := validateLine(from); err != nil {
|
||||
return err
|
||||
@@ -264,8 +264,8 @@ func (c *Client) Mail(from string) error {
|
||||
}
|
||||
|
||||
// Rcpt issues a RCPT command to the server using the provided email address.
|
||||
// A call to Rcpt must be preceded by a call to Mail and may be followed by
|
||||
// a Data call or another Rcpt call.
|
||||
// A call to Rcpt must be preceded by a call to [Client.Mail] and may be followed by
|
||||
// a [Client.Data] call or another Rcpt call.
|
||||
func (c *Client) Rcpt(to string) error {
|
||||
if err := validateLine(to); err != nil {
|
||||
return err
|
||||
@@ -288,7 +288,7 @@ func (d *dataCloser) Close() error {
|
||||
// Data issues a DATA command to the server and returns a writer that
|
||||
// can be used to write the mail headers and body. The caller should
|
||||
// close the writer before calling any more methods on c. A call to
|
||||
// Data must be preceded by one or more calls to Rcpt.
|
||||
// Data must be preceded by one or more calls to [Client.Rcpt].
|
||||
func (c *Client) Data() (io.WriteCloser, error) {
|
||||
_, _, err := c.cmd(354, "DATA")
|
||||
if err != nil {
|
||||
@@ -445,9 +445,7 @@ func (c *Client) Noop() error {
|
||||
|
||||
// Quit sends the QUIT command and closes the connection to the server.
|
||||
func (c *Client) Quit() error {
|
||||
if err := c.hello(); err != nil {
|
||||
return err
|
||||
}
|
||||
c.hello() // ignore error; we're quitting anyhow
|
||||
_, _, err := c.cmd(221, "QUIT")
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -455,7 +453,7 @@ func (c *Client) Quit() error {
|
||||
return c.Text.Close()
|
||||
}
|
||||
|
||||
// validateLine checks to see if a line has CR or LF as per RFC 5321
|
||||
// validateLine checks to see if a line has CR or LF as per RFC 5321.
|
||||
func validateLine(line string) error {
|
||||
if strings.ContainsAny(line, "\n\r") {
|
||||
return errors.New("smtp: A line must not contain CR or LF")
|
||||
|
||||
@@ -13,6 +13,11 @@
|
||||
; Log level: panic, fatal, error, warn, info, debug, trace
|
||||
;log_level = info
|
||||
|
||||
; path to alias file
|
||||
; alias file format (separated by space):
|
||||
; fake@email.tld real@email.tld
|
||||
;aliases_file = aliases.txt
|
||||
|
||||
; Hostname for this SMTP server
|
||||
;hostname = localhost.localdomain
|
||||
|
||||
@@ -83,7 +88,7 @@
|
||||
; authentication before they can send mail.
|
||||
; File format: username bcrypt-hash [email[,email[,...]]]
|
||||
; username: The SMTP auth username
|
||||
; bcrypt-hash: The bcrypt hash of the pasword (generate with "./hasher password")
|
||||
; bcrypt-hash: The bcrypt hash of the pasword
|
||||
; 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
|
||||
|
||||
Reference in New Issue
Block a user