pax_global_header00006660000000000000000000000064152615247040014520gustar00rootroot0000000000000052 comment=b21998ec41d4d08777f089916bf237c3ac55206c roehling-postsrsd-24c678b/000077500000000000000000000000001526152470400155475ustar00rootroot00000000000000roehling-postsrsd-24c678b/.clang-format000066400000000000000000000014211526152470400201200ustar00rootroot00000000000000BasedOnStyle: LLVM AccessModifierOffset: -4 AlignConsecutiveMacros: true AlignEscapedNewlines: Left AllowShortBlocksOnASingleLine: Empty AllowShortEnumsOnASingleLine: false AllowShortFunctionsOnASingleLine: Empty AllowShortLambdasOnASingleLine: Inline AlwaysBreakBeforeMultilineStrings: true AlwaysBreakTemplateDeclarations: Yes BreakBeforeBinaryOperators: NonAssignment BreakBeforeBraces: Allman IncludeBlocks: Regroup IncludeCategories: - Regex: '<[[:alnum:]_]+>' SortPriority: 3 - Regex: '<.*>' SortPriority: 2 - Regex: '".*"' SortPriority: 1 IndentCaseLabels: true IndentExternBlock: NoIndent IndentGotoLabels: false IndentPPDirectives: AfterHash IndentWidth: 4 JavaScriptQuotes: Double PointerAlignment: Left SpacesBeforeTrailingComments: 2 SpaceAfterTemplateKeyword: false roehling-postsrsd-24c678b/.cmake-format.json000066400000000000000000000047121526152470400210720ustar00rootroot00000000000000{ "parse": { "additional_commands": { "add_autotools_dependency": { "flags": [ ], "kwargs": { "LIBRARY_NAME": "?", "EXPORTED_TARGET": "?" } } } }, "format": { "disable": false, "line_width": 80, "tab_size": 4, "use_tabchars": false, "fractional_tab_policy": "use-space", "max_subgroups_hwrap": 2, "max_pargs_hwrap": 6, "max_rows_cmdline": 2, "separate_ctrl_name_with_space": false, "separate_fn_name_with_space": false, "dangle_parens": true, "dangle_align": "prefix", "min_prefix_chars": 4, "max_prefix_chars": 10, "max_lines_hwrap": 2, "line_ending": "unix", "command_case": "canonical", "keyword_case": "unchanged", "always_wrap": [], "enable_sort": true, "autosort": false, "require_valid_layout": false, "layout_passes": {} }, "markup": { "_help_bullet_char": [ "What character to use for bulleted lists" ], "bullet_char": "*", "enum_char": ".", "first_comment_is_literal": true, "literal_comment_pattern": null, "fence_pattern": "^\\s*([`~]{3}[`~]*)(.*)$", "ruler_pattern": "^\\s*[^\\w\\s]{3}.*[^\\w\\s]{3}$", "explicit_trailing_pattern": "#<", "hashruler_min_length": 10, "canonicalize_hashrulers": true, "enable_markup": true }, "lint": { "disabled_codes": [], "function_pattern": "[0-9a-z_]+", "macro_pattern": "[0-9A-Z_]+", "global_var_pattern": "[A-Z][0-9A-Z_]+", "internal_var_pattern": "_[A-Z][0-9A-Z_]+", "local_var_pattern": "[a-z][a-z0-9_]+", "private_var_pattern": "_[0-9a-z_]+", "public_var_pattern": "[A-Z][0-9A-Z_]+", "argument_var_pattern": "[a-z][a-z0-9_]+", "keyword_pattern": "[A-Z][0-9A-Z_]+", "max_conditionals_custom_parser": 2, "min_statement_spacing": 1, "max_statement_spacing": 2, "max_returns": 6, "max_branches": 12, "max_arguments": 5, "max_localvars": 15, "max_statements": 50 }, "encode": { "emit_byteorder_mark": false, "input_encoding": "utf-8", "output_encoding": "utf-8" }, "misc": { "per_command": {} } } roehling-postsrsd-24c678b/.github/000077500000000000000000000000001526152470400171075ustar00rootroot00000000000000roehling-postsrsd-24c678b/.github/workflows/000077500000000000000000000000001526152470400211445ustar00rootroot00000000000000roehling-postsrsd-24c678b/.github/workflows/bsd.yml000066400000000000000000000046221526152470400224430ustar00rootroot00000000000000# Copyright 2023-2026 Timo Röhling # SPDX-License-Identifier: FSFAP # # Copying and distribution of this file, with or without modification, are # permitted in any medium without royalty provided the copyright notice and # this notice are preserved. This file is offered as-is, without any warranty. # name: CI (BSD) on: push: branches: - main pull_request: branches: - main permissions: contents: read jobs: freebsd: runs-on: ubuntu-latest name: FreeBSD steps: - uses: actions/checkout@v7 - uses: vmactions/freebsd-vm@v1 with: usesh: true copyback: false prepare: | pkg install -y cmake git gmake libconfuse check sqlite3 hiredis run: | mkdir _build cd _build cmake .. -DDEVELOPER_BUILD=ON -DWITH_SQLITE=ON -DWITH_REDIS=ON cmake --build . --verbose ctest --verbose openbsd: runs-on: ubuntu-latest name: OpenBSD steps: - uses: actions/checkout@v7 - uses: vmactions/openbsd-vm@v1 with: usesh: true copyback: false prepare: | pkg_add cmake git gmake libconfuse check sqlite3 libhiredis run: | mkdir _build cd _build cmake .. -DDEVELOPER_BUILD=ON -DWITH_SQLITE=ON -DWITH_REDIS=ON cmake --build . --verbose ctest --verbose netbsd: runs-on: ubuntu-latest name: NetBSD steps: - uses: actions/checkout@v7 - uses: vmactions/netbsd-vm@v1 with: usesh: true copyback: false prepare: | pkg_add cmake git gmake confuse check sqlite3 hiredis run: | mkdir _build cd _build cmake .. -DDEVELOPER_BUILD=ON -DWITH_SQLITE=ON -DWITH_REDIS=ON cmake --build . --verbose ctest --verbose macos: runs-on: macos-latest name: MacOS steps: - uses: actions/checkout@v7 - name: Install dependencies run: | brew install gcc python cmake git confuse check sqlite hiredis - name: Build PostSRSd run: | mkdir _build cd _build cmake .. -DDEVELOPER_BUILD=ON -DWITH_SQLITE=ON -DWITH_REDIS=ON cmake --build . --verbose - name: Run tests run: | cd _build ctest --verbose roehling-postsrsd-24c678b/.github/workflows/linux.yml000066400000000000000000000116221526152470400230300ustar00rootroot00000000000000# Copyright 2022-2026 Timo Röhling # SPDX-License-Identifier: FSFAP # # Copying and distribution of this file, with or without modification, are # permitted in any medium without royalty provided the copyright notice and # this notice are preserved. This file is offered as-is, without any warranty. # name: CI (Linux) on: push: branches: - main pull_request: branches: - main permissions: contents: read jobs: ubuntu: name: Ubuntu runs-on: ubuntu-latest strategy: matrix: sqlite: [SQLITE=OFF, SQLITE=ON] redis: [REDIS=OFF, REDIS=ON] deps: [vendored-deps, system-deps] steps: - uses: actions/checkout@v7 - name: Install dependencies run: | sudo apt-get update -qq sudo apt-get install -y cmake postfix redis gperf ${{ case(matrix.deps == 'system-deps', 'check libseccomp-dev libconfuse-dev libhiredis-dev libsqlite3-dev', '') }} - name: Build PostSRSd run: | mkdir _build cd _build cmake .. -DDEVELOPER_BUILD=ON -DTESTS_WITH_ASAN=ON -DTESTS_WITH_REDIS=ON -DWITH_SECCOMP=ON -DWITH_${{ matrix.sqlite }} -DWITH_${{ matrix.redis }} ${{ case(matrix.deps == 'system-deps', '-DFETCHCONTENT_FULLY_DISCONNECTED=ON -DFETCHCONTENT_TRY_FIND_PACKAGE_MODE=ALWAYS', '') }} cmake --build . --verbose - name: Run tests run: | cd _build ctest --verbose - name: Install and start PostSRSd daemon run: | cd _build sudo make install sed -e 's/^#srs-domain.*/srs-domain = "example.com"/' -e 's!^#milter.*!milter = unix:/var/spool/postfix/srs_milter!' /usr/local/share/doc/postsrsd/postsrsd.conf | sudo tee /usr/local/etc/postsrsd.conf sudo systemctl enable postsrsd sudo systemctl start postsrsd sudo journalctl --no-pager -u postsrsd sudo systemctl --no-pager status postsrsd sudo systemd-analyze --no-pager security postsrsd - name: Test Postfix integration run: | echo -e "@example.com $(whoami)\n@otherdomain.com $(whoami)" | sudo tee /etc/postfix/virtual sudo postmap hash:/etc/postfix/virtual sudo postconf -e non_smtpd_milters=unix:srs_milter smtpd_milters=unix:srs_milter "virtual_alias_domains=example.com otherdomain.com" virtual_alias_maps=hash:/etc/postfix/virtual sudo postfix reload postmap -q test@otherdomain.com socketmap:unix:/var/spool/postfix/srs:forward | tee /tmp/srs-alias.txt postmap -q "$(cat /tmp/srs-alias.txt)" socketmap:unix:/var/spool/postfix/srs:reverse echo -e 'Subject: Forward SRS\r\n\r\nThis is the first test\r\n\r\n\r\n' | sendmail -f sender@otherdomain.com -- recipient@otherdomain.com echo -e 'Subject: Reverse SRS\r\n\r\nThis is the second test\r\n\r\n\r\n' | sendmail -f sender@otherdomain.com -- $(cat /tmp/srs-alias.txt) sleep 2 sudo tail /var/log/mail.log || true sudo cat $(postconf -h mail_spool_directory)/* || true - name: Test notify-reload run: | sudo systemctl reload postsrsd sleep 1 sudo systemctl --no-pager status postsrsd fedora: name: Fedora runs-on: ubuntu-latest container: fedora:latest steps: - uses: actions/checkout@v7 - name: Install dependencies run: | dnf install -y cmake gcc make python3 check-devel libconfuse-devel libseccomp-devel hiredis-devel sqlite-devel - name: Build PostSRSd run: | mkdir _build cd _build cmake .. -DDEVELOPER_BUILD=ON -DWITH_SECCOMP=ON -DWITH_SQLITE=ON -DWITH_REDIS=ON cmake --build . --verbose - name: Run tests run: | cd _build ctest --verbose alpine: name: Alpine runs-on: ubuntu-latest container: alpine:latest steps: - uses: actions/checkout@v7 - name: Install dependencies run: | apk add cmake gcc make python3 musl-dev check-dev libseccomp-dev confuse-dev hiredis-dev sqlite-dev - name: Build PostSRSd run: | mkdir _build cd _build cmake .. -DDEVELOPER_BUILD=ON -DWITH_SECCOMP=ON -DWITH_SQLITE=ON -DWITH_REDIS=ON cmake --build . --verbose - name: Run tests run: | cd _build ctest --verbose archlinux: name: Arch Linux runs-on: ubuntu-latest container: archlinux:base steps: - uses: actions/checkout@v7 - name: Install dependencies run: | pacman -Syu --noconfirm cmake gcc make python3 confuse check libseccomp hiredis sqlite - name: Build PostSRSd run: | mkdir _build cd _build cmake .. -DDEVELOPER_BUILD=ON -DWITH_SECCOMP=ON -DWITH_SQLITE=ON -DWITH_REDIS=ON cmake --build . --verbose - name: Run tests run: | cd _build ctest --verbose roehling-postsrsd-24c678b/.github/workflows/release.yml000066400000000000000000000044301526152470400233100ustar00rootroot00000000000000# Copyright 2023-2026 Timo Röhling # SPDX-License-Identifier: FSFAP # # Copying and distribution of this file, with or without modification, are # permitted in any medium without royalty provided the copyright notice and # this notice are preserved. This file is offered as-is, without any warranty. # name: Build PostSRSd release on: push: branches: - main tags: - "2.*" permissions: contents: write jobs: release: runs-on: ubuntu-latest steps: - uses: actions/checkout@v7 - name: Install dependencies run: | sudo apt-get update -qq sudo apt-get install -y cmake musl-dev musl-tools dpkg-dev gperf - name: Determine build version uses: proudust/gh-describe@v2 id: ghd with: match: "2.*" - name: Build PostSRSd run: | mkdir _build cd _build cmake .. -DCMAKE_BUILD_TYPE=MinSizeRel -DCMAKE_C_COMPILER=musl-gcc -DCMAKE_EXE_LINKER_FLAGS=-static -DCMAKE_C_FLAGS="-idirafter /usr/include -idirafter /usr/include/$(dpkg-architecture -qDEB_HOST_MULTIARCH)" -DBUILD_TESTING=OFF -DWITH_SQLITE=ON -DWITH_REDIS=ON -DWITH_SECCOMP=ON -DGENERATE_SRS_SECRET=OFF -DFETCHCONTENT_TRY_FIND_PACKAGE_MODE=NEVER -DEXTRA_VERSION=${{ case(! startsWith(github.ref, 'refs/tags/'), format('+{0}.git.{1}', steps.ghd.outputs.distance, steps.ghd.outputs.short-sha), '') }} make VERBOSE=ON - name: Test PostSRSd functionality run: | python3 tests/blackbox/socketmap.py _build/postsrsd 1 0 python3 tests/blackbox/milter.py _build/postsrsd 1 0 python3 tests/blackbox/reload.py _build/postsrsd 1 - name: Install PostSRSd run: | cd _build make install DESTDIR=$PWD/_install - name: Create tarball run: tar -C_build/_install -cvzf postsrsd-x86_64-musl.tar.gz ./ - name: Upload tarball uses: actions/upload-artifact@v7 with: name: tarball path: postsrsd-x86_64-musl.tar.gz archive: false overwrite: true if-no-files-found: error - name: Create release if: startsWith(github.ref, 'refs/tags/') uses: softprops/action-gh-release@v3 with: files: postsrsd-x86_64-musl.tar.gz roehling-postsrsd-24c678b/.github/workflows/solaris.yml000066400000000000000000000031321526152470400233420ustar00rootroot00000000000000# Copyright 2023-2026 Timo Röhling # SPDX-License-Identifier: FSFAP # # Copying and distribution of this file, with or without modification, are # permitted in any medium without royalty provided the copyright notice and # this notice are preserved. This file is offered as-is, without any warranty. # name: CI (Solaris) on: push: branches: - main pull_request: branches: - main permissions: contents: read jobs: solaris: runs-on: ubuntu-latest name: Solaris steps: - uses: actions/checkout@v7 - uses: vmactions/solaris-vm@v1 with: usesh: true release: "11.4-gcc" copyback: false prepare: | pkgutil -y -i curl flex git gmake curl -Lfso cmake.sh https://github.com/Kitware/CMake/releases/download/v4.4.0/cmake-4.4.0-sunos-x86_64.sh sh cmake.sh --skip-license --prefix=/opt/csw run: | mkdir _build cd _build cmake .. -DDEVELOPER_BUILD=ON -DWITH_SQLITE=ON cmake --build . --verbose ctest --verbose omnios: runs-on: ubuntu-latest name: OmniOS steps: - uses: actions/checkout@v7 - uses: vmactions/omnios-vm@v1 with: usesh: true release: "r151058-build" copyback: false prepare: | pkg install cmake git gnu-make run: | mkdir _build cd _build cmake .. -DDEVELOPER_BUILD=ON -DWITH_SQLITE=ON -DWITH_REDIS=ON cmake --build . --verbose ctest --verbose roehling-postsrsd-24c678b/.pre-commit-config.yaml000066400000000000000000000013751526152470400220360ustar00rootroot00000000000000# See https://pre-commit.com for more information # See https://pre-commit.com/hooks.html for more hooks repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v6.0.0 hooks: - id: trailing-whitespace exclude: ^fuzz/(?:seeds|dict) - id: end-of-file-fixer exclude: ^fuzz/(?:seeds|dict) - id: check-yaml exclude: ^fuzz/(?:seeds|dict) - id: check-added-large-files - repo: https://github.com/pre-commit/mirrors-clang-format rev: v23.1.2 hooks: - id: clang-format - repo: https://github.com/psf/black-pre-commit-mirror rev: 26.10.0 hooks: - id: black - repo: https://github.com/cheshirekow/cmake-format-precommit rev: v0.6.13 hooks: - id: cmake-format roehling-postsrsd-24c678b/CHANGELOG.rst000066400000000000000000000247651526152470400176060ustar00rootroot00000000000000.. PostSRSd - Sender Rewriting Scheme daemon for Postfix Copyright 2012-2026 Timo Röhling SPDX-License-Identifier: GPL-3.0-only ######### Changelog ######### 2.4.1 ===== Fixed ----- * Make systemd unit configuration more robust Changed ------- * Downgrade log message to debug for MTA milter abort 2.4.0 ===== Fixed ----- * A few minor code defects have been fixed to contribute to defense in depth. Added ----- * New configuration option ``connection-limit`` to prevent DoS attacks by malicious clients repeatedly connecting to PostSRSd. * New configuration option ``milter-recipient-limit`` to keep the number of recipients per SMTP session sane. Changed ------- * The milter protocol implementation is no longer considered experimental. 2.3.0 ===== Changed ------- * Some code has been refactored to improve robustness and compatibility with different operating systems. Tested with: Arch Linux, Alpine Linux, Debian, Fedora, FreeBSD, MacOS, NetBSD, OmniOS, OpenBSD, Solaris, and Ubuntu. Added ----- * Improved diagnostics for errors in the worker process, especially if the worker process is killed due to a seccomp violation. 2.2.7 ===== Fixed ----- * Do not fail if seccomp sandboxing cannot be enabled on unsupported systems. 2.2.6 ===== Fixed ----- * Properly drop privileges in worker processes again (broken since 2.2.0). Added ----- * The systemd service unit file has been substantially hardened. Changed ------- * Drop FILE* API in favor of direct read()/write() * SRS hashes are encoded with the base64url scheme now (`#189 `_). 2.2.5 ===== Changed ------- * The milter is less strict with its input requirements for better compatibility with MTAs. 2.2.4 ===== Fixed ----- * Missing error handling for some edge cases (e.g., failing fork()). (`#199 `_) * Reworked a few potentially unsafe constructs in the code. Changed ------- * Delete socket file on shutdown. 2.2.3 ===== Changed ------- * Stop rejecting invalid SRS addresses for socketmap queries. This was introduced in version 2.1.0 but turns out to be short-sighted. The milter still rejects invalid SRS addresses, but only for the configured SRS domain, i.e., addresses which are supposed to be generated by us and thus must not be invalid or unverifiable. 2.2.2 ===== Fixed ----- * Work around unsafe domains file updates which cause a race condition in the inotify-based file watch. * ``reverse`` no longer rejects (socketmap ``PERM`` / milter reject) SRS addresses whose domain is not local. Such addresses are minted by a different SRS signer and only transit this host (relay, backup MX, multi-hop forwarding); they are passed through unchanged again, as in 2.1.0 and earlier. Unverifiable SRS addresses in a local domain (forged backscatter) are still rejected. Changed ------- * Additional sandboxing features in the systemd unit file. 2.2.1 ===== Changed ------- * Add per-process tracking of child processes. * The ``srs-domain`` configuration option is implicitly added to the list of local domains now. * Improved test coverage. * Show Postfix queue ID in log messages if used as milter. Added ----- * Additional CMake options to customize the build. Fixed ----- * The fallback stpcpy() implementation had a typo in its name. 2.2.0 ===== Changed ------- * Reimplemented milter without external LibMilter dependency. * PostSRSd milter supports not rewriting locally delivered mails now. Fixed ----- * SECCOMP with MUSL. 2.1.0 ===== Added ----- * Reload configuration on ``SIGHUP``. * inotify support to watch domains-file for changes and reconfigure automatically. * Better integration with systemd via sd_notify. * SECCOMP support for better sandboxing while handling untrusted input. 2.0.12 ====== Fixed ----- * PostSRSd will give a proper diagnostic instead of crashing if no SRS domain is configured. * The sysusers.d snippet will never be installed for the "nobody" user. Changed ------- * The build will always look for installed system dependencies first. * Updated vendored dependencies for Hiredis and SQLite to latest release. * If PostSRSd is installed to `/usr/local`, the systemd files are also installed there instead of `/etc`. Added ----- * New CMake switch `INSTALL_SYSTEMD_SYSUSERS` for sysusers.d snippet installation. 2.0.11 ====== Fixed ----- * Run `autoreconf` to prevent confuse build failures with newer autoconf/automake releases * Fix build failures with libcheck if libsubunit ist installed (`#161 `_) * Do not fail silently if `WITH_MILTER=ON` is set but libmilter is not available 2.0.10 ====== Changed ------- * Allow comments in domains-file (`#181 `_) Added ----- * Support for building against system libmilter library 2.0.9 ===== Fixed ----- * Fixed build with system libraries (`#176 `_) Changed ------- * Create sockets non-blocking and with close-on-exec enabled 2.0.8 ===== Fixed ----- * Fixed socket creation for Milter * Fixed Milter issue with IPv6 clients (`#156 `_) Added ----- * Support for system user management with ``sysusers.d`` * Better customization of the PostSRSd build with ``POSTSRSD_CONFIGDIR`` and ``INSTALL_SYSTEMD_SERVICE`` Changed ------- * Improved documentation of the PostSRSd example configuration Contributions ------------- * Richard Hansen (`#155 `_, `#157 `_) 2.0.7 ===== Fixed ----- * the parser callback for the ``original-envelope`` option used the wrong return type, which could prevent the ``database`` mode from activating * PostSRSd is confirmed to build and run on FreeBSD now 2.0.6 ===== Added ----- * New configuration option ``debug`` to increase log verbosity. Changed ------- * Reduced default log verbosity: PostSRSd no longer prints messages for mail addresses which need no rewrite (`#149 `_) 2.0.5 ===== Fixed ----- * Do not try to set Keep-Alive on Redis unix sockets (`#146 `_) 2.0.4 ===== Fixed ----- * Worked around EXCLUDE_FROM_ALL bug in CMake 3.20.x and older * Fixed a few compiler warnings in the test suite Added ----- * Added support for musl as libc alternative * Added support for CPack to generate installable packages * Added new CLI option -h to print a summary of CLI options Changed ------- * The test suite no longer requires ``faketime`` as dependency * Improved error logging 2.0.3 ===== Fixed ----- * Close socketmap connection in main process to prevent resource exhaustion (`#141 `_) * Explicitly set 0666 permissions on socketmap unix socket (`#141 `_) 2.0.2 ===== Fixed ----- * Improved detection logic for systemd system unit directory (`#132 `_) * Drop supplementary groups when relinquishing root privileges (`#133 `_) 2.0.1 ===== Fixed ----- * Fixed improper linking against the pthread library on systems where pthread is separate from libc (`#130 `_) 2.0.0 ===== Added ----- * Added proper configuration file format * Added support for unix sockets * Added new rewrite mode with database backend * Added experimental milter support Changed ------- * PostSRSd uses ``socketmap`` tables instead of ``tcp`` tables now Removed ------- * Removed AppArmor and SELinux profiles * Removed support for all init systems except systemd (Pull requests for needed init systems are welcome) 1.12 ==== Fixed ----- * Explicitly clear ``O_NONBLOCK`` to avoid inherited non-blocking sockets on some operating systems (`#117 `_) * Do not close all file descriptors up to ``_SC_MAX_OPEN``, as this limit tends to be absurdly high in Docker containers (`#122 `_) * Check for the existence of the ``faketime`` tool before using it in the unit tests. 1.11 ==== Security -------- * The subprocess that talks to Postfix could be caused to hang with a very long email address (`077be98d `_) 1.10 ==== Security -------- * Fixed CVE-2020-35573: PostSRSd could be tricked into consuming a lot of CPU time with an SRS address that has a very long time stamp tag (`4733fb11 `_) Fixed ----- * Fixed a bug where PostSRSd would occasionally create invalid SRS addresses if the used secret is extremely long 1.9 === Hotfix release Added ----- * Added test that systemd service file is working properly Fixed ----- * Fixed systemd service file 1.8 === Added ----- * Added "Always Rewrite" option (`#97 `_) * Added blackbox testing for PostSRSd daemon Changed ------- * Improved syslog messages Fixed ----- * Fixed AppArmor and SELinux profiles 1.7 === Changed ------- * Improved systemd auto detection * Drop group privileges as well as user privileges * Merged Debian adaptations (Thanks to Oxan van Leeuwen) Removed ------- * CMake 2.x support 1.6 === Added ----- * Somewhat usable unit tests Fixed ----- * Fixed Big Endian issue with SHA-1 implementation (`#90 `_) 1.5 === Added ----- * Add configuration options for listening network interface Changed ------- * Close all open file descriptors on startup Fixed ----- * Fixed SELinux policy * Fixed handling of excluded domains in systemd startup file 1.4 === Added ----- * Added dual stack support Fixed ----- * Make startup scripts more robust in case of configuration errors * Improved BSD compatibility 1.3 === Added ----- * Make SRS separator configurable * Added support for even more init systems 1.2 === Added ----- * Added support for more init systems Changed ------- * Listen to 127.0.0.1 by default Fixed ----- * Load correct timezone for logging 1.1 === Fixed ----- * Fixed various issues with the CMake script * Fixed command line parsing bug 1.0 === * First stable release roehling-postsrsd-24c678b/CMakeLists.txt000066400000000000000000000433251526152470400203160ustar00rootroot00000000000000# PostSRSd - Sender Rewriting Scheme daemon for Postfix # Copyright 2012-2026 Timo Röhling # SPDX-License-Identifier: GPL-3.0-only # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, version 3. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # cmake_minimum_required(VERSION 3.24...4.4) project( postsrsd VERSION 2.4.1 LANGUAGES C DESCRIPTION "Sender Rewriting Scheme daemon for Postfix" HOMEPAGE_URL "https://github.com/roehling/postsrsd" ) list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake") include(utils) include(CTest) include(FeatureSummary) include(FetchContent) include(GNUInstallDirs) include(CheckIncludeFile) include(CheckTypeSize) include(CheckSymbolExists) include(TestBigEndian) set(POSTSRSD_CONFIGDIR "${CMAKE_INSTALL_FULL_SYSCONFDIR}" CACHE PATH "The default directory where PostSRSd should look for configuration files" ) set(POSTSRSD_DATADIR "${CMAKE_INSTALL_FULL_LOCALSTATEDIR}/lib/${PROJECT_NAME}" CACHE PATH "The default directory where PostSRSd should put runtime data" ) set(POSTSRSD_CHROOTDIR "${POSTSRSD_DATADIR}" CACHE PATH "The default chroot directory where PostSRSd should jail itself" ) set(POSTSRSD_USER "nobody" CACHE STRING "The default unprivileged user as which PostSRSd will run" ) option(BUILD_FUZZING "Build fuzzing harnesses" OFF) option(WITH_SQLITE "Enable sqlite-based storage for opaque SRS tokens (requires sqlite3)" OFF ) add_feature_info(WITH_SQLITE WITH_SQLITE "use SQLite as database backend") option(WITH_REDIS "Enable Redis-based storage for opaque SRS tokens (requires hiredis)" OFF ) add_feature_info(WITH_REDIS WITH_REDIS "use Redis as database backend") option(WITH_SECCOMP "Enable additional sandboxing with seccomp" OFF) add_feature_info( WITH_SECCOMP WITH_SECCOMP "use seccomp for additional sandboxing" ) option(USE_DOMAINS_FILE "Pre-configure PostSRSd to use a domains file" OFF) add_feature_info( USE_DOMAINS_FILE USE_DOMAINS_FILE "pre-configure PostSRSd to use a domains file" ) option(USE_DOMAINS_FILE_WATCH "Pre-configure PostSRSd to watch for domains file changes" ${USE_DOMAINS_FILE} ) add_feature_info( USE_DOMAINS_FILE_WATCH USE_DOMAINS_FILE_WATCH "pre-configure PostSRSd to watch for domains file changes" ) option(TESTS_WITH_ASAN "Run test suite with AddressSanitizer" OFF) option(TESTS_WITH_REDIS "Run test suite against Redis database backend" OFF) option(DEVELOPER_BUILD "Add strict compiler options for development only" OFF) option(EXECUTABLE_WITH_ASAN "Build PostSRSd executable with AddressSanitizer" OFF ) option(GENERATE_SRS_SECRET "Generate and install a postsrsd.secret" ON) add_feature_info( GENERATE_SRS_SECRET GENERATE_SRS_SECRET "generate missing ${CMAKE_INSTALL_FULL_SYSCONFDIR}/${PROJECT_NAME}.secret on install" ) option(INSTALL_SYSTEMD_SERVICE "Install the systemd postsrsd.service unit" ON) add_feature_info( INSTALL_SYSTEMD_SERVICE INSTALL_SYSTEMD_SERVICE "install the systemd postsrsd.service unit" ) option(INSTALL_SYSTEMD_SYSUSERS "Install a systemd sysusers.d/postsrsd.conf" ${INSTALL_SYSTEMD_SERVICE} ) add_feature_info( INSTALL_SYSTEMD_SYSUSERS DO_INSTALL_SYSTEMD_SYSUSERS "instruct systemd to create the PostSRSd user \"${POSTSRSD_USER}\"" ) find_systemd_unit_destination(DETECTED_SYSTEMD_UNITDIR) set(SYSTEMD_UNITDIR "${DETECTED_SYSTEMD_UNITDIR}" CACHE PATH "Install destination for the systemd postsrsd.service unit" ) find_systemd_sysusers_destination(DETECTED_SYSTEMD_SYSUSERSDIR) set(SYSTEMD_SYSUSERSDIR "${DETECTED_SYSTEMD_SYSUSERSDIR}" CACHE PATH "Install destination for the sysusers.d configuration" ) if(POSTSRSD_CHROOTDIR) file(RELATIVE_PATH CHROOTABLE_DATADIR "${POSTSRSD_CHROOTDIR}" "${POSTSRSD_DATADIR}" ) if(CHROOTABLE_DATADIR MATCHES "^\.\.") message( FATAL_ERROR "POSTSRSD_DATADIR (${POSTSRSD_DATADIR}) must be below POSTSRSD_CHROOTDIR (${POSTSRSD_CHROOTDIR})" ) endif() if(NOT CHROOTABLE_DATADIR STREQUAL "") set(CHROOTABLE_DATADIR "${CHROOTABLE_DATADIR}/") endif() else() set(CHROOTABLE_DATADIR "${POSTSRSD_DATADIR}/") endif() if(INSTALL_SYSTEMD_SERVICE AND INSTALL_SYSTEMD_SYSUSERS AND NOT POSTSRSD_USER STREQUAL "nobody" ) set(DO_INSTALL_SYSTEMD_SYSUSERS TRUE) else() set(DO_INSTALL_SYSTEMD_SYSUSERS FALSE) endif() mark_as_advanced( BUILD_SHARED_LIBS TESTS_WITH_ASAN TESTS_WITH_REDIS GENERATE_SRS_SECRET INSTALL_SYSTEMD_SERVICE INSTALL_SYSTEMD_SYSUSERS DEVELOPER_BUILD SYSTEMD_UNITDIR SYSTEMD_SYSUSERSDIR POSTSRSD_CONFIGDIR POSTSRSD_CHROOTDIR POSTSRSD_DATADIR POSTSRSD_USER ) FetchContent_Declare( libconfuse URL https://github.com/libconfuse/libconfuse/releases/download/v3.3/confuse-3.3.tar.gz URL_HASH SHA3_256=da895d91a7755941872e73ff6522fd16810f1599862990df569459a0eee94515 FIND_PACKAGE_ARGS ) FetchContent_Declare( Hiredis GIT_REPOSITORY https://github.com/redis/hiredis GIT_TAG 67c88a05bb97c40d5c29d0680e51828627e4f362 FIND_PACKAGE_ARGS ) FetchContent_Declare( sqlite3 URL https://sqlite.org/2026/sqlite-amalgamation-3530200.zip URL_HASH SHA3_256=81142986038e18f96c4a54e1a72562ae17e502a916f2a7701eff43388cbf1a40 FIND_PACKAGE_ARGS ) FetchContent_Declare( Check URL https://github.com/libcheck/check/releases/download/0.15.2/check-0.15.2.tar.gz URL_HASH SHA3_256=bfb856a68c0ea4d930803f6bd16c1eed38910a231c9e0f0009e69310e35e7a5d FIND_PACKAGE_ARGS ) FetchContent_Declare( seccomp URL https://github.com/seccomp/libseccomp/releases/download/v2.6.0/libseccomp-2.6.0.tar.gz URL_HASH SHA3_256=1bbae54d95e09cab6ea6b490a2f5e4d4e4ac72ff7c9ab568412533c19b1c4bd0 FIND_PACKAGE_ARGS ) set(saved_CMAKE_REQUIRED_DEFINITIONS "${CMAKE_REQUIRED_DEFINITIONS}") list(APPEND CMAKE_REQUIRED_DEFINITIONS "-D_GNU_SOURCE" "-D_FILE_OFFSET_BITS=64") check_include_file(sys/inotify.h HAVE_SYS_INOTIFY_H) check_include_file(sys/time.h HAVE_SYS_TIME_H) check_include_file(sys/mman.h HAVE_SYS_MMAN_H) check_include_file(time.h HAVE_TIME_H) check_symbol_exists(chroot unistd.h HAVE_CHROOT) check_symbol_exists(close_range unistd.h HAVE_CLOSE_RANGE) check_symbol_exists(setgroups grp.h HAVE_SETGROUPS) check_type_size("unsigned long" SIZEOF_UNSIGNED_LONG) test_big_endian(HAVE_BIG_ENDIAN) set(CMAKE_REQUIRED_DEFINITIONS "${saved_CMAKE_REQUIRED_DEFINITIONS}") if(CMAKE_SYSTEM_NAME MATCHES "Solaris|SunOS") find_library(LIBSOCKET socket) find_library(LIBNSL nsl) endif() if(CMAKE_SYSTEM_NAME STREQUAL "Haiku") find_library(LIBNETWORK NAMES network net) endif() set(THREADS_PREFER_PTHREAD_FLAG TRUE) find_package(Threads QUIET) FetchContent_MakeAvailable(libconfuse) if(IS_DIRECTORY "${libconfuse_SOURCE_DIR}") set(saved_CMAKE_REQUIRED_DEFINITIONS "${CMAKE_REQUIRED_DEFINITIONS}") list(APPEND CMAKE_REQUIRED_DEFINITIONS "-D_GNU_SOURCE" "-D_FILE_OFFSET_BITS=64" ) check_include_file(string.h HAVE_STRING_H) check_include_file(strings.h HAVE_STRINGS_H) check_include_file(sys/stat.h HAVE_SYS_STAT_H) check_include_file(unistd.h HAVE_UNISTD_H) check_include_file(windows.h HAVE_WINDOWS_H) check_symbol_exists(fileno stdio.h HAVE_FILENO) check_symbol_exists(fmemopen stdio.h HAVE_FMEMOPEN) check_symbol_exists(funopen stdio.h HAVE_FUNOPEN) check_symbol_exists(isatty unistd.h HAVE_ISATTY) check_symbol_exists(reallocarray stdlib.h HAVE_REALLOCARRAY) check_symbol_exists(strcasecmp string.h HAVE_STRCASECMP) check_symbol_exists(strdup string.h HAVE_STRDUP) check_symbol_exists(strndup string.h HAVE_STRNDUP) check_symbol_exists(setenv stdlib.h HAVE_SETENV) check_symbol_exists(unsetenv stdlib.h HAVE_UNSETENV) check_symbol_exists(_putenv windows.h HAVE__PUTENV) set(CMAKE_REQUIRED_DEFINITIONS "${saved_CMAKE_REQUIRED_DEFINITIONS}") file(READ "${libconfuse_SOURCE_DIR}/configure.ac" content) if(content MATCHES "AC_INIT\\(([^ ,]+), *([^ ,]+)") set(LIBCONFUSE_NAME "${CMAKE_MATCH_1}") set(LIBCONFUSE_VERSION "${CMAKE_MATCH_2}") endif() configure_file( misc/libconfuse/config.h.in ${CMAKE_CURRENT_BINARY_DIR}/libconfuse/config.h ) find_package(FLEX) if(FLEX_FOUND) flex_target( libconfuse ${libconfuse_SOURCE_DIR}/src/lexer.l ${CMAKE_CURRENT_BINARY_DIR}/lexer.c COMPILE_FLAGS -Pcfg_yy ) set(LEXER_C ${FLEX_libconfuse_OUTPUTS}) else() set(LEXER_C ${libconfuse_SOURCE_DIR}/src/lexer.c) endif() add_library( confuse STATIC ${libconfuse_SOURCE_DIR}/src/confuse.c ${LEXER_C} $<$>:src/fmemopen.c> $<$>:src/reallocarray.c> ) target_compile_definitions( confuse PRIVATE HAVE_CONFIG_H=1 _FILE_OFFSET_BITS=64 ) target_include_directories( confuse PUBLIC $ ${CMAKE_CURRENT_BINARY_DIR}/libconfuse ) add_library(libconfuse::confuse ALIAS confuse) endif() if(WITH_REDIS) fetchcontent_makeavailable_override( Hiredis DISABLE_TESTS:BOOL=ON BUILD_SHARED_LIBS:BOOL=OFF ) mark_as_advanced( ENABLE_ASYNC_TESTS ENABLE_SSL_TESTS ENABLE_SSL ENABLE_NUGET ENABLE_EXAMPLES DISABLE_TESTS hiredis_export_name ) if(IS_DIRECTORY "${hiredis_SOURCE_DIR}") set_property( DIRECTORY "${hiredis_SOURCE_DIR}" PROPERTY EXCLUDE_FROM_ALL TRUE ) endif() if(TARGET hiredis::hiredis_static) set(HIREDIS_TARGET hiredis::hiredis_static) elseif(TARGET hiredis::hiredis) set(HIREDIS_TARGET hiredis::hiredis) elseif(TARGET hiredis) set(HIREDIS_TARGET hiredis) else() message( FATAL_ERROR "Cannot link against hiredis: no suitable CMake target found" ) endif() endif() if(WITH_SQLITE) FetchContent_MakeAvailable(sqlite3) if(IS_DIRECTORY "${sqlite3_SOURCE_DIR}") add_library(sqlite3 STATIC "${sqlite3_SOURCE_DIR}/sqlite3.c") target_include_directories(sqlite3 PUBLIC "${sqlite3_SOURCE_DIR}") target_compile_definitions( sqlite3 PRIVATE SQLITE_DQS=0 SQLITE_THREADSAFE=0 SQLITE_DEFAULT_MEMSTATUS=0 SQLITE_DEFAULT_WAL_SYNCHRONOUS=1 SQLITE_LIKE_DOESNT_MATCH_BLOBS SQLITE_MAX_EXPR_DEPTH=0 SQLITE_OMIT_DECLTYPE SQLITE_OMIT_DEPRECATED SQLITE_OMIT_PROGRESS_CALLBACK SQLITE_OMIT_SHARED_CACHE SQLITE_USE_ALLOCA ) add_library(sqlite3::sqlite3 ALIAS sqlite3) target_link_libraries(sqlite3 PUBLIC ${CMAKE_DL_LIBS}) endif() endif() if(WITH_SECCOMP) add_autotools_dependency( seccomp LIBRARY_NAME seccomp EXPORTED_TARGET seccomp::seccomp ) endif() configure_file( "${CMAKE_CURRENT_SOURCE_DIR}/src/postsrsd_build_config.h.in" "${CMAKE_CURRENT_BINARY_DIR}/postsrsd_build_config.h" ) if(DEVELOPER_BUILD AND CMAKE_C_COMPILER_ID MATCHES "GNU|Clang") add_compile_options(-Wall -Wextra -Werror) endif() add_executable( postsrsd src/config.c src/database.c src/endpoint.c src/main.c src/milter.c src/netstring.c src/sha1.c src/srs.c src/srs2.c src/util.c ) target_compile_definitions(postsrsd PRIVATE _GNU_SOURCE _FILE_OFFSET_BITS=64) target_include_directories(postsrsd PRIVATE "${CMAKE_CURRENT_BINARY_DIR}") target_compile_features(postsrsd PRIVATE c_std_99) target_link_libraries( postsrsd PRIVATE libconfuse::confuse $<$:sqlite3::sqlite3> $<$:${HIREDIS_TARGET}> $<$:seccomp::seccomp> ${LIBSOCKET} ${LIBNSL} ${LIBNETWORK} ) if(EXECUTABLE_WITH_ASAN) target_compile_options(postsrsd PRIVATE -fsanitize=address,undefined) target_link_options(postsrsd PRIVATE -fsanitize=address,undefined) endif() if(USE_DOMAINS_FILE) set(POSTSRSD_DOMAINS_CONFIG "#domains = {}") set(POSTSRSD_DOMAINS_FILE_CONFIG "domains-file = \"${POSTSRSD_CONFIGDIR}/${PROJECT_NAME}.domains\"" ) else() set(POSTSRSD_DOMAINS_CONFIG "domains = {}") set(POSTSRSD_DOMAINS_FILE_CONFIG "#domains-file =") endif() if(USE_DOMAINS_FILE_WATCH) set(POSTSRSD_DOMAINS_FILE_WATCH_CONFIG "domains-file-watch = on") else() set(POSTSRSD_DOMAINS_FILE_WATCH_CONFIG "#domains-file-watch = off") endif() configure_file( "${CMAKE_CURRENT_SOURCE_DIR}/data/postsrsd.conf.in" "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}.conf" @ONLY ) configure_file( "${CMAKE_CURRENT_SOURCE_DIR}/data/postsrsd.service.in" "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}.service" @ONLY ) configure_file( "${CMAKE_CURRENT_SOURCE_DIR}/data/sysusers.conf.in" "${CMAKE_CURRENT_BINARY_DIR}/sysusers.d/${PROJECT_NAME}.conf" @ONLY ) install(TARGETS postsrsd RUNTIME DESTINATION ${CMAKE_INSTALL_SBINDIR}) install(FILES "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}.conf" DESTINATION "${CMAKE_INSTALL_DATADIR}/doc/${PROJECT_NAME}" ) if(INSTALL_SYSTEMD_SERVICE) install(FILES "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}.service" DESTINATION "${SYSTEMD_UNITDIR}" ) endif() if(INSTALL_SYSTEMD_SYSUSERS AND NOT POSTSRSD_USER STREQUAL "nobody") install(FILES "${CMAKE_CURRENT_BINARY_DIR}/sysusers.d/${PROJECT_NAME}.conf" DESTINATION "${SYSTEMD_SYSUSERSDIR}" ) endif() if(GENERATE_SRS_SECRET) find_program(DD dd DOC "path to dd executable") find_program(BASE64 base64 DOC "path to base64 executable") find_program(OPENSSL openssl DOC "path to OpenSSL executable") find_file( RANDOM_SOURCE NAMES urandom random PATHS /dev ) mark_as_advanced(DD BASE64 OPENSSL RANDOM_SOURCE) if(BASE64) set(BASE64_ENCODE "${BASE64}") elseif(OPENSSL) set(BASE64_ENCODE "${OPENSSL} base64 -e") endif() if(DD AND BASE64_ENCODE AND RANDOM_SOURCE ) install( CODE "\ if(NOT EXISTS \"\$ENV{DESTDIR}${POSTSRSD_CONFIGDIR}/${PROJECT_NAME}.secret\") message(STATUS \"Generating: \$ENV{DESTDIR}${POSTSRSD_CONFIGDIR}/${PROJECT_NAME}.secret\") execute_process( COMMAND ${DD} if=${RANDOM_SOURCE} bs=18 count=1 COMMAND ${BASE64_ENCODE} OUTPUT_FILE \"${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}.secret\" ERROR_QUIET OUTPUT_STRIP_TRAILING_WHITESPACE ) file(INSTALL DESTINATION \"${POSTSRSD_CONFIGDIR}\" FILES \"${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}.secret\" RENAME \"${PROJECT_NAME}.secret\" PERMISSIONS OWNER_READ OWNER_WRITE) file(REMOVE \"${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}.secret\") endif()" ) endif() endif() # Create directory for chroot jail on install install(CODE "\ message(STATUS \"Installing: \$ENV{DESTDIR}${POSTSRSD_CHROOTDIR}\") file(MAKE_DIRECTORY \"\$ENV{DESTDIR}${POSTSRSD_CHROOTDIR}\")" ) if(USE_DOMAINS_FILE) install( CODE "\ if(NOT EXISTS \"\$ENV{DESTDIR}${POSTSRSD_CONFIGDIR}/${PROJECT_NAME}.domains\") message(STATUS \"Creating: \$ENV{DESTDIR}${POSTSRSD_CONFIGDIR}/${PROJECT_NAME}.domains\") file(TOUCH \"\$ENV{DESTDIR}${POSTSRSD_CONFIGDIR}/${PROJECT_NAME}.domains\") endif()" ) endif() if(BUILD_TESTING) FetchContent_MakeAvailable(Check) mark_as_advanced( AWK_PATH CHECK_ENABLE_GCOV CHECK_ENABLE_TESTS CHECK_ENABLE_TIMEOUT_TESTS ENABLE_MEMORY_LEAKING_TESTS INSTALL_CHECKMK ) if(IS_DIRECTORY "${check_SOURCE_DIR}") # Workaround for https://github.com/roehling/postsrsd/issues/161 file(REMOVE "${check_SOURCE_DIR}/src/check.h") set_property( DIRECTORY "${check_SOURCE_DIR}" PROPERTY EXCLUDE_FROM_ALL TRUE ) if(TARGET Threads::Threads) target_link_libraries(check PRIVATE Threads::Threads) endif() endif() add_subdirectory(tests) endif() if(BUILD_FUZZING) add_subdirectory(fuzz) endif() feature_summary(WHAT ENABLED_FEATURES DISABLED_FEATURES) if(DEFINED INIT_FLAVOR) message( WARNING "The INIT_FLAVOR option is no longer used by PostSRSd 2.x and will be ignored" ) endif() set(CPACK_SET_DESTDIR ON) set(CPACK_PACKAGE_NAME "postsrsd") set(CPACK_PACKAGE_VENDOR "Timo Röhling") set(CPACK_PACKAGE_RELOCATABLE OFF) set(CPACK_PACKAGE_DESCRIPTION "\ The Sender Rewriting Scheme (SRS) is a technique to forward mails from domains which deploy the Sender Policy Framework (SPF) to prohibit other Mail Transfer Agents (MTAs) from sending mails on their behalf. PostSRSd implements SRS for the Postfix MTA." ) set(CPACK_DEBIAN_PACKAGE_MAINTAINER "Timo Röhling ") set(CPACK_DEBIAN_FILE_NAME DEB-DEFAULT) set(CPACK_DEBIAN_PACKAGE_RELEASE 1) set(CPACK_DEBIAN_PACKAGE_SECTION "mail") set(CPACK_DEBIAN_PACKAGE_SHLIBDEPS ON) set(CPACK_RPM_FILE_NAME RPM-DEFAULT) set(CPACK_RPM_PACKAGE_AUTOREQ ON) set(CPACK_RPM_PACKAGE_DESCRIPTION "${CPACK_PACKAGE_DESCRIPTION}") set(CPACK_RPM_PACKAGE_LICENSE "GPLv3") set(CPACK_RPM_PACKAGE_RELEASE_DIST ON) include(CPack) roehling-postsrsd-24c678b/LICENSES/000077500000000000000000000000001526152470400167545ustar00rootroot00000000000000roehling-postsrsd-24c678b/LICENSES/BSD-3-Clause.txt000066400000000000000000000026271526152470400215060ustar00rootroot00000000000000Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the project nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. roehling-postsrsd-24c678b/LICENSES/FSFAP.txt000066400000000000000000000003401526152470400203510ustar00rootroot00000000000000Copying and distribution of this file, with or without modification, are permitted in any medium without royalty provided the copyright notice and this notice are preserved. This file is offered as-is, without any warranty. roehling-postsrsd-24c678b/LICENSES/FSFUL.txt000066400000000000000000000001321526152470400203700ustar00rootroot00000000000000The copyright holder gives unlimited permission to copy, distribute and modify this file. roehling-postsrsd-24c678b/LICENSES/GPL-3.0-only.txt000066400000000000000000001045131526152470400214200ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . roehling-postsrsd-24c678b/README.rst000066400000000000000000000241311526152470400172370ustar00rootroot00000000000000.. PostSRSd - Sender Rewriting Scheme daemon for Postfix Copyright 2012-2026 Timo Röhling SPDX-License-Identifier: GPL-3.0-only ======== PostSRSd ======== Sender Rewriting Scheme daemon for Postfix |Linux| |nbsp| |BSD| |nbsp| |Solaris| |nbsp| |Release| .. |Linux| image:: https://github.com/roehling/postsrsd/actions/workflows/linux.yml/badge.svg .. |BSD| image:: https://github.com/roehling/postsrsd/actions/workflows/bsd.yml/badge.svg .. |Solaris| image:: https://github.com/roehling/postsrsd/actions/workflows/solaris.yml/badge.svg .. |Release| image:: https://github.com/roehling/postsrsd/actions/workflows/release.yml/badge.svg .. |nbsp| unicode:: 0xA0 Overview -------- The Sender Rewriting Scheme (SRS) is a technique to forward mails from domains which deploy the Sender Policy Framework (SPF) to prohibit other Mail Transfer Agents (MTAs) from sending mails on their behalf. With SRS, an MTA can circumvent SPF restrictions by replacing the envelope sender with a temporary email address from one of their own domains. This temporary address is bound to the original sender and only valid for a certain amount of time, which prevents abuse by spammers. SRS in a nutshell ~~~~~~~~~~~~~~~~~ Imagine your server receives a mail from ``alice@example.com`` that is to be forwarded. If ``example.com`` uses the Sender Policy Framework to indicate that all legit mails originate from their server, your forwarded mail might be bounced, because you have no permission to send on behalf of ``example.com``. PostSRSd allows you to circumvent this restriction and map the sender address to one of your own domains instead. Typically, the temporary SRS address will look like ``SRS0=xxxx=yy=example.com=alice@yourdomain.org`` ("forward SRS"). If the mail is bounced later and a notification arrives, you can extract the original address from the SRS address ("reverse SRS") and relay the bounce mail to the actual sender. You might notice that the reverse SRS process could potentially be abused to turn your server into an open relay. For this reason, ``xxxx`` is a cryptographic signature and ``yy`` is a timestamp. If the signature does not verify or the timestamp is too old, the address is forged or expired, and the mail can be discarded. Installation ------------ Prebuilt packages ~~~~~~~~~~~~~~~~~ If your Linux distribution has a sufficiently recent PostSRSd package, install it! Unless you need a specific new feature or bugfix from a newer version, it will be much less of a maintenance burden. If you are interested in packaging PostSRSd for a Linux distribution, have a look at the packaging_ notes. .. _packaging: doc/packaging.rst Building from source ~~~~~~~~~~~~~~~~~~~~ Fetch the latest source tarball or clone the repository from Github_, unpack it and run:: cd path/to/source mkdir _build && cd _build cmake .. -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/usr/local make -j sudo make install .. _Github: https://github.com/roehling/postsrsd/releases/latest PostSRSd has a few external build dependencies: - CMake_ version 3.24 or newer - gcc_ or a similar C99 capable C compiler. - pkgconf_ or pkg-config is optional to improve detection of system settings - libConfuse_ is required to parse the configuration file. - sqlite3_ is optional to store envelope senders; enable it with ``-DWITH_SQLITE=ON`` as additional argument for ``cmake``. - hiredis_ is an optional alternative to store envelope senders in Redis; enable it with ``-DWITH_REDIS=ON``. - libseccomp_ and gperf_ are optional and only needed if you want to secure untrusted input handling with additional sandboxing; enable it with ``-DWITH_SECCOMP=ON``. - check_ is needed if you want to build and run the unit test suite; otherwise disable it with ``-DBUILD_TESTING=OFF``. - Python_ is optional and needed for additional blackbox tests as part of the test suite. PostSRSd relies on the FetchContent_ module of CMake for its dependency resolution. Please refer to its documentation if you wish to tweak the discovery process. .. _CMake: https://cmake.org .. _gcc: https://gcc.gnu.org .. _pkgconf: http://pkgconf.org .. _libConfuse: https://github.com/libconfuse/libconfuse .. _sqlite3: https://sqlite.org .. _hiredis: https://github.com/redis/hiredis .. _libseccomp: https://github.com/seccomp/libseccomp .. _gperf: https://github.com/jwinarske/gperf .. _check: https://github.com/libcheck/check .. _FetchContent: https://cmake.org/cmake/help/latest/module/FetchContent.html .. _Python: https://www.python.org Configuration ------------- PostSRSd itself is configured by ``postsrsd.conf`` (see the example_ for a detailed documentation of all options). PostSRSd will look for this file in ``/usr/local/etc``. The most important configuration options are ``domains`` (or ``domains-file``), so PostSRSd knows about your local domains, and ``secrets-file`` with a secret passphrase for authentication. The other options often work out of the box. You can also find the example configuration installed in ``/usr/local/share/postsrsd``. Feel free to use it as base for your own configuration. Postfix Setup ~~~~~~~~~~~~~ For integration with Postfix, the recommended mechanism is via the ``canonical`` maps of the ``cleanup`` daemon. Add the following snippet to your ``/etc/postfix/main.cf``:: sender_canonical_maps = socketmap:unix:srs:forward sender_canonical_classes = envelope_sender recipient_canonical_maps = socketmap:unix:srs:reverse recipient_canonical_classes = envelope_recipient, header_recipient The ``srs`` part in the lookup table mappings above is the path to the unix socket relative to ``/var/spool/postfix``; you will have to change this if you change the ``socketmap`` configuration of PostSRSd. If you prefer a TCP connection, e.g. ``inet:localhost:10003``, you need to change the mapping to something like ``socketmap:inet:localhost:10003:forward``. .. _example: doc/postsrsd.conf Milter Support ~~~~~~~~~~~~~~ PostSRSd 2.x has added support for the Milter protocol. You can set the ``milter`` option in ``postsrsd.conf`` and add the corresponding line to your ``etc/postfix/main.cf``:: smtpd_milters = unix:srs_milter Inotify Support ~~~~~~~~~~~~~~~ PostSRSd 2.1 added support for automatic reload if the ``domains-file`` is modified. This feature is disabled by default, but you can opt-in by enabling the ``domains-file-watch`` option. It comes with the usual caveats of modern file systems, especially regarding atomic file updates. The recommended way to update the domains file is by an atomic move, i.e., create a ``postsrsd.domains.tmp.XXXXXXX`` in the same directory, populate it, and rename it to replace the actual domains file. It is also technically possible to modify the file in-place, but this is unsafe if the system crashes. The worst way to update is to delete the existing file and create a new one in-place. This is not atomic either, and the inotify API introduces a race condition which may let PostSRSd miss the relevant file close event after the new file has been written completely. PostSRSd tries to recover from this, but there are no guarantees, so do not file any bugs if it fails. If a file change is detected, PostSRSd behaves exactly like it would if the process received a ``SIGHUP`` signal or a ``systemctl reload``. Migrating from version 1.x -------------------------- Most configuration options can no longer be configured with command line arguments, so you will have to set them in ``postsrsd.conf``. PostSRSd 1.x used shell variables in ``/etc/default/postsrsd``. If you migrate your settings, you should set - ``srs-domain`` to the value from ``SRS_DOMAIN`` - ``domains`` to the list of values from ``SRS_EXCLUDE_DOMAINS`` - ``secrets-file`` to the file name from ``SRS_SECRET`` - ``unprivileged-user`` to the user name from ``RUN_AS`` - ``chroot-dir`` to the directory from ``CHROOT`` Be aware that PostSRSd 2.x uses ``socketmap:`` tables, which are NOT compatible with ``tcp:`` tables. This also means that PostSRSd 2.x requires at least Postfix 2.10 now, and you need to update your Postfix configuration as detailed above. Frequently Asked Questions -------------------------- * **Can I configure PostSRSd so it will only rewrite the envelope sender if the email is not delivered locally?** Starting with PostSRSd 2.1, the PostSRSd milter supports this out-of-the-box: If all recipients in a mail transaction belong to one of the configured local domains, PostSRSd will assume that no forwarding will happen, and skip rewriting the envelope sender. If you prefer the socketmap behavior, you can enable the ``milter-rewrite-local`` configuration option. * **I am serving multiple domains with my MTA. Can I configure PostSRSd to rewrite addresses to the specific domain for which an email is forwarded?** It is much simpler and more robust to have a dedicated SRS (sub-)domain. You need to pick a domain for the reverse DNS lookup of your MTA IP address anyway, so setup an ``srs`` subdomain there and use it for SRS rewriting. * **I configured PostSRSd correctly; why are some of my emails still rejected with a DMARC failure?** Short Answer: Because the originating MTA is misconfigured. Long Answer: DMARC has two conditions for an email, but either of them is sufficient to pass the DMARC check: 1. The SMTP envelope sender must have the same domain as the ``From:`` address in the mail header. 2. The email must have a valid DKIM signature from the domain of the ``From:`` address. The first condition in combination with SPF prevents mail forwarding by unauthorized third parties, the second condition in combination with DKIM prevents sender address spoofing. Effectively, DMARC only allows mail forwarding if the mail is not tampered with. By design, SRS must break the first condition, but it will preserve the second, if the originating MTA signs all outgoing mails with DKIM. Unfortunately, some mail admins forget (or misconfigure) DKIM, which effectively breaks forwarding for *everyone*. Try to contact the mail administrator for the sending domain and tell them to fix their setup. * **Can you help me find the problem with my Postfix configuration?** No. roehling-postsrsd-24c678b/REUSE.toml000066400000000000000000000020761526152470400173340ustar00rootroot00000000000000version = 1 SPDX-PackageName = "PostSRSd" SPDX-PackageSupplier = "Timo Röhling " SPDX-PackageDownloadLocation = "https://github.com/roehling/postsrsd" [[annotations]] path = "**" precedence = "aggregate" SPDX-FileCopyrightText = "2012-2026, Timo Röhling " SPDX-License-Identifier = "GPL-3.0-only" [[annotations]] path = [".clang-format", ".cmake-format.json", ".pre-commit-config.yaml", "data/**", "doc/postsrsd.conf"] precedence = "aggregate" SPDX-FileCopyrightText = "2012-2026, Timo Röhling " SPDX-License-Identifier = "FSFUL" [[annotations]] path = [".github/**", "cmake/**"] precedence = "aggregate" SPDX-FileCopyrightText = "2022-2026, Timo Röhling " SPDX-License-Identifier = "FSFAP" [[annotations]] path = ["src/sha1.c", "src/sha1.h", "src/srs2.c", "src/srs2.h"] precedence = "aggregate" SPDX-FileCopyrightText = ["Gisle Ass, Peter C. Gutmann, Bruce Schneier", "2004, Shevek ", "2012-2026, Timo Röhling "] SPDX-License-Identifier = "BSD-3-Clause" roehling-postsrsd-24c678b/cmake/000077500000000000000000000000001526152470400166275ustar00rootroot00000000000000roehling-postsrsd-24c678b/cmake/FindCheck.cmake000066400000000000000000000035761526152470400214620ustar00rootroot00000000000000# Copyright 2022 Timo Röhling # SPDX-License-Identifier: FSFAP # # Copying and distribution of this file, with or without modification, are # permitted in any medium without royalty provided the copyright notice and # this notice are preserved. This file is offered as-is, without any warranty. # include(FindPackageHandleStandardArgs) find_package(Check CONFIG QUIET) if(TARGET Check::check) find_package_handle_standard_args(Check CONFIG_MODE) else() find_package(PkgConfig QUIET) if(PkgConfig_FOUND) pkg_search_module(PC_CHECK QUIET check) pkg_search_module(PC_SUBUNIT QUIET libsubunit) endif() find_path(Check_INCLUDE_DIR check.h HINTS ${PC_CHECK_INCLUDE_DIRS}) find_library( Check_LIBRARY NAMES check_pic check HINTS ${PC_CHECK_LIBRARY_DIRS} ) find_library(Check_subunit_LIBRARY subunit HINTS ${PC_SUBUNIT_LIBRARY_DIRS}) find_library(Check_m_LIBRARY m) find_library(Check_rt_LIBRARY rt) find_package(Threads REQUIRED) find_package_handle_standard_args( Check FOUND_VAR Check_FOUND REQUIRED_VARS Check_INCLUDE_DIR Check_LIBRARY ) if(Check_FOUND AND NOT TARGET Check::check) set(Check_DEPS "Threads::Threads") if(Check_subunit_LIBRARY) list(APPEND Check_DEPS "${Check_subunit_LIBRARY}") endif() if(Check_m_LIBRARY) list(APPEND Check_DEPS "${Check_m_LIBRARY}") endif() if(Check_rt_LIBRARY) list(APPEND Check_DEPS "${Check_rt_LIBRARY}") endif() add_library(Check::check UNKNOWN IMPORTED) set_target_properties( Check::check PROPERTIES IMPORTED_LOCATION "${Check_LIBRARY}" INTERFACE_INCLUDE_DIRECTORIES "${Check_INCLUDE_DIR}" INTERFACE_LINK_LIBRARIES "${Check_DEPS}" ) endif() endif() roehling-postsrsd-24c678b/cmake/FindHiredis.cmake000066400000000000000000000020641526152470400220230ustar00rootroot00000000000000# Copyright 2022 Timo Röhling # SPDX-License-Identifier: FSFAP # # Copying and distribution of this file, with or without modification, are # permitted in any medium without royalty provided the copyright notice and # this notice are preserved. This file is offered as-is, without any warranty. # include(FindPackageHandleStandardArgs) find_package(PkgConfig QUIET) if(PkgConfig_FOUND) pkg_search_module(PC_HIREDIS QUIET hiredis) endif() find_path( Hiredis_INCLUDE_DIR hiredis.h PATH_SUFFIXES hiredis HINTS ${PC_HIREDIS_INCLUDE_DIRS} ) find_library(Hiredis_LIBRARY hiredis HINTS ${PC_HIREDIS_LIBRARY_DIRS}) find_package_handle_standard_args( Hiredis FOUND_VAR Hiredis_FOUND REQUIRED_VARS Hiredis_INCLUDE_DIR Hiredis_LIBRARY ) if(Hiredis_FOUND AND NOT TARGET hiredis::hiredis) add_library(hiredis::hiredis UNKNOWN IMPORTED) set_target_properties( hiredis::hiredis PROPERTIES IMPORTED_LOCATION "${Hiredis_LIBRARY}" INTERFACE_INCLUDE_DIRECTORIES "${Hiredis_INCLUDE_DIR}" ) endif() roehling-postsrsd-24c678b/cmake/Findlibconfuse.cmake000066400000000000000000000021051526152470400225610ustar00rootroot00000000000000# Copyright 2022-2026 Timo Röhling # SPDX-License-Identifier: FSFAP # # Copying and distribution of this file, with or without modification, are # permitted in any medium without royalty provided the copyright notice and # this notice are preserved. This file is offered as-is, without any warranty. # include(FindPackageHandleStandardArgs) find_package(PkgConfig QUIET) if(PkgConfig_FOUND) pkg_search_module(PC_LIBCONFUSE QUIET libconfuse) endif() find_path(libconfuse_INCLUDE_DIR confuse.h HINTS ${PC_LIBCONFUSE_INCLUDE_DIRS}) find_library(libconfuse_LIBRARY confuse HINTS ${PC_LIBCONFUSE_LIBRARY_DIRS}) find_package_handle_standard_args( libconfuse FOUND_VAR libconfuse_FOUND REQUIRED_VARS libconfuse_INCLUDE_DIR libconfuse_LIBRARY ) if(libconfuse_FOUND AND NOT TARGET libconfuse::confuse) add_library(libconfuse::confuse UNKNOWN IMPORTED) set_target_properties( libconfuse::confuse PROPERTIES IMPORTED_LOCATION "${libconfuse_LIBRARY}" INTERFACE_INCLUDE_DIRECTORIES "${libconfuse_INCLUDE_DIR}" ) endif() roehling-postsrsd-24c678b/cmake/Findseccomp.cmake000066400000000000000000000020231526152470400220600ustar00rootroot00000000000000# Copyright 2026 Timo Röhling # SPDX-License-Identifier: FSFAP # # Copying and distribution of this file, with or without modification, are # permitted in any medium without royalty provided the copyright notice and # this notice are preserved. This file is offered as-is, without any warranty. # include(FindPackageHandleStandardArgs) find_package(PkgConfig QUIET) if(PkgConfig_FOUND) pkg_search_module(PC_SECCOMP QUIET libseccomp) endif() find_path(seccomp_INCLUDE_DIR seccomp.h HINTS ${PC_SECCOMP_INCLUDE_DIRS}) find_library(seccomp_LIBRARY seccomp HINTS ${PC_SECCOMP_LIBRARY_DIRS}) find_package_handle_standard_args( seccomp FOUND_VAR seccomp_FOUND REQUIRED_VARS seccomp_INCLUDE_DIR seccomp_LIBRARY ) if(seccomp_FOUND AND NOT TARGET seccomp::seccomp) add_library(seccomp::seccomp UNKNOWN IMPORTED) set_target_properties( seccomp::seccomp PROPERTIES IMPORTED_LOCATION "${seccomp_LIBRARY}" INTERFACE_INCLUDE_DIRECTORIES "${seccomp_INCLUDE_DIR}" ) endif() roehling-postsrsd-24c678b/cmake/Findsqlite3.cmake000066400000000000000000000020201526152470400220100ustar00rootroot00000000000000# Copyright 2022 Timo Röhling # SPDX-License-Identifier: FSFAP # # Copying and distribution of this file, with or without modification, are # permitted in any medium without royalty provided the copyright notice and # this notice are preserved. This file is offered as-is, without any warranty. # include(FindPackageHandleStandardArgs) find_package(PkgConfig QUIET) if(PkgConfig_FOUND) pkg_search_module(PC_SQLITE3 QUIET sqlite3) endif() find_path(sqlite3_INCLUDE_DIR sqlite3.h HINTS ${PC_SQLITE3_INCLUDE_DIRS}) find_library(sqlite3_LIBRARY sqlite3 HINTS ${PC_SQLITE3_LIBRARY_DIRS}) find_package_handle_standard_args( sqlite3 FOUND_VAR sqlite3_FOUND REQUIRED_VARS sqlite3_INCLUDE_DIR sqlite3_LIBRARY ) if(sqlite3_FOUND AND NOT TARGET sqlite3::sqlite3) add_library(sqlite3::sqlite3 UNKNOWN IMPORTED) set_target_properties( sqlite3::sqlite3 PROPERTIES IMPORTED_LOCATION "${sqlite3_LIBRARY}" INTERFACE_INCLUDE_DIRECTORIES "${sqlite3_INCLUDE_DIR}" ) endif() roehling-postsrsd-24c678b/cmake/utils.cmake000066400000000000000000000114111526152470400207670ustar00rootroot00000000000000# Copyright 2022-2026 Timo Röhling # SPDX-License-Identifier: FSFAP # # Copying and distribution of this file, with or without modification, are # permitted in any medium without royalty provided the copyright notice and # this notice are preserved. This file is offered as-is, without any warranty. # include(CMakeParseArguments) include(ExternalProject) include(FetchContent) function(fetchcontent_makeavailable_override name) foreach(override IN ITEMS ${ARGN}) if(override MATCHES "^([A-Z_0-9]+):([A-Z]+)=(.*)") set(saved_${CMAKE_MATCH_1} "${${CMAKE_MATCH_1}}") unset(${CMAKE_MATCH_1}) set(${CMAKE_MATCH_1} "${CMAKE_MATCH_3}" CACHE "${CMAKE_MATCH_2}" "" FORCE ) endif() endforeach() FetchContent_MakeAvailable(${name}) foreach(override IN ITEMS ${ARGN}) if(override MATCHES "^([A-Z_0-9]+):([A-Z]+)=(.*)") set(${CMAKE_MATCH_1} "${saved_${CMAKE_MATCH_1}}" CACHE "${CMAKE_MATCH_2}" "" FORCE ) endif() endforeach() endfunction() function(add_autotools_dependency name) cmake_parse_arguments(arg "" "LIBRARY_NAME;EXPORTED_TARGET" "" ${ARGN}) FetchContent_MakeAvailable(${name}) if(NOT TARGET ${arg_EXPORTED_TARGET}) find_program(MAKE_EXECUTABLE NAMES gmake make mingw32-make REQUIRED) mark_as_advanced(MAKE_EXECUTABLE) set(library_file "${CMAKE_STATIC_LIBRARY_PREFIX}${arg_LIBRARY_NAME}${CMAKE_STATIC_LIBRARY_SUFFIX}" ) string(TOLOWER "${name}" lc_name) string(TOUPPER "${CMAKE_BUILD_TYPE}" uc_build_type) if(CMAKE_C_COMPILER_AR) set(ar_executable "${CMAKE_C_COMPILER_AR}") else() set(ar_executable "${CMAKE_AR}") endif() if(CMAKE_C_COMPILER_LAUNCHER) set(cc_executable "${CMAKE_C_COMPILER_LAUNCHER} ${CMAKE_C_COMPILER}" ) else() set(cc_executable "${CMAKE_C_COMPILER}") endif() ExternalProject_Add( Ext${name} SOURCE_DIR "${${lc_name}_SOURCE_DIR}" UPDATE_DISCONNECTED TRUE PATCH_COMMAND command -v autoreconf && autoreconf CONFIGURE_COMMAND /configure --disable-shared --prefix= "CC=${cc_executable}" "AR=${ar_executable}" "RANLIB=${CMAKE_RANLIB}" "MAKE=${MAKE_EXECUTABLE}" "CFLAGS=${CMAKE_C_FLAGS} ${CMAKE_C_FLAGS_${uc_build_type}}" BUILD_COMMAND ${MAKE_EXECUTABLE} -j INSTALL_COMMAND ${MAKE_EXECUTABLE} -j install TEST_COMMAND "" BUILD_BYPRODUCTS /lib/${library_file} ) ExternalProject_Get_Property(Ext${name} INSTALL_DIR) add_library(${arg_EXPORTED_TARGET} STATIC IMPORTED) set_target_properties( ${arg_EXPORTED_TARGET} PROPERTIES IMPORTED_LOCATION "${INSTALL_DIR}/lib/${library_file}" INTERFACE_INCLUDE_DIRECTORIES "${INSTALL_DIR}/include" ) add_dependencies(${arg_EXPORTED_TARGET} Ext${name}) file(MAKE_DIRECTORY "${INSTALL_DIR}/include") endif() endfunction() function(find_systemd_unit_destination var) if(CMAKE_INSTALL_PREFIX MATCHES "^/usr/?$") find_package(PkgConfig QUIET) if(PkgConfig_FOUND) pkg_get_variable(unitdir systemd systemdsystemunitdir) endif() if(unitdir) set(${var} "${unitdir}" PARENT_SCOPE ) else() set(${var} "/usr/lib/systemd/system" PARENT_SCOPE ) endif() elseif(CMAKE_INSTALL_PREFIX MATCHES "^/usr/local/?$") set(${var} "/usr/local/lib/systemd/system" PARENT_SCOPE ) else() set(${var} "/etc/systemd/system" PARENT_SCOPE ) endif() endfunction() function(find_systemd_sysusers_destination var) if(CMAKE_INSTALL_PREFIX MATCHES "^/usr/?$") find_package(PkgConfig QUIET) if(PkgConfig_FOUND) pkg_get_variable(sysusersdir systemd sysusersdir) endif() if(sysusersdir) set(${var} "${sysusersdir}" PARENT_SCOPE ) else() set(${var} "/usr/lib/sysusers.d" PARENT_SCOPE ) endif() elseif(CMAKE_INSTALL_PREFIX MATCHES "^/usr/local/?$") set(${var} "/usr/local/lib/sysusers.d" PARENT_SCOPE ) else() set(${var} "/etc/sysusers.d" PARENT_SCOPE ) endif() endfunction() roehling-postsrsd-24c678b/data/000077500000000000000000000000001526152470400164605ustar00rootroot00000000000000roehling-postsrsd-24c678b/data/postsrsd.conf.in000066400000000000000000000222301526152470400216140ustar00rootroot00000000000000# PostSRSd example configuration file # Copyright 2022-2026 Timo Röhling # SPDX-License-Identifier: FSFUL # # The copyright holder gives unlimited permission to copy, distribute and modify # this file. # Local domains # Your local domains need not be rewritten, so PostSRSd has to know about them. # # Example: # domains = { "example.com", "example.org", "example.net" } # # Default: # none # @POSTSRSD_DOMAINS_CONFIG@ # Local domains (file storage) # Instead of listing your local domains directly, you can also write them to a # file and have PostSRSd read it. This is particularly useful if you have a # large number of domains for which you need to act as mail forwarder. PostSRSd # reads this file before it chroots and drops root privileges. The file format # is one domain per line. # # Example: # domains-file = "@POSTSRSD_CONFIGDIR@/@PROJECT_NAME@.domains" # # Default: # none # @POSTSRSD_DOMAINS_FILE_CONFIG@ # Watch domains file for changes # You can tell PostSRSd to automatically reconfigure itself whenever the domain # file changes. Alternatively, sending SIGHUP to the PostSRSd process will also # trigger a reload. # # Default: # domains-file-watch = off # @POSTSRSD_DOMAINS_FILE_WATCH_CONFIG@ # Dedicated SRS rewrite domain. # The local domain which is used to create the ephemeral SRS envelope # addresses. It is recommended that you use a dedicated mail domain for SRS if # you serve multiple unrelated domains (e.g. for your customers), to prevent # privacy issues. If unset, the first configured local domain is used. In # either case, make sure that the SRS rewrite domain has proper mail # authentication configured, such as an SPF record in the DNS. # # Example: # srs-domain = "srs.example.com" # # Default: # none # #srs-domain = # Socketmap lookup table for Postfix integration. # Traditionally, PostSRSd interacts with Postfix through the canonicalization # lookup tables of the cleanup daemon. If you use a unix socket, be aware that # most Postfix instances will jail their cleanup daemon in a /var/spool/postfix # chroot, so no other path will be visible to them. Unix sockets are created # before PostSRSd chroots and drops root privileges. # # Examples: # socketmap = unix:/var/spool/postfix/srs # socketmap = inet:localhost:10003 # # Default: # socketmap = unix:/var/spool/postfix/srs # socketmap = unix:/var/spool/postfix/srs # Connection keep-alive timeout. # After PostSRSd has served a request, it will keep the connection open for a # while longer, in case Postfix has additional queries. PostSRSd will close # the connection after the configured time (in seconds) has expired. # # Default: # keep-alive = 30 # #keep-alive = 30 # Connection limit. # This is a hard limit for the number of concurrent connections. It is # a fail-safe to prevent PostSRSd from forking an unbounded number of # child processes. Once this limit is reached, PostSRSd will accept but # immediately close incoming connections without serving requests. # # Default: # connection-limit = 200 # #connection-limit = 200 # Secret keys for signing and verifying SRS addresses. # Rewritten addresses are tagged with a truncated HMAC-SHA1 signature, to # prevent tampering and forged envelope addresses. You can have more than # one signing secret; each line of the secrets file is considered one secret # key. If an incoming signature matches any key, it is accepted. Outgoing # signatures will always be generated with the first configured secret. # # For security reasons, you should also make sure that the file is owned and # only accessible by root (chmod 600). PostSRSd reads this file before it # chroots and drops root privileges. # # Default: # secrets-file = "@POSTSRSD_CONFIGDIR@/@PROJECT_NAME@.secret" # secrets-file = "@POSTSRSD_CONFIGDIR@/@PROJECT_NAME@.secret" # Milter endpoint for MTA integration. # PostSRSd can act as a milter to rewrite envelope addresses if it has been # built with milter support. Unix sockets are created before PostSRSd chroots # and drops root privileges. # # Examples: # milter = unix:/var/spool/postfix/srs_milter # milter = inet:localhost:9997 # # Default: # none # #milter = # Original envelope sender handling. # When the envelope sender is rewritten, the original address can either be # embedded in the rewritten address, or stored in a local database. Embedding # makes PostSRSd work fully stateless, but the full sender address needs to fit # into the localpart of the embedded address, effectively limiting the length # of forwardable sender addresses to 51 octets. Storing the sender address in a # database circumvents this problem, but makes PostSRSd vulnerable to an # attacker sending vast amounts of emails with fake sender addresses, all of # which need to be stored in the database. # # If you are unsure which option suits your use-case best, the vast majority of # mail addresses will be relatively short, so you should pick "embedded". # # Examples: # original-envelope = embedded # original-envelope = database # # Default: # original-envelope = embedded # #original-envelope = embedded # Database for envelope sender storage. # If you decide to store envelope senders in a database, this database will be # used. The option is ignored if original-envelope is set to "embedded". Also # note that PostSRSd needs to be built with SQLite or Redis support for this. # # PostSRSd accesses this database after it chroots and drops root privileges, so # the filename needs to be relative to the chroot directory. # # Examples: # envelope-database = "sqlite:@CHROOTABLE_DATADIR@senders.db" # envelope-database = "redis:localhost:6379" # # Default: # none # #envelope-database = "sqlite:@CHROOTABLE_DATADIR@senders.db" # Force milter SRS rewrite for local recipients # If PostSRSd is run as milter and finds that a particular mail has only # recipients in the configured local domains, it will assume that no # forwarding is required and skip rewriting the envelope sender. # # If this option is enabled, the milter will process sender and recipients # independently like the socketmap implementation. # # Default: # milter-rewrite-local = off # #milter-rewrite-local = off # Recipient limit per milter transaction # PostSRSd rejects emails which exceed this recipient limit, to prevent # broken or malicious MTAs from consuming arbitrary amounts of memory. The # default limit matches the Postfix default limit for SMTP transactions. # # Default: # milter-recipient-limit = 1000 # #milter-recipient-limit = 1000 # SRS tag separator # This is the character following the initial SRS0 or SRS1 tag of a generated # sender address. Valid separators are "=", "+", and "-". Unless you have a # very good reason, you should leave this setting at its default. # # Default: # separator = "=" # #separator = "=" # SRS hash signature length # Any SRS address will be signed with a truncated hash to prevent tampering and # ensure that only legitimate email bounces will be returned to sender. The # default length provides adequate security without taking up too much valuable # space. Unless you know what you are doing, you should leave this setting at # its default. # # WARNING: You can break your mail server (or worse, turn it into a spam relay) # if you mess up this setting. # # Default: # hash-length = 4 # #hash-length = 4 # SRS minimum acceptable hash signature length # This is the mininum signature length that PostSRSd considers valid. It is a # separate setting because if you decide to increase the hash length, you may # want to keep accepting the shorter hashes for a 24 hour grace period. Again, # Unless you know what you are doing, you should leave this setting at its # default. # # WARNING: You can break your mail server (or worse, turn it into a spam relay) # if you mess up this setting. # # Default: # hash-minimum = 4 # #hash-minimum = 4 # Always rewrite sender addresses # You can force PostSRSd to rewrite any sender address, even if it has been # rewritten already. You probably do not want to do this, though. # # Default: # always-rewrite = off # #always-rewrite = off # Execute PostSRSd as unprivileged user # Drop root privileges and run as this user before entering the main loop and # handling untrusted input. To prevent PostSRSd from changing users, set this to # the empty string. # # Default: # unprivileged-user = "@POSTSRSD_USER@" # #unprivileged-user = "@POSTSRSD_USER@" # Execute PostSRSd in chroot jail # PostSRSd will jail itself in the given directory, which adds an additional # layer of protection against the exploitation of security bugs in PostSRSd. To # prevent PostSRSd from chrooting, set this to the empty string. # # Default: # chroot-dir = "@POSTSRSD_CHROOTDIR@" # #chroot-dir = "@POSTSRSD_CHROOTDIR@" # Syslog # PostSRSd writes log messages to stderr. If you enable this option, PostSRSd # will also send all messages to the syslog mail facility. # # Default: # syslog = off # #syslog = off # Debug # This option makes PostSRSd more verbose in its logging, which can be useful # to hunt down configuration problems. # # Default: # debug = off # #debug = off # Seccomp sandboxing # This option enables additional sandboxing while handling untrusted input. # # Default: # seccomp = on # #seccomp = on roehling-postsrsd-24c678b/data/postsrsd.service.in000066400000000000000000000021131526152470400223250ustar00rootroot00000000000000# PostSRSd systemd service file # Copyright 2022-2026 Timo Röhling # SPDX-License-Identifier: FSFUL # # The copyright holder gives unlimited permission to copy, distribute and modify # this file. [Unit] Description=Sender Rewriting Scheme daemon for Postfix Before=postfix.service After=network.target [Service] Type=notify-reload ExecStart=@CMAKE_INSTALL_FULL_SBINDIR@/postsrsd -C @POSTSRSD_CONFIGDIR@/@PROJECT_NAME@.conf CapabilityBoundingSet=CAP_DAC_OVERRIDE CAP_NET_BIND_SERVICE CAP_SETGID CAP_SETUID CAP_SYS_CHROOT LockPersonality=yes MemoryDenyWriteExecute=yes NoNewPrivileges=yes NotifyAccess=main PrivateDevices=yes PrivateTmp=yes ProcSubset=pid ProtectClock=yes ProtectControlGroups=yes ProtectHome=yes ProtectHostname=yes ProtectKernelLogs=yes ProtectKernelModules=yes ProtectKernelTunables=yes ProtectProc=noaccess ProtectSystem=strict ReadWritePaths=/var/spool/postfix @POSTSRSD_CHROOTDIR@ RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 RestrictNamespaces=yes RestrictRealtime=yes RestrictSUIDSGID=yes SystemCallArchitectures=native UMask=077 [Install] WantedBy=multi-user.target roehling-postsrsd-24c678b/data/sysusers.conf.in000066400000000000000000000003611526152470400216340ustar00rootroot00000000000000# PostSRSd sysusers.d configuration file # Copyright 2023 Timo Röhling # SPDX-License-Identifier: FSFUL # # The copyright holder gives unlimited permission to copy, distribute and modify # this file. u @POSTSRSD_USER@ - "PostSRSd user" - - roehling-postsrsd-24c678b/doc/000077500000000000000000000000001526152470400163145ustar00rootroot00000000000000roehling-postsrsd-24c678b/doc/packaging.rst000066400000000000000000000126141526152470400207760ustar00rootroot00000000000000.. PostSRSd - Sender Rewriting Scheme daemon for Postfix Copyright 2012-2026 Timo Röhling SPDX-License-Identifier: GPL-3.0-only ======================== PostSRSd Packaging Notes ======================== Introduction ------------ Thank you for taking an interest in PostSRSd and for all the work you put in to make my software available to a broader audience! I have tried to make PostSRSd easy to package, and this document is intended to document a few advanced CMake features you can use to adapt PostSRSd for your distribution. Feel free to open an issue if you think that PostSRSd can be improved. Third-Party Dependencies ------------------------ PostSRSd has gained a few external dependencies with its 2.0 rewrite, and it uses the CMake FetchContent_ module to manage those. By default, PostSRSd will look for installed system libraries and fall back to downloading the sources of its dependencies at configure time, building them, and linking them statically into the executable. For self-contained builds, you may want to pass the additional CMake options ``-DFETCHCONTENT_FULLY_DISCONNECTED -DFETCHCONTENT_TRY_FIND_PACKAGE_MODE=ALWAYS`` to make sure that no attempts to download anything are made. .. _FetchContent: https://cmake.org/cmake/help/latest/module/FetchContent.html Tweaking the Default Configuration ---------------------------------- PostSRSd mostly relies on the GNUInstallDirs_ module to discover the correct paths for data files. Additionally, PostSRSd has a few custom CMake options you can set with ``-D=`` and tweak the default settings for your users: - ``POSTSRSD_USER``: the unprivileged user as which PostSRSd is supposed to run. Defaults to ``nobody``. Note that this value can always be overridden in ``postsrsd.conf`` by the user. - ``POSTSRSD_CONFIGDIR``: the location where PostSRSd should store configuration files. The default is ``${CMAKE_INSTALL_FULL_SYSCONFDIR}``. - ``POSTSRSD_DATADIR``: the location where PostSRSd should store runtime files such as the SQLite database for envelope senders (if PostSRSd is configured to use that). The default is ``${CMAKE_INSTALL_LOCALSTATEDIR}/lib/postsrsd``. Note that this value can always be overridden in ``postsrsd.conf`` by the user. - ``POSTSRSD_CHROOTDIR``: the location where PostSRSd is supposed to jail itself. Defaults to ``${POSTSRSD_DATADIR}``. Note that this value can always be overridden in ``postsrsd.conf`` by the user. - ``GENERATE_SRS_SECRET``: If set to ``ON`` (the default), PostSRSd will create ``postsrsd.secret`` if it does not exist. This is helpful to make a source installation secure by default, but less so for a distributed binary package. - ``USE_DOMAINS_FILE``: If set to ``ON``, the generated default configuration will use the domains file. This is disabled by default. Note that this can always be overridden in ``postsrsd.conf`` by the user. - ``USE_DOMAINS_FILE_WATCH``: If set to ``ON``, the generated default configuration will enable inotify support and automatically reload if the domains file is changed. This is disabled by default. Note that this can always be overridden in ``postsrsd.conf`` by the user. - ``INSTALL_SYSTEMD_SERVICE``: If set to ``ON`` (the default), a postsrsd.service unit will be installed to allow starting PostSRSd via systemd. You can disable this if your distribution uses a different init system. - ``INSTALL_SYSTEMD_SYSUSERS``: If set to ``ON``, a sysusers.d config snippet will be installed which instructs systemd to create the ``POSTSRSD_USER`` system user if it not exists. This is disabled by default. - ``SYSTEMD_UNITDIR``: the intended install destination for the ``postsrsd.service`` file. The default should be fine for most systems, but you can override it if the auto-detected location is wrong. - ``SYSTEMD_SYSUSERSDIR``: the intended install destination for the sysusers.d configuration file. The default should be fine for most systems, but you can override it if the auto-detected location is wrong. - ``DEVELOPER_BUILD``: this makes the compiler treat all warnings as errors and enable as much of them as possible. While certainly useful for me as upstream developer (and for the Github CI), you should keep this option disabled. It will not do much for you except likely break your package build each time a new compiler version is released. - ``TESTS_WITH_ASAN``: If set to ``ON``, the unit tests will be linked against the AddressSanitizer and LeakSanitizer libraries to catch common memory handling bugs. Enabling this option does not affect the PostSRSd executable, it will only be used for the test suite. It is disabled by default. - ``TESTS_WITH_REDIS``: If set to ``ON``, the test suite will assume that a Redis instance is available at ``localhost:6379``, and run additional database related tests. This is disabled by default and has no effect unless ``WITH_REDIS=ON`` is also set. - ``EXECUTABLE_WITH_ASAN``: If set to ``ON``, the PostSRSd executable itself will be linked against the AddressSanitizer and LeakSanitizer libraries. This is useful to detect memory handling bugs in the blackbox tests, but comes at a performance cost and also weakens the SECCOMP sandboxing, as the sanitizer needs additional permissions. It is disabled by default and you should keep it disabled for release builds. .. _GNUInstallDirs: https://cmake.org/cmake/help/latest/module/GNUInstallDirs.html roehling-postsrsd-24c678b/doc/postsrsd.conf000066400000000000000000000220411526152470400210430ustar00rootroot00000000000000# PostSRSd example configuration file # Copyright 2022-2026 Timo Röhling # SPDX-License-Identifier: FSFUL # # The copyright holder gives unlimited permission to copy, distribute and modify # this file. # Local domains # Your local domains need not be rewritten, so PostSRSd has to know about them. # # Example: # domains = { "example.com", "example.org", "example.net" } # # Default: # none # domains = {} # Local domains (file storage) # Instead of listing your local domains directly, you can also write them to a # file and have PostSRSd read it. This is particularly useful if you have a # large number of domains for which you need to act as mail forwarder. PostSRSd # reads this file before it chroots and drops root privileges. The file format # is one domain per line. # # Example: # domains-file = "/usr/local/etc/postsrsd.domains" # # Default: # none # #domains-file = # Watch domains file for changes # You can tell PostSRSd to automatically reconfigure itself whenever the domain # file changes. Alternatively, sending SIGHUP to the PostSRSd process will also # trigger a reload. # # Default: # domains-file-watch = off # #domains-file-watch = off # Dedicated SRS rewrite domain. # The local domain which is used to create the ephemeral SRS envelope # addresses. It is recommended that you use a dedicated mail domain for SRS if # you serve multiple unrelated domains (e.g. for your customers), to prevent # privacy issues. If unset, the first configured local domain is used. In # either case, make sure that the SRS rewrite domain has proper mail # authentication configured, such as an SPF record in the DNS. # # Example: # srs-domain = "srs.example.com" # # Default: # none # #srs-domain = # Socketmap lookup table for Postfix integration. # Traditionally, PostSRSd interacts with Postfix through the canonicalization # lookup tables of the cleanup daemon. If you use a unix socket, be aware that # most Postfix instances will jail their cleanup daemon in a /var/spool/postfix # chroot, so no other path will be visible to them. Unix sockets are created # before PostSRSd chroots and drops root privileges. # # Examples: # socketmap = unix:/var/spool/postfix/srs # socketmap = inet:localhost:10003 # # Default: # socketmap = unix:/var/spool/postfix/srs # socketmap = unix:/var/spool/postfix/srs # Connection keep-alive timeout. # After PostSRSd has served a request, it will keep the connection open for a # while longer, in case Postfix has additional queries. PostSRSd will close # the connection after the configured time (in seconds) has expired. # # Default: # keep-alive = 30 # #keep-alive = 30 # Connection limit. # This is a hard limit for the number of concurrent connections. It is # a fail-safe to prevent PostSRSd from forking an unbounded number of # child processes. Once this limit is reached, PostSRSd will accept but # immediately close incoming connections without serving requests. # # Default: # connection-limit = 200 # #connection-limit = 200 # Secret keys for signing and verifying SRS addresses. # Rewritten addresses are tagged with a truncated HMAC-SHA1 signature, to # prevent tampering and forged envelope addresses. You can have more than # one signing secret; each line of the secrets file is considered one secret # key. If an incoming signature matches any key, it is accepted. Outgoing # signatures will always be generated with the first configured secret. # # For security reasons, you should also make sure that the file is owned and # only accessible by root (chmod 600). PostSRSd reads this file before it # chroots and drops root privileges. # # Default: # secrets-file = "/usr/local/etc/postsrsd.secret" # secrets-file = "/usr/local/etc/postsrsd.secret" # Milter endpoint for MTA integration. # PostSRSd can act as a milter to rewrite envelope addresses if it has been # built with milter support. Unix sockets are created before PostSRSd chroots # and drops root privileges. # # Examples: # milter = unix:/var/spool/postfix/srs_milter # milter = inet:localhost:9997 # # Default: # none # #milter = # Original envelope sender handling. # When the envelope sender is rewritten, the original address can either be # embedded in the rewritten address, or stored in a local database. Embedding # makes PostSRSd work fully stateless, but the full sender address needs to fit # into the localpart of the embedded address, effectively limiting the length # of forwardable sender addresses to 51 octets. Storing the sender address in a # database circumvents this problem, but makes PostSRSd vulnerable to an # attacker sending vast amounts of emails with fake sender addresses, all of # which need to be stored in the database. # # If you are unsure which option suits your use-case best, the vast majority of # mail addresses will be relatively short, so you should pick "embedded". # # Examples: # original-envelope = embedded # original-envelope = database # # Default: # original-envelope = embedded # #original-envelope = embedded # Database for envelope sender storage. # If you decide to store envelope senders in a database, this database will be # used. The option is ignored if original-envelope is set to "embedded". Also # note that PostSRSd needs to be built with SQLite or Redis support for this. # # PostSRSd accesses this database after it chroots and drops root privileges, so # the filename needs to be relative to the chroot directory. # # Examples: # envelope-database = "sqlite:senders.db" # envelope-database = "redis:localhost:6379" # # Default: # none # #envelope-database = "sqlite:senders.db" # Force milter SRS rewrite for local recipients # If PostSRSd is run as milter and finds that a particular mail has only # recipients in the configured local domains, it will assume that no # forwarding is required and skip rewriting the envelope sender. # # If this option is enabled, the milter will process sender and recipients # independently like the socketmap implementation. # # Default: # milter-rewrite-local = off # #milter-rewrite-local = off # Recipient limit per milter transaction # PostSRSd rejects emails which exceed this recipient limit, to prevent # broken or malicious MTAs from consuming arbitrary amounts of memory. The # default limit matches the Postfix default limit for SMTP transactions. # # Default: # milter-recipient-limit = 1000 # #milter-recipient-limit = 1000 # SRS tag separator # This is the character following the initial SRS0 or SRS1 tag of a generated # sender address. Valid separators are "=", "+", and "-". Unless you have a # very good reason, you should leave this setting at its default. # # Default: # separator = "=" # #separator = "=" # SRS hash signature length # Any SRS address will be signed with a truncated hash to prevent tampering and # ensure that only legitimate email bounces will be returned to sender. The # default length provides adequate security without taking up too much valuable # space. Unless you know what you are doing, you should leave this setting at # its default. # # WARNING: You can break your mail server (or worse, turn it into a spam relay) # if you mess up this setting. # # Default: # hash-length = 4 # #hash-length = 4 # SRS minimum acceptable hash signature length # This is the mininum signature length that PostSRSd considers valid. It is a # separate setting because if you decide to increase the hash length, you may # want to keep accepting the shorter hashes for a 24 hour grace period. Again, # Unless you know what you are doing, you should leave this setting at its # default. # # WARNING: You can break your mail server (or worse, turn it into a spam relay) # if you mess up this setting. # # Default: # hash-minimum = 4 # #hash-minimum = 4 # Always rewrite sender addresses # You can force PostSRSd to rewrite any sender address, even if it has been # rewritten already. You probably do not want to do this, though. # # Default: # always-rewrite = off # #always-rewrite = off # Execute PostSRSd as unprivileged user # Drop root privileges and run as this user before entering the main loop and # handling untrusted input. To prevent PostSRSd from changing users, set this to # the empty string. # # Default: # unprivileged-user = "nobody" # #unprivileged-user = "nobody" # Execute PostSRSd in chroot jail # PostSRSd will jail itself in the given directory, which adds an additional # layer of protection against the exploitation of security bugs in PostSRSd. To # prevent PostSRSd from chrooting, set this to the empty string. # # Default: # chroot-dir = "/usr/local/var/lib/postsrsd" # #chroot-dir = "/usr/local/var/lib/postsrsd" # Syslog # PostSRSd writes log messages to stderr. If you enable this option, PostSRSd # will also send all messages to the syslog mail facility. # # Default: # syslog = off # #syslog = off # Debug # This option makes PostSRSd more verbose in its logging, which can be useful # to hunt down configuration problems. # # Default: # debug = off # #debug = off # Seccomp sandboxing # This option enables additional sandboxing while handling untrusted input. # # Default: # seccomp = on # #seccomp = on roehling-postsrsd-24c678b/fuzz/000077500000000000000000000000001526152470400165455ustar00rootroot00000000000000roehling-postsrsd-24c678b/fuzz/CMakeLists.txt000066400000000000000000000064211526152470400213100ustar00rootroot00000000000000# PostSRSd - Sender Rewriting Scheme daemon for Postfix # Copyright 2012-2026 Timo Röhling # SPDX-License-Identifier: GPL-3.0-only # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, version 3. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # find_program(AFL_FUZZ afl-fuzz) add_library( postsrsd_fuzz fuzz.c ${PROJECT_SOURCE_DIR}/src/config.c ${PROJECT_SOURCE_DIR}/src/database.c ${PROJECT_SOURCE_DIR}/src/endpoint.c ${PROJECT_SOURCE_DIR}/src/main.c ${PROJECT_SOURCE_DIR}/src/milter.c ${PROJECT_SOURCE_DIR}/src/netstring.c ${PROJECT_SOURCE_DIR}/src/sha1.c ${PROJECT_SOURCE_DIR}/src/srs.c ${PROJECT_SOURCE_DIR}/src/srs2.c ${PROJECT_SOURCE_DIR}/src/util.c ) target_compile_definitions( postsrsd_fuzz PRIVATE POSTSRSD_FUZZING _GNU_SOURCE _FILE_OFFSET_BITS=64 ) target_include_directories( postsrsd_fuzz PUBLIC ${PROJECT_SOURCE_DIR}/src ${PROJECT_BINARY_DIR} ) target_compile_options( postsrsd_fuzz PRIVATE -fsanitize=address,undefined -fno-omit-frame-pointer ) target_link_options(postsrsd_fuzz PRIVATE -fsanitize=address,undefined) target_compile_features(postsrsd_fuzz PRIVATE c_std_99) target_link_libraries( postsrsd_fuzz PRIVATE libconfuse::confuse $<$:sqlite3::sqlite3> $<$:${HIREDIS_TARGET}> $<$:seccomp::seccomp> ${LIBSOCKET} ${LIBNSL} ${LIBNETWORK} ) function(add_fuzzer_harness name) cmake_parse_arguments(arg "" "SEED;DICT" "" ${ARGN}) add_executable(${name}_harness ${name}.c) target_compile_options( ${name}_harness PRIVATE -fsanitize=fuzzer,address,undefined -fno-omit-frame-pointer ) target_link_options( ${name}_harness PRIVATE -fsanitize=fuzzer,address,undefined ) target_link_libraries(${name}_harness PRIVATE postsrsd_fuzz) file(MAKE_DIRECTORY ${PROJECT_BINARY_DIR}/FUZZING/${name}) set(fuzzer_call ${AFL_FUZZ} -G 4096 -o "${PROJECT_BINARY_DIR}/FUZZING/${name}" ) if(arg_SEED) list(APPEND fuzzer_call -i "${CMAKE_CURRENT_SOURCE_DIR}/seeds/${arg_SEED}" ) endif() if(arg_DICT) list(APPEND fuzzer_call -x "${CMAKE_CURRENT_SOURCE_DIR}/dict/${arg_DICT}" ) endif() list(APPEND fuzzer_call "--" "$") message(STATUS "${fuzzer_call}") add_custom_target( ${name} "${fuzzer_call}" COMMAND_EXPAND_LISTS ) endfunction() add_fuzzer_harness(fuzz_netstring SEED netstring) add_fuzzer_harness(fuzz_srs SEED srs DICT srs) add_fuzzer_harness(fuzz_socketmap SEED socketmap DICT socketmap) add_fuzzer_harness(fuzz_milter SEED milter DICT milter) add_fuzzer_harness(fuzz_milter_parsers SEED milter_parsers) roehling-postsrsd-24c678b/fuzz/FUZZ_README.rst000066400000000000000000000012471526152470400211160ustar00rootroot00000000000000.. PostSRSd - Sender Rewriting Scheme daemon for Postfix Copyright 2012-2026 Timo Röhling SPDX-License-Identifier: GPL-3.0-only ====================== PostSRSd Fuzzing Notes ====================== This is a simple fuzzing harness for AFL_ which I used to shake out some bugs:: cd path/to/source mkdir _build && cd _build cmake .. -DCMAKE_BUILD_TYPE=RelWithDebInfo -DCMAKE_C_COMPILER=/usr/bin/afl-clang-lto -DBUILD_FUZZING=ON cmake --build . --target $FUZZING_TARGET cmake --build . --target Currently implemented fuzzing targets are: ``fuzz_netstring``, ``fuzz_srs``, ``fuzz_socketmap``. .. _AFL: https://aflplus.plus/ roehling-postsrsd-24c678b/fuzz/dict/000077500000000000000000000000001526152470400174705ustar00rootroot00000000000000roehling-postsrsd-24c678b/fuzz/dict/milter000066400000000000000000000000641526152470400207070ustar00rootroot00000000000000"O" "C" "H" "M" "R" "L" "N" "B" "E" "A" "Q" "D" "6" roehling-postsrsd-24c678b/fuzz/dict/socketmap000066400000000000000000000000331526152470400213750ustar00rootroot00000000000000"forward " "reverse " "@" roehling-postsrsd-24c678b/fuzz/dict/srs000066400000000000000000000000371526152470400202220ustar00rootroot00000000000000"SRS0" "SRS1" "=" "+" "-" "@" roehling-postsrsd-24c678b/fuzz/fuzz.c000066400000000000000000000055511526152470400177150ustar00rootroot00000000000000/* PostSRSd - Sender Rewriting Scheme daemon for Postfix * Copyright 2012-2026 Timo Röhling * SPDX-License-Identifier: GPL-3.0-only * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include "fuzz.h" #include #include #include postsrsd_t* fuzz_state_create() { postsrsd_t* state = malloc(sizeof(postsrsd_t)); if (state == NULL) return NULL; init_state(state); state->cfg = config_defaults(); if (state->cfg == NULL) goto fail; cfg_setstr(state->cfg, "chroot-dir", ""); cfg_setstr(state->cfg, "unprivileged-user", ""); cfg_setbool(state->cfg, "seccomp", cfg_false); cfg_setint(state->cfg, "keep-alive", 1); cfg_setint(state->cfg, "milter-recipient-limit", 1000); cfg_setbool(state->cfg, "always-rewrite", cfg_true); state->srs = srs_new(); if (state->srs == NULL) goto fail; srs_add_secret(state->srs, "tops3cr3t"); state->srs_domain = strdup("example.com"); if (state->srs_domain == NULL) goto fail; state->local_domains = domain_set_create(); if (state->local_domains == NULL) goto fail; domain_set_add(state->local_domains, "example.com"); return state; fail: finalize_state(state); free(state); return NULL; } void fuzz_state_destroy(postsrsd_t* state) { finalize_state(state); free(state); } void fuzz_client(network_client_t client, const uint8_t* data, size_t size) { int fds[2]; if (socketpair(AF_UNIX, SOCK_STREAM, 0, fds) < 0) abort(); pid_t pid = fork(); if (pid < 0) abort(); if (pid == 0) { close(fds[0]); postsrsd_t* state = fuzz_state_create(); if (state == NULL) _exit(1); handle_socketmap_client(state, fds[1]); fuzz_state_destroy(state); close(fds[1]); _exit(0); } close(fds[1]); if (size > 4096) size = 4096; if (write(fds[0], data, size) != (ssize_t)size) abort(); shutdown(fds[0], SHUT_WR); char buffer[4096]; while (read(fds[0], buffer, sizeof(buffer)) > 0) /* do nothing */ ; close(fds[0]); int status; if (waitpid(pid, &status, 0) < 0) abort(); if (WIFSIGNALED(status)) abort(); if (WIFEXITED(status) && WEXITSTATUS(status) != 0) abort(); } roehling-postsrsd-24c678b/fuzz/fuzz.h000066400000000000000000000020071526152470400177130ustar00rootroot00000000000000/* PostSRSd - Sender Rewriting Scheme daemon for Postfix * Copyright 2012-2026 Timo Röhling * SPDX-License-Identifier: GPL-3.0-only * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef FUZZ_H #define FUZZ_H #include #include typedef void (*network_client_t)(postsrsd_t*, int); postsrsd_t* fuzz_state_create(); void fuzz_state_destroy(postsrsd_t* state); void fuzz_client(network_client_t client, const uint8_t* data, size_t size); #endif roehling-postsrsd-24c678b/fuzz/fuzz_milter.c000066400000000000000000000002761526152470400212700ustar00rootroot00000000000000#include "fuzz.h" #include #include int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { fuzz_client(handle_milter_client, data, size); return 0; } roehling-postsrsd-24c678b/fuzz/fuzz_milter_parsers.c000066400000000000000000000006131526152470400230220ustar00rootroot00000000000000#include #include #include #include #include int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { char* output; output = milter_parse_macros("i", data, size); if (output != NULL) free(output); list_t* L = list_create(); milter_parse_str_list(L, data, size); list_destroy(L, free); return 0; } roehling-postsrsd-24c678b/fuzz/fuzz_netstring.c000066400000000000000000000011131526152470400220000ustar00rootroot00000000000000#include #include #include #include #include int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { char output[1024]; size_t decoded_length = 0; netstring_decode(data, size, output, sizeof(output), &decoded_length); int fds[2]; if (pipe(fds) < 0) abort(); if (size > 4096) size = 4096; if (write(fds[1], data, size) != (ssize_t)size) abort(); close(fds[1]); netstring_read(fds[0], output, sizeof(output), &decoded_length); close(fds[0]); return 0; } roehling-postsrsd-24c678b/fuzz/fuzz_socketmap.c000066400000000000000000000003011526152470400217470ustar00rootroot00000000000000#include "fuzz.h" #include #include int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { fuzz_client(handle_socketmap_client, data, size); return 0; } roehling-postsrsd-24c678b/fuzz/fuzz_srs.c000066400000000000000000000011521526152470400205750ustar00rootroot00000000000000#include #include #include #include #include int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { srs_t* srs = srs_new(); if (srs == NULL) abort(); srs_add_secret(srs, "tops3cr3t"); srs_set_hashlength(srs, 4); srs_set_hashmin(srs, 4); srs->faketime = 1577836860; char* input = malloc(size + 1); if (input == NULL) abort(); memcpy(input, data, size); input[size] = 0; char output[4096]; srs_reverse(srs, output, sizeof(output), input); free(input); srs_free(srs); return 0; } roehling-postsrsd-24c678b/fuzz/seeds/000077500000000000000000000000001526152470400176505ustar00rootroot00000000000000roehling-postsrsd-24c678b/fuzz/seeds/gen_milter.py000077500000000000000000000010751526152470400223550ustar00rootroot00000000000000#!/usr/bin/python3 from pathlib import Path import struct DIR = Path(__file__).parent / "milter" def pkt(payload: bytes): return struct.pack(">L", len(payload)) + payload optneg = struct.pack(">cLLL", b"O", 6, 0xFF, 0xFF) mailfrom = b"M\x00" rcptto = b"R\x00" eom = b"E" (DIR / "valid").write_bytes(pkt(optneg) + pkt(mailfrom) + pkt(rcptto) + pkt(eom)) (DIR / "optneg").write_bytes(pkt(optneg)) (DIR / "mailfrom").write_bytes(pkt(mailfrom)) (DIR / "rcptto").write_bytes(pkt(rcptto)) (DIR / "eom").write_bytes(pkt(eom)) roehling-postsrsd-24c678b/fuzz/seeds/gen_milter_parsers.py000077500000000000000000000003521526152470400241110ustar00rootroot00000000000000#!/usr/bin/python3 from pathlib import Path import struct DIR = Path(__file__).parent / "milter_parsers" example_list = [b"i", b"foo", b"bar", b"foobar", b"test@example.com"] (DIR / "list").write_bytes(b"\x00".join(example_list)) roehling-postsrsd-24c678b/fuzz/seeds/gen_socketmap.py000077500000000000000000000005611526152470400230460ustar00rootroot00000000000000#!/usr/bin/python3 from pathlib import Path SEEDS = { "forward": "forward test@otherdomain.com", "reverse": "reverse SRS0=XjO9=2V=otherdomain.com=test@example.com", } DIR = Path(__file__).parent / "socketmap" DIR.mkdir(exist_ok=True) for seed_file, value in SEEDS.items(): with open(DIR / seed_file, "w") as f: f.write(f"{len(value)}:{value},") roehling-postsrsd-24c678b/fuzz/seeds/milter/000077500000000000000000000000001526152470400211445ustar00rootroot00000000000000roehling-postsrsd-24c678b/fuzz/seeds/milter/eom000066400000000000000000000000051526152470400216420ustar00rootroot00000000000000Eroehling-postsrsd-24c678b/fuzz/seeds/milter/mailfrom000066400000000000000000000000321526152470400226700ustar00rootroot00000000000000Mroehling-postsrsd-24c678b/fuzz/seeds/milter/optneg000066400000000000000000000000211526152470400223540ustar00rootroot00000000000000 Oÿÿroehling-postsrsd-24c678b/fuzz/seeds/milter/rcptto000066400000000000000000000000351526152470400224000ustar00rootroot00000000000000Rroehling-postsrsd-24c678b/fuzz/seeds/milter/valid000066400000000000000000000001151526152470400221630ustar00rootroot00000000000000 OÿÿMREroehling-postsrsd-24c678b/fuzz/seeds/milter_parsers/000077500000000000000000000000001526152470400227035ustar00rootroot00000000000000roehling-postsrsd-24c678b/fuzz/seeds/milter_parsers/list000066400000000000000000000000411526152470400235740ustar00rootroot00000000000000ifoobarfoobartest@example.comroehling-postsrsd-24c678b/fuzz/seeds/netstring/000077500000000000000000000000001526152470400216655ustar00rootroot00000000000000roehling-postsrsd-24c678b/fuzz/seeds/netstring/a000066400000000000000000000000061526152470400220240ustar00rootroot000000000000001:a, roehling-postsrsd-24c678b/fuzz/seeds/netstring/empty000066400000000000000000000000041526152470400227400ustar00rootroot000000000000000:, roehling-postsrsd-24c678b/fuzz/seeds/netstring/forward_foobar000066400000000000000000000000241526152470400246000ustar00rootroot0000000000000017:forward foo@bar, roehling-postsrsd-24c678b/fuzz/seeds/netstring/test000066400000000000000000000000111526152470400225570ustar00rootroot000000000000004:test, roehling-postsrsd-24c678b/fuzz/seeds/socketmap/000077500000000000000000000000001526152470400216365ustar00rootroot00000000000000roehling-postsrsd-24c678b/fuzz/seeds/socketmap/forward000066400000000000000000000000401526152470400232170ustar00rootroot0000000000000028:forward test@otherdomain.com,roehling-postsrsd-24c678b/fuzz/seeds/socketmap/reverse000066400000000000000000000000711526152470400232320ustar00rootroot0000000000000053:reverse SRS0=XjO9=2V=otherdomain.com=test@example.com,roehling-postsrsd-24c678b/fuzz/seeds/srs/000077500000000000000000000000001526152470400204575ustar00rootroot00000000000000roehling-postsrsd-24c678b/fuzz/seeds/srs/empty000066400000000000000000000000001526152470400215260ustar00rootroot00000000000000roehling-postsrsd-24c678b/fuzz/seeds/srs/malformed1000066400000000000000000000000051526152470400224240ustar00rootroot00000000000000SRS0=roehling-postsrsd-24c678b/fuzz/seeds/srs/malformed2000066400000000000000000000000121526152470400224230ustar00rootroot00000000000000SRS0=AAAA=roehling-postsrsd-24c678b/fuzz/seeds/srs/malformed3000066400000000000000000000000151526152470400224270ustar00rootroot00000000000000SRS0=AAAA=AA=roehling-postsrsd-24c678b/fuzz/seeds/srs/plain000066400000000000000000000000201526152470400214750ustar00rootroot00000000000000test@example.comroehling-postsrsd-24c678b/fuzz/seeds/srs/valid000066400000000000000000000000551526152470400215010ustar00rootroot00000000000000SRS0=XjO9=2V=otherdomain.com=test@example.comroehling-postsrsd-24c678b/misc/000077500000000000000000000000001526152470400165025ustar00rootroot00000000000000roehling-postsrsd-24c678b/misc/libconfuse/000077500000000000000000000000001526152470400206335ustar00rootroot00000000000000roehling-postsrsd-24c678b/misc/libconfuse/config.h.in000066400000000000000000000014141526152470400226560ustar00rootroot00000000000000/* PostSRSd - Sender Rewriting Scheme daemon for Postfix * Copyright 2026 Timo Röhling * SPDX-License-Identifier: FSFUL * * The copyright holder gives unlimited permission to copy, distribute and modify * this file. */ #ifndef LIBCONFUSE_CONFIG_H #define LIBCONFUSE_CONFIG_H #define PACKAGE_STRING "@LIBCONFUSE_NAME@" #define PACKAGE_VERSION "@LIBCONFUSE_VERSION@" #cmakedefine HAVE_STRING_H 1 #cmakedefine HAVE_SYS_STAT_H 1 #cmakedefine HAVE_UNISTD_H 1 #cmakedefine HAVE_FILENO 1 #cmakedefine HAVE_FMEMOPEN 1 #cmakedefine HAVE_ISATTTY 1 #cmakedefine HAVE_REALLOCARRAY 1 #cmakedefine HAVE_SETENV 1 #cmakedefine HAVE_STRCASECMP 1 #cmakedefine HAVE_STRDUP 1 #cmakedefine HAVE_STRNDUP 1 #cmakedefine HAVE_UNSETENV 1 #cmakedefine HAVE__PUTENV 1 #endif roehling-postsrsd-24c678b/src/000077500000000000000000000000001526152470400163365ustar00rootroot00000000000000roehling-postsrsd-24c678b/src/config.c000066400000000000000000000344011526152470400177510ustar00rootroot00000000000000/* PostSRSd - Sender Rewriting Scheme daemon for Postfix * Copyright 2012-2026 Timo Röhling * SPDX-License-Identifier: GPL-3.0-only * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include "config.h" #include "postsrsd_build_config.h" #include "util.h" #include #include #include #include #include #include #include #include static int parse_original_envelope(cfg_t* cfg, cfg_opt_t* opt, const char* value, void* result) { if (strcasecmp(value, "embedded") == 0) *(long*)result = SRS_ENVELOPE_EMBEDDED; else if (strcasecmp(value, "database") == 0) *(long*)result = SRS_ENVELOPE_DATABASE; else { cfg_error(cfg, "option '%s' must be either 'embedded' or 'database'", cfg_opt_name(opt)); return -1; } return 0; } static int validate_separator(cfg_t* cfg, cfg_opt_t* opt) { const char* value = cfg_opt_getstr(opt); if (strlen(value) != 1 || !strpbrk(value, "=+-")) { cfg_error(cfg, "option '%s' must be one of '=', '+', '-'", cfg_opt_name(opt)); return -1; } return 0; } static int validate_uint(cfg_t* cfg, cfg_opt_t* opt) { int value = cfg_opt_getnint(opt, cfg_opt_size(opt) - 1); if (value < 0) { cfg_error(cfg, "option '%s' must be non-negative", cfg_opt_name(opt)); return -1; } return 0; } static int validate_hash_size(cfg_t* cfg, cfg_opt_t* opt) { int value = cfg_opt_getnint(opt, cfg_opt_size(opt) - 1); if (value < 1 || value > 20) { cfg_error(cfg, "option '%s' must be between 1 and 20 inclusive.", cfg_opt_name(opt)); return -1; } return 0; } static bool is_valid_domain_name(const char* s) { char prev = 0; if (s == NULL) return false; if (*s == 0) return false; while (*s != 0) { if (*s == '.' && prev == '.') return false; if (!isalnum((unsigned char)*s) && *s != '-' && *s != '.') return false; prev = *s++; } return prev != '.'; } static int validate_domain_names(cfg_t* cfg, cfg_opt_t* opt) { unsigned ndomains = cfg_opt_size(opt); for (unsigned i = 0; i < ndomains; ++i) { const char* domain = cfg_opt_getnstr(opt, i); if (!is_valid_domain_name(domain)) { cfg_error(cfg, "option '%s' has invalid domain name '%s'", cfg_opt_name(opt), domain); return -1; } } return 0; } static int validate_unprivileged_user(cfg_t* cfg, cfg_opt_t* opt) { const char* user = cfg_opt_getstr(opt); if (NONEMPTY_STRING(user)) { struct passwd* pwd = NULL; pwd = getpwnam(user); if (pwd == NULL) { cfg_error(cfg, "option '%s' has invalid user name '%s'", cfg_opt_name(opt), user); return -1; } } return 0; } static void show_help() { puts( "PostSRSd - Sender Rewriting Scheme daemon for Postfix\n" "\n" "Available command line options:\n" " -h show this help\n" " -C load configuration from \n" " (default: " DEFAULT_CONFIG_FILE ")\n" " -c use as chroot directory\n" " (default: " DEFAULT_CHROOT_DIR ")\n" " -D daemonize by forking into background\n" " -p write PostSRSd process ID into \n" " -u drop root privileges and run as \n" " (default: " DEFAULT_POSTSRSD_USER ")\n" " -v show version number (" POSTSRSD_VERSION ")\n" #if defined(WITH_SQLITE) || defined(WITH_REDIS) || defined(WITH_SECCOMP) "\n" "This binary has been compiled with optional features:\n" # ifdef WITH_SQLITE "* SQLite database storage support\n" # endif # ifdef WITH_REDIS "* Redis database storage support\n" # endif # ifdef WITH_SECCOMP "* seccomp sandboxing support\n" # endif #endif ); } cfg_t* config_defaults() { static cfg_opt_t opts[] = { CFG_STR("srs-domain", NULL, CFGF_NODEFAULT), CFG_STR_LIST("domains", "{}", CFGF_NONE), CFG_STR("domains-file", NULL, CFGF_NODEFAULT), CFG_BOOL("domains-file-watch", cfg_false, CFGF_NONE), CFG_INT_CB("original-envelope", SRS_ENVELOPE_EMBEDDED, CFGF_NONE, parse_original_envelope), CFG_STR("separator", "=", CFGF_NONE), CFG_INT("hash-length", 4, CFGF_NONE), CFG_INT("hash-minimum", 4, CFGF_NONE), CFG_BOOL("always-rewrite", cfg_false, CFGF_NONE), CFG_STR("socketmap", "unix:/var/spool/postfix/srs", CFGF_NONE), CFG_INT("keep-alive", 30, CFGF_NONE), CFG_INT("connection-limit", 200, CFGF_NONE), CFG_STR("milter", NULL, CFGF_NODEFAULT), CFG_BOOL("milter-rewrite-local", cfg_false, CFGF_NONE), CFG_INT("milter-recipient-limit", 1000, CFGF_NONE), CFG_STR("secrets-file", DEFAULT_SECRETS_FILE, CFGF_NONE), CFG_STR("envelope-database", NULL, CFGF_NODEFAULT), CFG_STR("pid-file", NULL, CFGF_NODEFAULT), CFG_STR("unprivileged-user", DEFAULT_POSTSRSD_USER, CFGF_NONE), CFG_STR("chroot-dir", DEFAULT_CHROOT_DIR, CFGF_NONE), CFG_BOOL("seccomp", cfg_true, CFGF_NONE), CFG_BOOL("daemonize", cfg_false, CFGF_NONE), CFG_BOOL("syslog", cfg_false, CFGF_NONE), CFG_BOOL("debug", cfg_false, CFGF_NONE), CFG_END(), }; cfg_t* cfg = cfg_init(opts, CFGF_NONE); cfg_set_validate_func(cfg, "separator", validate_separator); cfg_set_validate_func(cfg, "srs-domain", validate_domain_names); cfg_set_validate_func(cfg, "domains", validate_domain_names); cfg_set_validate_func(cfg, "hash-length", validate_hash_size); cfg_set_validate_func(cfg, "hash-minimum", validate_hash_size); cfg_set_validate_func(cfg, "keep-alive", validate_uint); cfg_set_validate_func(cfg, "connection-limit", validate_uint); cfg_set_validate_func(cfg, "milter-recipient-limit", validate_uint); cfg_set_validate_func(cfg, "unprivileged-user", validate_unprivileged_user); return cfg; } cfg_t* config_from_commandline(int argc, char* const* argv) { cfg_t* cfg = config_defaults(); int opt; char* config_file = NULL; char* pid_file = NULL; char* chroot_dir = NULL; char* unprivileged_user = NULL; int daemonize = 0; int ok = 1; if (file_exists(DEFAULT_CONFIG_FILE)) string_set(&config_file, strdup(DEFAULT_CONFIG_FILE)); optind = 1; while ((opt = getopt(argc, argv, "C:c:Dhp:u:v")) != -1) { switch (opt) { case '?': return 0; case 'C': string_set(&config_file, strdup(optarg)); break; case 'c': string_set(&chroot_dir, strdup(optarg)); break; case 'D': daemonize = 1; break; case 'h': show_help(); exit(0); break; case 'p': string_set(&pid_file, strdup(optarg)); break; case 'u': string_set(&unprivileged_user, strdup(optarg)); break; case 'v': puts(POSTSRSD_VERSION); exit(0); break; default: break; } } if (config_file != NULL) { switch (cfg_parse(cfg, config_file)) { case CFG_FILE_ERROR: log_error("cannot read '%s': %s", config_file, strerror(errno)); ok = 0; break; case CFG_PARSE_ERROR: log_error("malformed configuration file '%s'", config_file); ok = 0; break; default: break; } string_set(&config_file, NULL); } if (pid_file != NULL) { cfg_setstr(cfg, "pid-file", pid_file); string_set(&pid_file, NULL); } if (unprivileged_user != NULL) { cfg_setstr(cfg, "unprivileged-user", unprivileged_user); string_set(&unprivileged_user, NULL); } if (chroot_dir != NULL) { cfg_setstr(cfg, "chroot-dir", chroot_dir); string_set(&chroot_dir, NULL); } if (daemonize) cfg_setbool(cfg, "daemonize", cfg_true); if (ok) return cfg; cfg_free(cfg); return NULL; } srs_t* srs_from_config(cfg_t* cfg) { int hash_length = cfg_getint(cfg, "hash-length"); int hash_minimum = cfg_getint(cfg, "hash-minimum"); if (hash_minimum > hash_length) { log_error("hash-minimum (%d) exceeds hash-length (%d)", hash_minimum, hash_length); return NULL; } srs_t* srs = srs_new(); srs_set_alwaysrewrite(srs, cfg_getbool(cfg, "always-rewrite")); srs_set_hashlength(srs, hash_length); srs_set_hashmin(srs, hash_minimum); srs_set_separator(srs, cfg_getstr(cfg, "separator")[0]); char* secrets_file = cfg_getstr(cfg, "secrets-file"); if (NONEMPTY_STRING(secrets_file)) { FILE* f = fopen(secrets_file, "r"); if (f) { char buffer[1024]; char* secret; while ((secret = fgets(buffer, sizeof(buffer), f)) != NULL) { char* crlf = strpbrk(secret, "\r\n"); if (crlf != NULL) *crlf = 0; if (NONEMPTY_STRING(secret)) srs_add_secret(srs, secret); } fclose(f); } else { log_error("cannot read secrets from %s", secrets_file); srs_free(srs); return NULL; } } if (srs->numsecrets == 0 || srs->secrets == NULL || srs->secrets[0] == NULL) { log_error("need at least one secret"); srs_free(srs); return NULL; } char* faketime = getenv("POSTSRSD_FAKETIME"); if (NONEMPTY_STRING(faketime)) { char* eptr; long stamp = strtol(faketime, &eptr, 10); if (eptr && *eptr == 0) { srs->faketime = stamp; log_warn( "POSTSRSD_FAKETIME=%s overrides system clock. DO NOT USE IN " "PRODUCTION!", faketime); } else { log_error("POSTSRSD_FAKETIME must be an integer"); srs_free(srs); return NULL; } } return srs; } bool srs_domains_from_config(cfg_t* cfg, char** srs_domain, struct domain_set** local_domains) { *srs_domain = NULL; *local_domains = domain_set_create(); char* domain; domain = cfg_getstr(cfg, "srs-domain"); if (NONEMPTY_STRING(domain)) *srs_domain = strdup(domain[0] == '.' ? domain + 1 : domain); unsigned ndomains = cfg_size(cfg, "domains"); for (unsigned i = 0; i < ndomains; ++i) { domain = cfg_getnstr(cfg, "domains", i); if (NONEMPTY_STRING(domain)) { if (!domain_set_add(*local_domains, domain)) log_warn("duplicate local domain: %s", domain); if (*srs_domain == NULL) *srs_domain = strdup(domain[0] == '.' ? domain + 1 : domain); } } char* domains_file = cfg_getstr(cfg, "domains-file"); if (NONEMPTY_STRING(domains_file)) { FILE* f = fopen(domains_file, "r"); if (f) { char buffer[1024]; char* end; while ((domain = fgets(buffer, sizeof(buffer), f)) != NULL) { end = strpbrk(domain, "#\r\n"); if (end != NULL) *end = 0; else end = domain + strlen(domain); while (isspace((unsigned char)domain[0])) ++domain; while (end != domain && isspace((unsigned char)*(end - 1))) *--end = 0; if (NULL_OR_EMPTY_STRING(domain)) continue; if (is_valid_domain_name(domain)) { if (!domain_set_add(*local_domains, domain)) log_warn("duplicate local domain: %s", domain); if (*srs_domain == NULL) *srs_domain = strdup(domain[0] == '.' ? domain + 1 : domain); } else { log_error("invalid domain name '%s' in domains file", domain); goto fail; } } fclose(f); } else { log_error("cannot read local domains from %s", domains_file); goto fail; } } if (*srs_domain == NULL) { log_error("no SRS domain configured"); goto fail; } domain_set_add(*local_domains, *srs_domain); return true; fail: domain_set_destroy(*local_domains); *local_domains = NULL; free(*srs_domain); *srs_domain = NULL; return false; } bool unprivileged_user_from_config(cfg_t* cfg, int* target_uid, int* target_gid) { char* user = cfg_getstr(cfg, "unprivileged-user"); if (NONEMPTY_STRING(user)) { struct passwd* pwd = NULL; pwd = getpwnam(user); if (pwd == NULL) { log_error("unknown or invalid unprivileged user: %s", user); return false; } *target_uid = pwd->pw_uid; *target_gid = pwd->pw_gid; } else { *target_uid = 0; *target_gid = 0; } return true; } roehling-postsrsd-24c678b/src/config.h000066400000000000000000000023761526152470400177640ustar00rootroot00000000000000/* PostSRSd - Sender Rewriting Scheme daemon for Postfix * Copyright 2012-2026 Timo Röhling * SPDX-License-Identifier: GPL-3.0-only * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef CONFIG_H #define CONFIG_H #define SRS_ENVELOPE_EMBEDDED 0 #define SRS_ENVELOPE_DATABASE 1 #include "srs2.h" #include "util.h" #include cfg_t* config_defaults(); cfg_t* config_from_commandline(int argc, char* const* argv); srs_t* srs_from_config(cfg_t* cfg); bool srs_domains_from_config(cfg_t* cfg, char** srs_domain, struct domain_set** other_domains); bool unprivileged_user_from_config(cfg_t* cfg, int* target_uid, int* target_gid); #endif roehling-postsrsd-24c678b/src/database.c000066400000000000000000000234631526152470400202560ustar00rootroot00000000000000/* PostSRSd - Sender Rewriting Scheme daemon for Postfix * Copyright 2012-2026 Timo Röhling * SPDX-License-Identifier: GPL-3.0-only * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include "database.h" #include "postsrsd_build_config.h" #include "util.h" #include #include #ifdef WITH_REDIS # include #endif #ifdef WITH_SQLITE # include #endif #ifdef HAVE_SYS_TIME_H # include #endif #ifdef HAVE_TIME_H # include #endif struct database { char* (*read)(database_t*, const char*); bool (*write)(database_t*, const char*, const char*, unsigned); void (*expire)(database_t*); void (*disconnect)(database_t*); void* handle; #ifdef WITH_SQLITE sqlite3_stmt *read_stmt, *write_stmt, *expire_stmt; #endif }; #ifdef WITH_SQLITE static char* db_sqlite_read(database_t* db, const char* key) { if (db->read_stmt == NULL) { sqlite3* handle = (sqlite3*)db->handle; if (sqlite3_prepare_v2(handle, "SELECT v FROM kv WHERE k = ?", -1, &db->read_stmt, NULL) != SQLITE_OK) { log_error("failed to prepare sqlite read statement"); return NULL; } } char* value = NULL; sqlite3_bind_text(db->read_stmt, 1, key, -1, SQLITE_STATIC); int result = sqlite3_step(db->read_stmt); if (result == SQLITE_ERROR) { sqlite3* handle = (sqlite3*)db->handle; log_warn("sqlite read error: %s", sqlite3_errmsg(handle)); } if (result == SQLITE_ROW) { const char* column_text = (const char*)sqlite3_column_text(db->read_stmt, 0); value = NONEMPTY_STRING(column_text) ? strdup(column_text) : NULL; } sqlite3_reset(db->read_stmt); sqlite3_clear_bindings(db->read_stmt); return value; } static bool db_sqlite_write(database_t* db, const char* key, const char* value, unsigned lifetime) { if (db->write_stmt == NULL) { sqlite3* handle = (sqlite3*)db->handle; if (sqlite3_prepare_v2(handle, "INSERT INTO kv (k, v, lt) VALUES (?, ?, ?)", -1, &db->write_stmt, NULL) != SQLITE_OK) { log_error("failed to prepare sqlite write statement"); return false; } } bool success = true; sqlite3_bind_text(db->write_stmt, 1, key, -1, SQLITE_STATIC); sqlite3_bind_text(db->write_stmt, 2, value, -1, SQLITE_STATIC); sqlite3_bind_int64(db->write_stmt, 3, time(NULL) + lifetime); if (sqlite3_step(db->write_stmt) == SQLITE_ERROR) { sqlite3* handle = (sqlite3*)db->handle; log_warn("sqlite write error: %s", sqlite3_errmsg(handle)); success = false; } sqlite3_reset(db->write_stmt); sqlite3_clear_bindings(db->write_stmt); return success; } static void db_sqlite_expire(database_t* db) { if (db->expire_stmt == NULL) { sqlite3* handle = (sqlite3*)db->handle; if (sqlite3_prepare_v2(handle, "DELETE FROM kv WHERE lt <= ?", -1, &db->expire_stmt, NULL) != SQLITE_OK) { log_error("failed to prepare sqlite expire statement"); return; } } sqlite3_bind_int64(db->expire_stmt, 1, time(NULL)); sqlite3_step(db->expire_stmt); sqlite3_reset(db->expire_stmt); } static void db_sqlite_disconnect(database_t* db) { sqlite3* handle = (sqlite3*)db->handle; sqlite3_finalize(db->expire_stmt); sqlite3_finalize(db->read_stmt); sqlite3_finalize(db->write_stmt); sqlite3_close(handle); } static bool db_sqlite_connect(database_t* db, const char* uri, bool create_if_not_exist) { sqlite3* handle; char* err; if (sqlite3_open(uri, &handle) != SQLITE_OK) { sqlite3_close(handle); return false; } if (create_if_not_exist) { if (sqlite3_exec(handle, "CREATE TABLE IF NOT EXISTS kv (" "k TEXT NOT NULL UNIQUE ON CONFLICT REPLACE," "v TEXT NOT NULL," "lt INTEGER NOT NULL);" "CREATE INDEX IF NOT EXISTS ltidx ON kv (lt)", NULL, NULL, &err) != SQLITE_OK) { if (err != NULL) { log_error("%s", err); sqlite3_free(err); } sqlite3_close(handle); return false; } } db->handle = handle; db->read = db_sqlite_read; db->write = db_sqlite_write; db->expire = db_sqlite_expire; db->disconnect = db_sqlite_disconnect; db->read_stmt = NULL; db->write_stmt = NULL; db->expire_stmt = NULL; return true; } #endif #ifdef WITH_REDIS static char* db_redis_read(database_t* db, const char* key) { char buffer[128]; snprintf(buffer, sizeof(buffer), "PostSRSd/%s", key); redisContext* handle = (redisContext*)db->handle; redisReply* reply = redisCommand(handle, "GET %s", buffer); if (reply == NULL) { log_warn("redis connection failure: %s", handle->errstr); return NULL; } char* value = NULL; if (reply->type == REDIS_REPLY_ERROR) { log_warn("redis read error: %s", reply->str); } if (reply->type == REDIS_REPLY_STRING) { value = NONEMPTY_STRING(reply->str) ? strdup(reply->str) : NULL; } freeReplyObject(reply); return value; } static bool db_redis_write(database_t* db, const char* key, const char* value, unsigned lifetime) { char buffer[128]; snprintf(buffer, sizeof(buffer), "PostSRSd/%s", key); redisContext* handle = (redisContext*)db->handle; bool success = true; redisReply* reply = redisCommand(handle, "SETEX %s %u %s", buffer, lifetime, value); if (reply == NULL) { log_warn("redis connection failure: %s", handle->errstr); return false; } if (reply->type == REDIS_REPLY_ERROR) { log_warn("redis write error: %s", reply->str); success = false; } freeReplyObject(reply); return success; } static void db_redis_disconnect(database_t* db) { redisContext* handle = (redisContext*)db->handle; redisFree(handle); } static bool db_redis_connect(database_t* db, const char* hostname, int port) { redisContext* handle; if (port > 0) { handle = redisConnect(hostname, port); if (handle == NULL) goto alloc_fail; if (handle->err) goto conn_fail; redisEnableKeepAlive(handle); } else { handle = redisConnectUnix(hostname); if (handle == NULL) goto alloc_fail; } if (handle->err) goto conn_fail; db->handle = handle; db->read = db_redis_read; db->write = db_redis_write; db->expire = NULL; db->disconnect = db_redis_disconnect; return true; conn_fail: log_error("failed to connect to redis instance: %s", handle->errstr); redisFree(handle); return false; alloc_fail: log_error("failed to allocate redis handle"); return false; } #endif database_t* database_connect(const char* uri, bool create_if_not_exist) { MAYBE_UNUSED(create_if_not_exist); if (NULL_OR_EMPTY_STRING(uri)) { log_error("not database uri configured"); return NULL; } #ifdef WITH_SQLITE if (strncmp(uri, "sqlite:", 7) == 0) { database_t* db = (database_t*)malloc(sizeof(struct database)); if (db == NULL) { log_error("failed to allocate database connection handle"); return NULL; } if (!db_sqlite_connect(db, uri + 7, create_if_not_exist)) { log_error("failed to connect to '%s'", uri); free(db); return NULL; } return db; } #endif #ifdef WITH_REDIS if (strncmp(uri, "redis:", 6) == 0) { database_t* db = (database_t*)malloc(sizeof(struct database)); if (db == NULL) { log_error("failed to allocate database connection handle"); return NULL; } int port; char* hostname = endpoint_for_redis(&uri[6], &port); if (hostname == NULL) { log_error("invalid database uri '%s'", uri); free(db); return NULL; } if (!db_redis_connect(db, hostname, port)) { log_error("failed to connect to '%s'", uri); free(hostname); free(db); return NULL; } free(hostname); return db; } #endif log_error("unsupported database '%s'", uri); return NULL; } char* database_read(database_t* db, const char* key) { if (db != NULL && key != NULL) return db->read(db, key); return NULL; } bool database_write(database_t* db, const char* key, const char* value, unsigned lifetime) { if (db != NULL && key != NULL && value != NULL) return db->write(db, key, value, lifetime); return false; } void database_expire(database_t* db) { if (db != NULL && db->expire != NULL) db->expire(db); } void database_disconnect(database_t* db) { if (db != NULL) db->disconnect(db); free(db); } roehling-postsrsd-24c678b/src/database.h000066400000000000000000000022441526152470400202550ustar00rootroot00000000000000/* PostSRSd - Sender Rewriting Scheme daemon for Postfix * Copyright 2012-2026 Timo Röhling * SPDX-License-Identifier: GPL-3.0-only * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef DATABASE_H #define DATABASE_H #include struct database; typedef struct database database_t; database_t* database_connect(const char* uri, bool create_if_not_exist); char* database_read(database_t* db, const char* key); bool database_write(database_t* db, const char* key, const char* value, unsigned lifetime); void database_expire(database_t* db); void database_disconnect(database_t* db); #endif roehling-postsrsd-24c678b/src/endpoint.c000066400000000000000000000204561526152470400203310ustar00rootroot00000000000000/* PostSRSd - Sender Rewriting Scheme daemon for Postfix * Copyright 2012-2026 Timo Röhling * SPDX-License-Identifier: GPL-3.0-only * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include "endpoint.h" #include "util.h" #include #include #include #include #include #include #include #include #include #include #ifndef SO_REUSEPORT # define SO_REUSEPORT SO_REUSEADDR #endif #ifdef SOCK_CLOEXEC # define HAVE_SOCK_CLOEXEC 1 #else # define SOCK_CLOEXEC 0 #endif #ifdef SOCK_NONBLOCK # define HAVE_SOCK_NONBLOCK 1 #else # define SOCK_NONBLOCK 0 # include #endif #define POSTSRSD_SOCKET_LISTEN_QUEUE 16 #define POSTSRSD_MAX_FDS 4 struct endpoint { size_t num_fds; int fd[POSTSRSD_MAX_FDS]; int lock; char* path; }; static bool create_unix_socket(const char* path, endpoint_t* endpoint) { struct sockaddr_un sa; if (NULL_OR_EMPTY_STRING(path)) { log_error("expected file path for unix socket"); return false; } if (endpoint->num_fds >= POSTSRSD_MAX_FDS) { log_warn("too many endpoint sockets"); return true; } size_t path_len = strlen(path); if (path_len >= sizeof(sa.sun_path)) { log_error("file path for unix socket is too long"); return false; } endpoint->lock = lock_acquire(path); if (endpoint->lock >= 0) unlink(path); mode_t old_mask = umask(0); int sock = socket(AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0); if (sock < 0) goto fail; #if !defined(HAVE_SOCK_NONBLOCK) || !defined(HAVE_SOCK_CLOEXEC) int flags = fcntl(sock, F_GETFL); if (fcntl(sock, F_SETFL, flags | O_NONBLOCK | O_CLOEXEC) < 0) goto fail; #endif sa.sun_family = AF_UNIX; memset(sa.sun_path, 0, sizeof(sa.sun_path)); memcpy(sa.sun_path, path, path_len); if (bind(sock, (const struct sockaddr*)&sa, offsetof(struct sockaddr_un, sun_path) + path_len) < 0) goto fail; if (listen(sock, POSTSRSD_SOCKET_LISTEN_QUEUE) < 0) goto fail; endpoint->fd[endpoint->num_fds++] = sock; if (endpoint->lock >= 0) endpoint->path = strdup(path); umask(old_mask); return true; fail: umask(old_mask); log_perror(errno, NULL); if (sock >= 0) close(sock); if (endpoint->lock >= 0) { lock_release(path, endpoint->lock); endpoint->lock = -1; } return false; } static bool create_inet_sockets(char* addr, int family, endpoint_t* endpoint) { const int one = 1; struct addrinfo hints, *ai; if (endpoint->num_fds >= POSTSRSD_MAX_FDS) { log_warn("too many endpoint sockets"); return true; } memset(&hints, 0, sizeof(struct addrinfo)); char* node = addr; char* service = NULL; if (addr[0] == '[') { node = ++addr; while (*addr != ']') { if (*addr == 0) { log_error("expected closing ']' in socket address"); return false; } ++addr; } *addr++ = 0; if (*addr != ':') { log_error("expected ':' separator in socket address"); return false; } service = ++addr; } else { service = strchr(addr, ':'); if (service) { *service = 0; ++service; } else { service = addr; node = NULL; } } if (NULL_OR_EMPTY_STRING(service)) { log_error("expected portnumber in socket address"); return false; } hints.ai_family = family; hints.ai_socktype = SOCK_STREAM; if (node != NULL && strcmp(node, "*") == 0) { node = NULL; hints.ai_flags |= AI_PASSIVE; } if (node != NULL && strcmp(node, "localhost") == 0) { node = NULL; } int err = getaddrinfo(node, service, &hints, &ai); if (err != 0) { log_error("%s", gai_strerror(err)); return false; } int sock = -1, count = 0, free_fds = POSTSRSD_MAX_FDS - endpoint->num_fds; for (struct addrinfo* it = ai; it; it = it->ai_next) { if (free_fds == 0) break; sock = socket(it->ai_family, it->ai_socktype | SOCK_NONBLOCK | SOCK_CLOEXEC, it->ai_protocol); if (sock < 0) goto fail; #if !defined(HAVE_SOCK_NONBLOCK) || !defined(HAVE_SOCK_CLOEXEC) int flags = fcntl(sock, F_GETFL); if (fcntl(sock, F_SETFL, flags | O_NONBLOCK | O_CLOEXEC) < 0) goto fail; #endif if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &one, sizeof(one)) < 0) goto fail; if (bind(sock, it->ai_addr, it->ai_addrlen) < 0) goto fail; if (listen(sock, POSTSRSD_SOCKET_LISTEN_QUEUE) < 0) goto fail; endpoint->fd[endpoint->num_fds++] = sock; free_fds--; count++; continue; fail: err = errno; log_perror(err, NULL); if (sock >= 0) close(sock); } freeaddrinfo(ai); if (count == 0 && err != 0) return false; return true; } endpoint_t* endpoint_create(const char* s) { endpoint_t* result = (endpoint_t*)malloc(sizeof(struct endpoint)); if (result == NULL) { log_error("failed to allocate endpoint socket handle"); return NULL; } result->num_fds = 0; for (unsigned i = 0; i < POSTSRSD_MAX_FDS; ++i) result->fd[i] = -1; result->lock = -1; result->path = NULL; const char* path = NULL; if (strncmp(s, "unix:", 5) == 0) { path = &s[5]; } else if (strncmp(s, "local:", 6) == 0) { path = &s[6]; } if (path != NULL) { if (create_unix_socket(path, result)) return result; log_error("failed to create endpoint '%s'", s); endpoint_destroy(result); return NULL; } char* addr = NULL; int family = AF_UNSPEC; if (strncmp(s, "inet:", 5) == 0) { addr = strdup(&s[5]); } else if (strncmp(s, "inet4:", 6) == 0) { addr = strdup(&s[6]); family = AF_INET; } else if (strncmp(s, "inet6:", 6) == 0) { addr = strdup(&s[6]); family = AF_INET6; } if (addr != NULL) { bool ok = create_inet_sockets(addr, family, result); free(addr); if (ok) return result; log_error("failed to create endpoint '%s'", s); endpoint_destroy(result); return NULL; } log_error("unsupported endpoint '%s'", s); endpoint_destroy(result); return NULL; } void endpoint_destroy(endpoint_t* endpoint) { if (endpoint == NULL) return; if (endpoint->lock >= 0 && endpoint->path != NULL) { lock_release(endpoint->path, endpoint->lock); } if (endpoint->path != NULL) { unlink(endpoint->path); free(endpoint->path); } for (unsigned i = 0; i < endpoint->num_fds; ++i) { int sock = endpoint->fd[i]; if (sock >= 0) close(sock); } free(endpoint); } void endpoint_release(endpoint_t* endpoint) { if (endpoint == NULL) return; if (endpoint->path != NULL) free(endpoint->path); free(endpoint); } size_t endpoint_prepare_poll(endpoint_t* endpoint, struct pollfd* pollfds, size_t max_fds) { if (endpoint == NULL) return 0; size_t count = 0; for (size_t i = 0; i < endpoint->num_fds && i < max_fds; ++i) { pollfds[i].fd = endpoint->fd[i]; pollfds[i].events = POLLIN; pollfds[i].revents = 0; ++count; } return count; } roehling-postsrsd-24c678b/src/endpoint.h000066400000000000000000000022071526152470400203300ustar00rootroot00000000000000/* PostSRSd - Sender Rewriting Scheme daemon for Postfix * Copyright 2012-2026 Timo Röhling * SPDX-License-Identifier: GPL-3.0-only * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef ENDPOINT_H #define ENDPOINT_H #include #include struct pollfd; struct endpoint; typedef struct endpoint endpoint_t; endpoint_t* endpoint_create(const char* s); void endpoint_destroy(endpoint_t* endpoint); void endpoint_release(endpoint_t* endpoint); size_t endpoint_prepare_poll(endpoint_t* endpoint, struct pollfd* pollfds, size_t max_fds); #endif roehling-postsrsd-24c678b/src/main.c000066400000000000000000001003131526152470400174240ustar00rootroot00000000000000/* PostSRSd - Sender Rewriting Scheme daemon for Postfix * Copyright 2012-2026 Timo Röhling * SPDX-License-Identifier: GPL-3.0-only * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include "main.h" #include "database.h" #include "milter.h" #include "netstring.h" #include "postsrsd_build_config.h" #include "srs.h" #include #include #include #include #include #include #include #include #include #include #include #define PAYLOAD_SIZE MILTER_PAYLOAD_SIZE #define FD_UNUSED 0 #define FD_SOCKETMAP 1 #define FD_MILTER 2 #define FD_WATCH 3 static volatile sig_atomic_t timeout = 0; static volatile sig_atomic_t reload_requested = 0, shutdown_requested = 0; static bool files_changed = false, files_changed_unsafe = false; static time_t last_file_watch_event = 0; static bool sd_notify_support = false; static sandbox_t* sandbox = NULL; void init_state(postsrsd_t* state) { state->cfg = NULL; state->srs = NULL; state->socketmap = NULL; state->milter = NULL; state->srs_domain = NULL; state->local_domains = NULL; state->file_watch = NULL; state->target_uid = 0; state->target_gid = 0; state->connection_limit = 0; } void finalize_state(postsrsd_t* state) { if (state->file_watch != NULL) { file_watch_destroy(state->file_watch); state->file_watch = NULL; } if (state->socketmap != NULL) { endpoint_destroy(state->socketmap); state->socketmap = NULL; } if (state->milter != NULL) { endpoint_destroy(state->milter); state->milter = NULL; } string_set(&state->srs_domain, NULL); if (state->local_domains != NULL) { domain_set_destroy(state->local_domains); state->local_domains = NULL; } if (state->srs != NULL) { srs_free(state->srs); state->srs = NULL; } if (state->cfg != NULL) { cfg_free(state->cfg); state->cfg = NULL; } } static bool drop_privileges(postsrsd_t* state) { const char* chroot_dir = cfg_getstr(state->cfg, "chroot-dir"); if (NONEMPTY_STRING(chroot_dir)) { #ifdef HAVE_CHROOT if (chdir(chroot_dir) < 0) { log_perror(errno, "cannot drop privileges: failed to chdir to chroot"); return false; } if (chroot(chroot_dir) < 0) { log_perror(errno, "cannot drop privileges: chroot"); return false; } #else log_error("chroot is not supported on this system"); return false; #endif } if (state->target_uid != 0 || state->target_gid != 0) { #ifdef HAVE_SETGROUPS if (setgroups(0, NULL) < 0) { log_perror(errno, "cannot drop privileges: setgroups"); return false; } #endif if (setgid(state->target_gid) < 0) { log_perror(errno, "cannot drop privileges: setgid"); return false; } if (setuid(state->target_uid) < 0) { log_perror(errno, "cannot drop privileges: setuid"); return false; } } return true; } static bool check_unprivileged_work(postsrsd_t* state) { int status; pid_t worker_pid = fork(); if (worker_pid < 0) { log_perror(errno, "fork"); return false; } if (worker_pid == 0) { if (!drop_privileges(state)) exit(EXIT_FAILURE); if (cfg_getint(state->cfg, "original-envelope") == SRS_ENVELOPE_DATABASE) { database_t* db = database_connect( cfg_getstr(state->cfg, "envelope-database"), true); if (db == NULL) exit(EXIT_FAILURE); if (cfg_getbool(state->cfg, "seccomp") && sandbox != NULL && !sandbox_enable(sandbox)) { log_fatal("failed to enable sandboxing for worker processes"); } database_expire(db); database_disconnect(db); } exit(EXIT_SUCCESS); } retry: if (waitpid(worker_pid, &status, 0) < 0) { if (errno == EINTR) goto retry; log_perror(errno, "waitpid"); return false; } if (WIFEXITED(status)) { return (WEXITSTATUS(status) == EXIT_SUCCESS); } if (WIFSIGNALED(status)) { log_error("Worker process was terminated with signal %d", (int)WTERMSIG(status)); } return false; } static bool daemonize(postsrsd_t* state) { if (!cfg_getbool(state->cfg, "daemonize")) return true; close(0); close(1); close(2); if (fork() != 0) exit(EXIT_SUCCESS); setsid(); if (fork() != 0) exit(EXIT_SUCCESS); return true; } static void on_timeout(int signum) { timeout = signum; } static void on_reload_requested(int signum) { reload_requested = signum; } static void on_shutdown_requested(int signum) { shutdown_requested = signum; } static bool prepare_client(postsrsd_t* state, int conn, database_t** db) { if (state == NULL || db == NULL) return false; *db = NULL; if (!drop_privileges(state)) return false; int flags = fcntl(conn, F_GETFL); if (flags & O_NONBLOCK) { if (fcntl(conn, F_SETFL, flags & ~O_NONBLOCK) < 0) { log_error("failed to make socket connection blocking"); return false; } } if (cfg_getint(state->cfg, "original-envelope") == SRS_ENVELOPE_DATABASE) { *db = database_connect(cfg_getstr(state->cfg, "envelope-database"), false); if (*db == NULL) return false; } signal_set_handler(SIGALRM, on_timeout); signal_reset_handler(SIGTERM); signal_reset_handler(SIGINT); if (cfg_getbool(state->cfg, "seccomp") && sandbox != NULL && !sandbox_enable(sandbox)) { log_error("failed to activate seccomp sandboxing"); return false; } return true; } void handle_socketmap_client(postsrsd_t* state, int conn) { database_t* db; if (!prepare_client(state, conn, &db)) exit(EXIT_FAILURE); const bool always_rewrite = cfg_getbool(state->cfg, "always-rewrite"); const int keep_alive = cfg_getint(state->cfg, "keep-alive"); for (;;) { char buffer[1024]; size_t len; char* addr; bool error; char* eob; if (reload_requested) break; timeout = 0; alarm(keep_alive); char* request = netstring_read(conn, buffer, sizeof(buffer), &len); if (timeout) break; if (request == NULL) { if (len != 0) { netstring_write(conn, "PERM Invalid query.", 19); log_error("invalid socketmap query, closing connection"); } break; } alarm(0); char* query_type = strtok_r(request, " ", &addr); if (query_type == NULL) { netstring_write(conn, "PERM Invalid query.", 19); log_error("invalid socketmap query, closing connection"); break; } if (len > PAYLOAD_SIZE + (size_t)(addr - request)) { netstring_write(conn, "PERM Too big.", 13); log_warn("socketmap query is too big"); continue; } char* rewritten = NULL; const char* info = NULL; if (strcmp(query_type, "forward") == 0) { rewritten = postsrsd_forward(addr, state->srs_domain, state->srs, db, always_rewrite ? NULL : state->local_domains, &error, &info, "socketmap"); } else if (strcmp(query_type, "reverse") == 0) { rewritten = postsrsd_reverse(addr, state->srs, db, &error, &info, "socketmap"); } else { error = true; info = "Invalid map."; log_warn("invalid key in socketmap query"); } if (rewritten) { eob = stpncpy(stpcpy(buffer, "OK "), rewritten, sizeof(buffer) - 4); free(rewritten); netstring_write(conn, buffer, eob - buffer); } else { if (error) { eob = stpcpy(buffer, "PERM "); } else { eob = stpcpy(buffer, "NOTFOUND "); } if (info) eob = stpncpy(eob, info, sizeof(buffer) - 9); netstring_write(conn, buffer, eob - buffer); } } database_disconnect(db); } void handle_milter_client(postsrsd_t* state, int conn) { #define MILTER_AWAIT_OPTNEG 0 #define MILTER_AWAIT_MAIL 1 #define MILTER_AWAIT_RCPT 2 #define MILTER_AWAIT_RCPT_OR_EOM 3 database_t* db; char buffer[PAYLOAD_SIZE]; size_t len, truncated; if (!prepare_client(state, conn, &db)) exit(EXIT_FAILURE); if (reload_requested) return; const bool always_rewrite = cfg_getbool(state->cfg, "always-rewrite"); const bool rewrite_local = cfg_getbool(state->cfg, "milter-rewrite-local"); const size_t milter_recipient_limit = cfg_getint(state->cfg, "milter-recipient-limit"); const int keep_alive = cfg_getint(state->cfg, "keep-alive"); int milter_state = MILTER_AWAIT_OPTNEG; char* queue_id = NULL; string_set(&queue_id, strdup("NOQUEUE")); list_t* sender = list_create(); list_t* recipients = list_create(); for (;;) { timeout = 0; alarm(keep_alive); len = milter_receive(conn, buffer, sizeof(buffer), &truncated); if (len == 0 || timeout) break; alarm(0); char action = buffer[0]; char* addr = NULL; const char* info = NULL; bool error = false; bool is_local = false; switch (action) { case MILTER_CMD_OPTNEG: if (milter_state != MILTER_AWAIT_OPTNEG) { log_error( "%s: MTA initiated unexpected milter option " "negotiation", queue_id); if (!milter_tempfail(conn)) goto done; goto cleanup; } if (!milter_handle_optneg(conn, buffer + 1, len - 1)) goto done; milter_state = MILTER_AWAIT_MAIL; break; case MILTER_CMD_MACRO: if (len > 2) string_set(&queue_id, milter_parse_macros("i", buffer + 2, len - 2)); break; case MILTER_CMD_MAIL: if (milter_state != MILTER_AWAIT_MAIL) { log_error("%s: MTA sent unexpected milter MAIL command", queue_id); if (!milter_tempfail(conn)) goto done; goto cleanup; } if (truncated > 0) { log_error("%s: MTA sent oversized milter MAIL command", queue_id); if (!milter_reject(conn)) goto done; goto cleanup; } milter_state = MILTER_AWAIT_RCPT; milter_parse_str_list(sender, buffer + 1, len - 1); if (list_size(sender) < 1) { log_error("%s: MTA sent empty milter MAIL command", queue_id); if (!milter_reject(conn)) goto done; goto cleanup; } addr = milter_parse_address(list_get(sender, 0)); if (addr == NULL) { log_error("%s: MTA sent malformed milter MAIL command", queue_id); if (!milter_reject(conn)) goto done; goto cleanup; } list_replace_at(sender, 0, addr, free); if (!milter_continue(conn)) goto done; break; case MILTER_CMD_QUIT: goto done; case MILTER_CMD_RCPT: if (milter_state != MILTER_AWAIT_RCPT && milter_state != MILTER_AWAIT_RCPT_OR_EOM) { log_error("%s: MTA sent unexpected milter RCPT command", queue_id); if (!milter_tempfail(conn)) goto done; goto cleanup; } if (truncated > 0) { log_error("%s: MTA sent oversized milter RCPT command", queue_id); if (!milter_reject(conn)) goto done; goto cleanup; } if (list_size(recipients) >= milter_recipient_limit) { log_error( "%s: MTA exceeded the recipient limit per mail " "transaction", queue_id); if (!milter_reject(conn)) goto done; goto cleanup; } list_append(recipients, strndup(buffer + 1, len - 1)); if (!milter_continue(conn)) goto done; milter_state = MILTER_AWAIT_RCPT_OR_EOM; break; case MILTER_CMD_EOM: if (milter_state != MILTER_AWAIT_RCPT_OR_EOM) { log_error("%s: MTA sent unexpected milter EOM command", queue_id); if (!milter_tempfail(conn)) goto done; goto cleanup; } if (list_size(sender) == 0) { log_error("%s: no sender envelope address", queue_id); if (!milter_reject(conn)) goto done; goto cleanup; } if (list_size(recipients) == 0) { log_error("%s: no recipient address", queue_id); if (!milter_reject(conn)) goto done; goto cleanup; } is_local = true; for (size_t i = 0; i < list_size(recipients); ++i) { char* old_rcpt = list_get(recipients, i); addr = milter_parse_address_buf(old_rcpt, buffer, sizeof(buffer)); if (addr == NULL) { log_error("%s: invalid recipient: %s", queue_id, old_rcpt); if (!milter_reject(conn)) goto done; goto cleanup; } char* rewritten = postsrsd_reverse(addr, state->srs, db, &error, &info, queue_id); if (rewritten) { if (!milter_send_str(conn, MILTER_DO_DELRCPT, old_rcpt)) goto done; if (!milter_send_str(conn, MILTER_DO_ADDRCPT, rewritten)) goto done; char* domain = strchr(rewritten, '@'); if (domain != NULL && !domain_set_contains(state->local_domains, domain + 1)) is_local = false; free(rewritten); } else if (error) { if (!milter_reject(conn)) goto done; goto cleanup; } else { char* domain = strchr(addr, '@'); if (domain != NULL) { if (SRS_IS_SRS_ADDRESS(addr) && strcasecmp(domain + 1, state->srs_domain) == 0) { log_info( "%s: rejecting invalid SRS address <%s>", queue_id, addr); if (!milter_reject(conn)) goto done; goto cleanup; } if (!domain_set_contains(state->local_domains, domain + 1)) is_local = false; } } } if (!is_local || rewrite_local || always_rewrite) { char* rewritten = postsrsd_forward( list_get(sender, 0), state->srs_domain, state->srs, db, always_rewrite ? NULL : state->local_domains, &error, &info, queue_id); if (rewritten) { list_replace_at(sender, 0, rewritten, free); if (!milter_send_str_list(conn, MILTER_DO_CHGFROM, sender)) goto done; } else if (error) { if (!milter_reject(conn)) goto done; goto cleanup; } } else { log_info( "%s: <%s> not rewritten: all recipients are in local " "domains", queue_id, (char*)list_get(sender, 0)); } if (!milter_accept(conn)) goto done; goto cleanup; case MILTER_CMD_ABORT: log_debug("%s: MTA aborted transaction", queue_id); cleanup: list_clear(sender, free); list_clear(recipients, free); string_set(&queue_id, strdup("NOQUEUE")); if (milter_state != MILTER_AWAIT_OPTNEG) milter_state = MILTER_AWAIT_MAIL; if (reload_requested) goto done; break; default: log_warn("%s: MTA sent unexpected milter command", queue_id); if (milter_state != MILTER_AWAIT_OPTNEG) { if (!milter_continue(conn)) goto done; } break; } } done: list_clear(sender, free); list_clear(recipients, free); string_set(&queue_id, NULL); database_disconnect(db); } static void on_file_watch_event(const char* path, unsigned what, size_t cookie) { MAYBE_UNUSED(path); MAYBE_UNUSED(cookie); if (what & FW_MODIFIED) { files_changed = true; files_changed_unsafe = false; } else if (what & FW_CREATED) { files_changed_unsafe = true; } if (what & FW_CHANGING) { files_changed_unsafe = false; } time(&last_file_watch_event); } static bool config_changed_str(cfg_t* old_cfg, cfg_t* new_cfg, const char* name) { if (old_cfg == NULL) return new_cfg != NULL; const char* old_value = cfg_getstr(old_cfg, name); const char* new_value = cfg_getstr(new_cfg, name); if (old_value == NULL) return new_value != NULL; if (new_value != NULL) return strcmp(old_value, new_value) != 0; return true; } static bool setup_state(int argc, char** argv, postsrsd_t* state) { postsrsd_t new_state; bool socketmap_rollback = false; bool milter_rollback = false; init_state(&new_state); new_state.cfg = config_from_commandline(argc, argv); if (new_state.cfg == NULL) goto fail; if (cfg_getbool(new_state.cfg, "syslog")) log_enable_syslog(); else log_disable_syslog(); log_set_verbosity(cfg_getbool(new_state.cfg, "debug") ? LogDebug : LogInfo); new_state.srs = srs_from_config(new_state.cfg); if (new_state.srs == NULL) goto fail; const char* domains_file = cfg_getstr(new_state.cfg, "domains-file"); if (cfg_getbool(new_state.cfg, "domains-file-watch") && NONEMPTY_STRING(domains_file)) { new_state.file_watch = file_watch_create(); if (new_state.file_watch == NULL) { log_error("failed to setup inotify watch"); goto fail; } file_watch_if_modified(new_state.file_watch, domains_file, on_file_watch_event); } if (!srs_domains_from_config(new_state.cfg, &new_state.srs_domain, &new_state.local_domains)) goto fail; if (!unprivileged_user_from_config(new_state.cfg, &new_state.target_uid, &new_state.target_gid)) goto fail; if (!check_unprivileged_work(&new_state)) goto fail; if (config_changed_str(state->cfg, new_state.cfg, "socketmap")) { const char* value = cfg_getstr(new_state.cfg, "socketmap"); if (NONEMPTY_STRING(value)) { new_state.socketmap = endpoint_create(value); if (new_state.socketmap == NULL) goto fail; } } else { /* We want to keep the socketmap, so we move it from the old state before we actually commit to the new state. This needs to be rolled back if a configuration error occurs later. */ new_state.socketmap = state->socketmap; state->socketmap = NULL; socketmap_rollback = true; } if (config_changed_str(state->cfg, new_state.cfg, "milter")) { const char* value = cfg_getstr(new_state.cfg, "milter"); if (NONEMPTY_STRING(value)) { new_state.milter = endpoint_create(value); if (new_state.milter == NULL) goto fail; } } else { /* Same logic applies as with socketmap */ new_state.milter = state->milter; state->milter = NULL; milter_rollback = true; } /* If we reached this point, the new configuration is valid, so we commit */ finalize_state(state); new_state.connection_limit = cfg_getint(new_state.cfg, "connection-limit"); *state = new_state; return true; fail: /* If a configuration error occurs and the daemon was configured already, we want to keep the old functional configuration. */ if (cfg_getbool(state->cfg, "syslog")) log_enable_syslog(); else log_disable_syslog(); log_set_verbosity(cfg_getbool(state->cfg, "debug") ? LogDebug : LogInfo); if (socketmap_rollback) { state->socketmap = new_state.socketmap; new_state.socketmap = NULL; } if (milter_rollback) { state->milter = new_state.milter; new_state.milter = NULL; } finalize_state(&new_state); return false; } static size_t setup_poll(postsrsd_t* state, struct pollfd* fds, int* fd_types, size_t max_fds) { size_t num_fds = 0; size_t remaining_fds = max_fds; size_t num_socketmap_fds = endpoint_prepare_poll(state->socketmap, fds + num_fds, remaining_fds); for (size_t i = num_fds; i < num_fds + num_socketmap_fds; ++i) fd_types[i] = FD_SOCKETMAP; remaining_fds -= num_socketmap_fds; num_fds += num_socketmap_fds; size_t num_milter_fds = endpoint_prepare_poll(state->milter, fds + num_fds, remaining_fds); for (size_t i = num_fds; i < num_fds + num_milter_fds; ++i) fd_types[i] = FD_MILTER; remaining_fds -= num_milter_fds; num_fds += num_milter_fds; size_t num_watch_fds = file_watch_prepare_poll( state->file_watch, fds + num_fds, remaining_fds); for (size_t i = num_fds; i < num_fds + num_watch_fds; ++i) fd_types[i] = FD_WATCH; remaining_fds -= num_watch_fds; num_fds += num_watch_fds; for (size_t i = num_fds; i < max_fds; ++i) fd_types[i] = FD_UNUSED; return num_fds; } static void collect_finished_workers(pid_set_t* P) { pid_t pid; int child_status; do { pid = waitpid(0, &child_status, WNOHANG); if (pid > 0) { if (WIFEXITED(child_status) && WEXITSTATUS(child_status) != EXIT_SUCCESS) { log_warn("child process %d exited with status code %d", (int)pid, WEXITSTATUS(child_status)); } if (WIFSIGNALED(child_status)) { switch (WTERMSIG(child_status)) { #if defined(WITH_SECCOMP) && defined(SIGSYS) case SIGSYS: log_error( "child process %d was terminated due to a sandbox " "violation", (int)pid); break; #endif default: log_warn("child process %d was terminated by signal %d", (int)pid, WTERMSIG(child_status)); break; } } pid_set_remove(P, pid); } } while (pid > 0); } #ifndef POSTSRSD_FUZZING int main(int argc, char** argv) { postsrsd_t state; init_state(&state); FILE* pf = NULL; pid_set_t* P = NULL; int exit_code = EXIT_FAILURE; # ifdef HAVE_CLOSE_RANGE close_range(3, ~0U, 0); # else for (int fd = 3; fd < 1024; ++fd) close(fd); # endif if (!setup_state(argc, argv, &state)) goto shutdown; sandbox = sandbox_init(); if (sandbox == NULL) log_warn("seccomp sandbox is unavailable"); const char* pid_file = cfg_getstr(state.cfg, "pid-file"); if (NONEMPTY_STRING(pid_file)) { pf = fopen(pid_file, "w"); if (pf == NULL) { log_error("cannot open %s for writing", pid_file); goto shutdown; } } P = pid_set_create(); if (P == NULL) goto shutdown; if (!daemonize(&state)) goto shutdown; if (pf != NULL) { fprintf(pf, "%d", (int)getpid()); fclose(pf); pf = NULL; } exit_code = EXIT_SUCCESS; signal_set_handler(SIGHUP, on_reload_requested); signal_set_handler_once(SIGTERM, on_shutdown_requested); signal_set_handler_once(SIGINT, on_shutdown_requested); signal_ignore(SIGPIPE); sd_notify_support = sd_notify("READY=1\nMAINPID=%d", (int)getpid()); struct pollfd fds[16]; int fd_types[sizeof(fds) / sizeof(struct pollfd)]; size_t num_fds = setup_poll(&state, fds, fd_types, sizeof(fds) / sizeof(struct pollfd)); for (;;) { if (shutdown_requested) { log_info("Signal %d received. shutting down.", (int)shutdown_requested); shutdown_requested = 0; goto shutdown; } if (files_changed_unsafe && time(NULL) - last_file_watch_event >= 1) { files_changed = true; } if (reload_requested || files_changed) { if (sd_notify_support) { struct timespec tp; clock_gettime(CLOCK_MONOTONIC, &tp); sd_notify("RELOADING=1\nMONOTONIC_USEC=%ld", (long)(1000000l * tp.tv_sec + tp.tv_nsec / 1000l)); } if (reload_requested) { log_info("Signal %d received, reloading configuration.", (int)reload_requested); reload_requested = 0; } if (files_changed) { files_changed = false; if (files_changed_unsafe) { log_warn( "trying to reload configuration after unsafe update"); files_changed_unsafe = false; } else log_info("file change detected, reloading configuration."); } if (setup_state(argc, argv, &state)) { pid_set_kill(P, SIGHUP); num_fds = setup_poll(&state, fds, fd_types, sizeof(fds) / sizeof(struct pollfd)); } else { log_error("configuration error, rolling back changes"); } if (sd_notify_support) sd_notify("READY=1"); } if (poll(fds, num_fds, 1000) < 0) { if (errno == EINTR) continue; log_perror(errno, "poll"); goto shutdown; } for (unsigned i = 0; i < num_fds; ++i) { if (fds[i].revents) { if (fds[i].fd == file_watch_poll_fd(state.file_watch)) { file_watch_process_events(state.file_watch); } else { int conn = accept(fds[i].fd, NULL, NULL); if (conn < 0) { log_perror(errno, "accept"); continue; } if (pid_set_size(P) >= state.connection_limit) { log_warn("connection limit reached"); close(conn); continue; } pid_t pid = fork(); if (pid == 0) { endpoint_release(state.socketmap); state.socketmap = NULL; endpoint_release(state.milter); state.milter = NULL; switch (fd_types[i]) { case FD_SOCKETMAP: handle_socketmap_client(&state, conn); break; case FD_MILTER: handle_milter_client(&state, conn); break; default: log_error("socket dispatch error"); exit(EXIT_FAILURE); } finalize_state(&state); sandbox_release(sandbox); pid_set_destroy(P); exit(EXIT_SUCCESS); } if (pid > 0) { pid_set_add(P, pid); } else { log_perror(errno, "fork"); } close(conn); } } } collect_finished_workers(P); } shutdown: if (pf != NULL) fclose(pf); finalize_state(&state); sandbox_release(sandbox); collect_finished_workers(P); pid_set_kill(P, SIGTERM); pid_set_wait(P); pid_set_destroy(P); return exit_code; } #endif roehling-postsrsd-24c678b/src/main.h000066400000000000000000000024771526152470400174450ustar00rootroot00000000000000/* PostSRSd - Sender Rewriting Scheme daemon for Postfix * Copyright 2012-2026 Timo Röhling * SPDX-License-Identifier: GPL-3.0-only * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef MAIN_H #define MAIN_H #include "config.h" #include "endpoint.h" #include "srs2.h" #include "util.h" struct postsrsd { cfg_t* cfg; srs_t* srs; endpoint_t* socketmap; endpoint_t* milter; char* srs_domain; domain_set_t* local_domains; file_watch_t* file_watch; int target_uid, target_gid; size_t connection_limit; }; typedef struct postsrsd postsrsd_t; void init_state(postsrsd_t* state); void finalize_state(postsrsd_t* state); void handle_socketmap_client(postsrsd_t* state, int conn); void handle_milter_client(postsrsd_t* state, int conn); #endif roehling-postsrsd-24c678b/src/milter.c000066400000000000000000000205161526152470400200020ustar00rootroot00000000000000/* PostSRSd - Sender Rewriting Scheme daemon for Postfix * Copyright 2012-2026 Timo Röhling * SPDX-License-Identifier: GPL-3.0-only * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include "milter.h" #include "util.h" #include #include #include #include #include #include #if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ # define BE32(x) (x) #else # ifdef __GNUC__ # define BE32(x) __builtin_bswap32(x) # else # include # define BE32(x) bswap_32(x) # endif #endif struct milter_packet { uint32_t length; char code; char payload[]; } ATTRIBUTE(packed); typedef struct milter_packet milter_packet_t; static_assert(sizeof(struct milter_packet) == 5, "unexpected size of struct milter_packet"); size_t milter_receive(int fd, void* buffer, size_t size, size_t* truncated) { static char discardpile[512]; uint32_t len; ssize_t r; if (truncated != NULL) *truncated = 0; if (!read_all(fd, &len, 4)) return 0; len = BE32(len); size_t read_len = len < size ? len : size; if (!read_all(fd, buffer, read_len)) return 0; len -= read_len; while (len > 0) { size_t discard_len = len < sizeof(discardpile) ? len : sizeof(discardpile); r = read(fd, discardpile, discard_len); if (r <= 0) break; len -= r; if (truncated != NULL) *truncated += r; } return read_len; } bool milter_send_bytes(int fd, char action, const void* data, size_t length) { if (data == NULL && length != 0) return false; if (length > 0xfffffffe) return false; milter_packet_t packet; struct iovec iov[2]; packet.length = BE32(1 + length); packet.code = action; iov[0].iov_base = (void*)&packet; iov[0].iov_len = sizeof(milter_packet_t); if (length != 0) { iov[1].iov_base = (void*)data; iov[1].iov_len = length; } return writev_all(fd, iov, length != 0 ? 2 : 1); } bool milter_send_str(int fd, char action, const char* value) { return milter_send_bytes(fd, action, value, value != NULL ? strlen(value) + 1 : 0); } bool milter_send(int fd, char action) { milter_packet_t packet; packet.length = BE32(1); packet.code = action; return write(fd, &packet, sizeof(milter_packet_t)) == sizeof(milter_packet_t); } bool milter_continue(int fd) { return milter_send(fd, MILTER_DO_CONTINUE); } bool milter_tempfail(int fd) { return milter_send(fd, MILTER_DO_TEMPFAIL); } bool milter_accept(int fd) { return milter_send(fd, MILTER_DO_ACCEPT); } bool milter_reject(int fd) { return milter_send(fd, MILTER_DO_REJECT); } bool milter_send_str_list(int fd, char action, list_t* L) { size_t numv = list_size(L); if (numv == 0) return milter_send(fd, action); if (numv > 127) return false; struct iovec iov[numv + 1]; size_t j = 1, length = 0; for (size_t i = 0; i < numv; ++i) { const char* item = list_get(L, i); if (item != NULL) { size_t item_length = strlen(item) + 1; if (length > 0xfffffffe - item_length) return false; length += item_length; iov[j].iov_base = (void*)item; iov[j].iov_len = item_length; ++j; } } if (length > 0xfffffffe) return false; milter_packet_t packet; packet.length = BE32(1 + length); packet.code = action; iov[0].iov_base = (void*)&packet; iov[0].iov_len = sizeof(milter_packet_t); return writev_all(fd, iov, j); } void milter_parse_str_list(list_t* L, const char* data, size_t length) { while (length > 0) { size_t next_item_length = strnlen(data, length); list_append(L, strndup(data, next_item_length)); if (next_item_length == length) break; data += next_item_length + 1; length -= next_item_length + 1; } } bool milter_handle_optneg(int fd, const void* input, size_t length) { struct { uint32_t version, actions, protocol; } ATTRIBUTE(packed) buf; static_assert(sizeof(buf) == 12, "internal struct has unexpected alignment"); if (length < sizeof(buf)) return false; memcpy(&buf, input, sizeof(buf)); buf.version = BE32(buf.version); buf.actions = BE32(buf.actions); buf.protocol = BE32(buf.protocol); if (buf.version > 6) { buf.version = 6; } buf.actions &= (MILTER_FL_CHGFROM | MILTER_FL_ADDRCPT | MILTER_FL_DELRCPT); if ((buf.actions & MILTER_FL_CHGFROM) == 0) { log_error("MTA does not support CHGFROM milter action"); milter_send(fd, MILTER_DO_TEMPFAIL); return false; } if ((buf.actions & MILTER_FL_ADDRCPT) == 0) { log_error("MTA does not support ADDRCPT milter action"); milter_send(fd, MILTER_DO_TEMPFAIL); return false; } if ((buf.actions & MILTER_FL_DELRCPT) == 0) { log_error("MTA does not support DELRCPT milter action"); milter_send(fd, MILTER_DO_TEMPFAIL); return false; } buf.protocol &= (MILTER_FL_NOCONNECT | MILTER_FL_NOHELO | MILTER_FL_NOHDRS | MILTER_FL_NOBODY | MILTER_FL_NODATA | MILTER_FL_NOUNKNOWN | MILTER_FL_NOEOH); buf.version = BE32(buf.version); buf.actions = BE32(buf.actions); buf.protocol = BE32(buf.protocol); return milter_send_bytes(fd, MILTER_CMD_OPTNEG, &buf, sizeof(buf)); } char* milter_parse_macros(const char* name, const char* buffer, size_t length) { while (length > 0) { const char* key = buffer; size_t keylen = strnlen(key, length); if (keylen == length || keylen + 1 == length) return NULL; length -= keylen + 1; buffer += keylen + 1; if (strcmp(key, name) == 0) return strndup(buffer, length); size_t vallen = strnlen(buffer, length); if (vallen == length || vallen + 1 == length) return NULL; length -= vallen + 1; buffer += vallen + 1; } return NULL; } char* milter_parse_address_n(const char* addr, size_t length) { if (addr == NULL) return NULL; if (length < 2) return strndup(addr, length); const char* lbrak = memchr(addr, '<', length); if (lbrak == NULL) { if (memchr(addr, '>', length) == NULL) return strndup(addr, length); return NULL; } const char* rbrak = memchr(lbrak, '>', length - (lbrak - addr)); if (rbrak == NULL) return NULL; return strndup(lbrak + 1, rbrak - lbrak - 1); } char* milter_parse_address(const char* addr) { if (addr == NULL) return NULL; const char* lbrak = strchr(addr, '<'); if (lbrak == NULL) { if (strchr(addr, '>') == NULL) return strdup(addr); return NULL; } const char* rbrak = strchr(lbrak, '>'); if (rbrak == NULL) return NULL; return strndup(lbrak + 1, rbrak - lbrak - 1); } char* milter_parse_address_buf(const char* addr, void* buffer, size_t size) { if (addr == NULL) return NULL; const char* lbrak = strchr(addr, '<'); if (lbrak == NULL) { if (strchr(addr, '>') == NULL) { size_t len = strlen(addr); if (len < size) { char* eob = stpcpy(buffer, addr); *eob = 0; return buffer; } } return NULL; } const char* rbrak = strchr(lbrak, '>'); if (rbrak == NULL) return NULL; size_t len = rbrak - lbrak - 1; if (len >= size) return NULL; char* eob = stpncpy(buffer, lbrak + 1, len); *eob = 0; return buffer; } roehling-postsrsd-24c678b/src/milter.h000066400000000000000000000066041526152470400200110ustar00rootroot00000000000000/* PostSRSd - Sender Rewriting Scheme daemon for Postfix * Copyright 2012-2026 Timo Röhling * SPDX-License-Identifier: GPL-3.0-only * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef MILTER_H #define MILTER_H #include "util.h" #include #include #include #define MILTER_FL_ADDHDRS 0x000001 #define MILTER_FL_CHGBODY 0x000002 #define MILTER_FL_ADDRCPT 0x000004 #define MILTER_FL_DELRCPT 0x000008 #define MILTER_FL_CHGHDRS 0x000010 #define MILTER_FL_QUARANTINE 0x000020 #define MILTER_FL_CHGFROM 0x000040 #define MILTER_FL_ADDRCPT_PAR 0x000080 #define MILTER_FL_SETSYMLIST 0x000100 #define MILTER_FL_NOCONNECT 0x000001 #define MILTER_FL_NOHELO 0x000002 #define MILTER_FL_NOMAIL 0x000004 #define MILTER_FL_NORCPT 0x000008 #define MILTER_FL_NOBODY 0x000010 #define MILTER_FL_NOHDRS 0x000020 #define MILTER_FL_NOEOH 0x000040 #define MILTER_FL_NOUNKNOWN 0x000100 #define MILTER_FL_NODATA 0x000200 #define MILTER_CMD_ABORT 'A' #define MILTER_CMD_BODY 'B' #define MILTER_CMD_CONNECT 'C' #define MILTER_CMD_MACRO 'D' #define MILTER_CMD_EOM 'E' #define MILTER_CMD_HELO 'H' #define MILTER_CMD_HEADER 'L' #define MILTER_CMD_MAIL 'M' #define MILTER_CMD_EOH 'N' #define MILTER_CMD_OPTNEG 'O' #define MILTER_CMD_QUIT 'Q' #define MILTER_CMD_RCPT 'R' #define MILTER_CMD_DATA 'T' #define MILTER_CMD_UNKNOWN 'U' #define MILTER_DO_ACCEPT 'a' #define MILTER_DO_CONTINUE 'c' #define MILTER_DO_DISCARD 'd' #define MILTER_DO_REJECT 'r' #define MILTER_DO_TEMPFAIL 't' #define MILTER_DO_REPLYCODE 'y' #define MILTER_DO_SKIP 's' #define MILTER_DO_ADDRCPT '+' #define MILTER_DO_DELRCPT '-' #define MILTER_DO_ADDRCPT_PAR '2' #define MILTER_DO_REPLBODY 'b' #define MILTER_DO_CHGFROM 'e' #define MILTER_DO_ADDHEADER 'h' #define MILTER_DO_INSHEADER 'h' #define MILTER_DO_CHGHEADER 'm' #define MILTER_DO_QUARANTINE 'q' #define MILTER_DO_PROGRESS 'p' #define MILTER_DO_SETSYMLIST 'l' #define MILTER_PAYLOAD_SIZE 512 size_t milter_receive(int fd, void* buffer, size_t size, size_t* truncated); bool milter_send(int fd, char action); bool milter_send_bytes(int fd, char action, const void* data, size_t length); bool milter_send_str(int fd, char action, const char* value); bool milter_send_str_list(int fd, char action, list_t* L); bool milter_tempfail(int fd); bool milter_continue(int fd); bool milter_accept(int fd); bool milter_reject(int fd); bool milter_handle_optneg(int fd, const void* input, size_t length); void milter_parse_str_list(list_t* L, const char* data, size_t length); char* milter_parse_address(const char* addr); char* milter_parse_address_buf(const char* addr, void* buffer, size_t size); char* milter_parse_address_n(const char* addr, size_t length); char* milter_parse_macros(const char* name, const char* data, size_t length); #endif roehling-postsrsd-24c678b/src/netstring.c000066400000000000000000000077041526152470400205270ustar00rootroot00000000000000/* PostSRSd - Sender Rewriting Scheme daemon for Postfix * Copyright 2012-2026 Timo Röhling * SPDX-License-Identifier: GPL-3.0-only * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include "netstring.h" #include "util.h" #include #include #include char* netstring_encode(const char* data, size_t length, char* buffer, size_t bufsize, size_t* encoded_length) { if (data == NULL) return NULL; int i = snprintf(buffer, bufsize, "%zu:", length); if (i <= 0 || (size_t)i >= bufsize || length >= bufsize - i) return NULL; memcpy(&buffer[i], data, length); buffer[length + i] = ','; if (encoded_length != NULL) *encoded_length = length + i + 1; return buffer; } char* netstring_decode(const char* netstring, size_t encoded_length, char* buffer, size_t bufsize, size_t* decoded_length) { if (netstring == NULL) return NULL; size_t i = 0; size_t length = 0; while (i < encoded_length && netstring[i] != ':') { if (netstring[i] < '0' || netstring[i] > '9') return NULL; length = 10 * length + (netstring[i] - '0'); if (length > 100000 || length >= bufsize) return NULL; ++i; } if (i == 0 || length >= bufsize || length + i + 1 >= encoded_length) return NULL; if (netstring[i] != ':' || netstring[length + i + 1] != ',') return NULL; memcpy(buffer, &netstring[i + 1], length); if (decoded_length != NULL) *decoded_length = length; buffer[length] = 0; return buffer; } char* netstring_read(int fd, char* buffer, size_t bufsize, size_t* decoded_length) { size_t length = 0; char ch; if (decoded_length != NULL) *decoded_length = 0; for (;;) { if (!read_all(fd, &ch, 1)) return NULL; if (ch == ':') break; if (ch < '0' || ch > '9') { if (decoded_length != NULL) *decoded_length = SIZE_MAX; return NULL; } length = 10 * length + (ch - '0'); if (length > 100000 || length >= bufsize) { if (decoded_length != NULL) *decoded_length = SIZE_MAX; return NULL; } } if (!read_all(fd, buffer, length)) return NULL; if (!read_all(fd, &ch, 1)) return NULL; if (ch != ',') { if (decoded_length != NULL) *decoded_length = SIZE_MAX; return NULL; } buffer[length] = 0; if (decoded_length != NULL) *decoded_length = length; return buffer; } int netstring_write(int fd, const char* data, size_t length) { static const char suffix[] = {','}; char prefix[16]; struct iovec iov[3]; if (length != 0) { if (data == NULL) return -1; size_t n = snprintf(prefix, sizeof(prefix), "%zu:", length); if (n >= sizeof(prefix)) return -1; iov[0].iov_base = (void*)prefix; iov[0].iov_len = n; iov[1].iov_base = (void*)data; iov[1].iov_len = length; iov[2].iov_base = (void*)suffix; iov[2].iov_len = 1; return writev_all(fd, iov, 3) ? (int)(length + n + 1) : -1; } else { iov[0].iov_base = (void*)"0:,"; iov[0].iov_len = 3; return writev_all(fd, iov, 1) ? 3 : -1; } } roehling-postsrsd-24c678b/src/netstring.h000066400000000000000000000024031526152470400205230ustar00rootroot00000000000000/* PostSRSd - Sender Rewriting Scheme daemon for Postfix * Copyright 2012-2026 Timo Röhling * SPDX-License-Identifier: GPL-3.0-only * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef NETSTRING_H #define NETSTRING_H #include #include char* netstring_encode(const char* data, size_t length, char* buffer, size_t bufsize, size_t* encoded_length); char* netstring_decode(const char* netstring, size_t encoded_length, char* buffer, size_t bufsize, size_t* decoded_length); char* netstring_read(int fd, char* buffer, size_t bufsize, size_t* decoded_length); int netstring_write(int fd, const char* data, size_t length); #endif roehling-postsrsd-24c678b/src/postsrsd_build_config.h.in000066400000000000000000000030601526152470400235000ustar00rootroot00000000000000/* PostSRSd - Sender Rewriting Scheme daemon for Postfix * Copyright 2012-2023 Timo Röhling * SPDX-License-Identifier: GPL-3.0-only * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef POSTSRSD_BUILD_CONFIG_H #define POSTSRSD_BUILD_CONFIG_H /* clang-format off */ #define POSTSRSD_VERSION "@PROJECT_VERSION@@EXTRA_VERSION@" #define SIZEOF_UNSIGNED_LONG @SIZEOF_UNSIGNED_LONG@ #define DEFAULT_CONFIG_FILE "@POSTSRSD_CONFIGDIR@/@PROJECT_NAME@.conf" #define DEFAULT_SECRETS_FILE "@POSTSRSD_CONFIGDIR@/@PROJECT_NAME@.secret" #define DEFAULT_CHROOT_DIR "@POSTSRSD_CHROOTDIR@" #define DEFAULT_POSTSRSD_USER "@POSTSRSD_USER@" /* clang-format on */ #cmakedefine WITH_REDIS 1 #cmakedefine WITH_SQLITE 1 #cmakedefine WITH_SECCOMP 1 #cmakedefine TESTS_WITH_REDIS 1 #cmakedefine HAVE_BIG_ENDIAN 1 #cmakedefine HAVE_CHROOT 1 #cmakedefine HAVE_CLOSE_RANGE 1 #cmakedefine HAVE_SETGROUPS 1 #cmakedefine HAVE_SYS_INOTIFY_H 1 #cmakedefine HAVE_SYS_TIME_H 1 #cmakedefine HAVE_TIME_H 1 #endif roehling-postsrsd-24c678b/src/sha1.c000066400000000000000000000321421526152470400173400ustar00rootroot00000000000000/* Copyright Gisle Ass, Peter C. Gutmann, Bruce Schneier * Copyright 2004 Shevek * Copyright 2012-2026 Timo Röhling * SPDX-License-Identifier: BSD-3-Clause * * This file has been copied from libsrs2. Original copyright follows: */ /* NIST Secure Hash Algorithm */ /* Borrowed from SHA1.xs by Gisle Ass */ /* heavily modified by Uwe Hollerbach */ /* from Peter C. Gutmann's implementation as found in */ /* Applied Cryptography by Bruce Schneier */ /* Further modifications to include the "UNRAVEL" stuff, below */ /* HMAC functions by Shevek for inclusion in * libsrs2, under GPL-2 or BSD license. Combine this lot in any way * you think will stand up in court. I hope my intent is clear. */ /* This code is in the public domain */ #include "sha1.h" #include "postsrsd_build_config.h" #include /* memcpy, strcpy, memset */ #ifdef SIZEOF_UNSIGNED_LONG # if SIZEOF_UNSIGNED_LONG < 4 # error "SHA1 requires an unsigned long of at least 32 bits" # endif #endif #if SIZEOF_UNSIGNED_LONG == 4 # ifdef HAVE_BIG_ENDIAN # define BYTEORDER 0x4321 # else # define BYTEORDER 0x1234 # endif #elif SIZEOF_UNSIGNED_LONG == 8 # ifdef HAVE_BIG_ENDIAN # define BYTEORDER 0x87654321 # else # define BYTEORDER 0x12345678 # endif #else # error "SHA1 requires an unsigned long of either 4 or 8 bytes" #endif /* UNRAVEL should be fastest & biggest */ /* UNROLL_LOOPS should be just as big, but slightly slower */ /* both undefined should be smallest and slowest */ #define SHA_VERSION 1 #define UNRAVEL /* #define UNROLL_LOOPS */ /* SHA f()-functions */ #define f1(x, y, z) ((x & y) | (~x & z)) #define f2(x, y, z) (x ^ y ^ z) #define f3(x, y, z) ((x & y) | (x & z) | (y & z)) #define f4(x, y, z) (x ^ y ^ z) /* SHA constants */ #define CONST1 0x5a827999L #define CONST2 0x6ed9eba1L #define CONST3 0x8f1bbcdcL #define CONST4 0xca62c1d6L /* truncate to 32 bits -- should be a null op on 32-bit machines */ #define T32(x) ((x) & 0xffffffffL) /* 32-bit rotate */ #define R32(x, n) T32(((x << n) | (x >> (32 - n)))) /* the generic case, for when the overall rotation is not unraveled */ #define FG(n) \ T = T32(R32(A, 5) + f##n(B, C, D) + E + *WP++ + CONST##n); \ E = D; \ D = C; \ C = R32(B, 30); \ B = A; \ A = T /* specific cases, for when the overall rotation is unraveled */ #define FA(n) \ T = T32(R32(A, 5) + f##n(B, C, D) + E + *WP++ + CONST##n); \ B = R32(B, 30) #define FB(n) \ E = T32(R32(T, 5) + f##n(A, B, C) + D + *WP++ + CONST##n); \ A = R32(A, 30) #define FC(n) \ D = T32(R32(E, 5) + f##n(T, A, B) + C + *WP++ + CONST##n); \ T = R32(T, 30) #define FD(n) \ C = T32(R32(D, 5) + f##n(E, T, A) + B + *WP++ + CONST##n); \ E = R32(E, 30) #define FE(n) \ B = T32(R32(C, 5) + f##n(D, E, T) + A + *WP++ + CONST##n); \ D = R32(D, 30) #define FT(n) \ A = T32(R32(B, 5) + f##n(C, D, E) + T + *WP++ + CONST##n); \ C = R32(C, 30) static void sha_transform(SHA_INFO* sha_info) { int i; sha_byte* dp; ULONG T, A, B, C, D, E, W[80], *WP; dp = sha_info->data; /* the following makes sure that at least one code block below is traversed or an error is reported, without the necessity for nested preprocessor if/else/endif blocks, which are a great pain in the nether regions of the anatomy... */ #undef SWAP_DONE #if BYTEORDER == 0x1234 # define SWAP_DONE /* assert(sizeof(ULONG) == 4); */ for (i = 0; i < 16; ++i) { T = *((ULONG*)dp); dp += 4; W[i] = ((T << 24) & 0xff000000) | ((T << 8) & 0x00ff0000) | ((T >> 8) & 0x0000ff00) | ((T >> 24) & 0x000000ff); } #endif #if BYTEORDER == 0x4321 # define SWAP_DONE /* assert(sizeof(ULONG) == 4); */ for (i = 0; i < 16; ++i) { T = *((ULONG*)dp); dp += 4; W[i] = T32(T); } #endif #if BYTEORDER == 0x12345678 # define SWAP_DONE /* assert(sizeof(ULONG) == 8); */ for (i = 0; i < 16; i += 2) { T = *((ULONG*)dp); dp += 8; W[i] = ((T << 24) & 0xff000000) | ((T << 8) & 0x00ff0000) | ((T >> 8) & 0x0000ff00) | ((T >> 24) & 0x000000ff); T >>= 32; W[i + 1] = ((T << 24) & 0xff000000) | ((T << 8) & 0x00ff0000) | ((T >> 8) & 0x0000ff00) | ((T >> 24) & 0x000000ff); } #endif #if BYTEORDER == 0x87654321 # define SWAP_DONE /* assert(sizeof(ULONG) == 8); */ for (i = 0; i < 16; i += 2) { T = *((ULONG*)dp); dp += 8; W[i] = T32(T >> 32); W[i + 1] = T32(T); } #endif #ifndef SWAP_DONE # error Unknown byte order -- you need to add code here #endif for (i = 16; i < 80; ++i) { W[i] = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]; #if (SHA_VERSION == 1) W[i] = R32(W[i], 1); #endif } A = sha_info->digest[0]; B = sha_info->digest[1]; C = sha_info->digest[2]; D = sha_info->digest[3]; E = sha_info->digest[4]; WP = W; #ifdef UNRAVEL /* clang-format off */ FA(1); FB(1); FC(1); FD(1); FE(1); FT(1); FA(1); FB(1); FC(1); FD(1); FE(1); FT(1); FA(1); FB(1); FC(1); FD(1); FE(1); FT(1); FA(1); FB(1); FC(2); FD(2); FE(2); FT(2); FA(2); FB(2); FC(2); FD(2); FE(2); FT(2); FA(2); FB(2); FC(2); FD(2); FE(2); FT(2); FA(2); FB(2); FC(2); FD(2); FE(3); FT(3); FA(3); FB(3); FC(3); FD(3); FE(3); FT(3); FA(3); FB(3); FC(3); FD(3); FE(3); FT(3); FA(3); FB(3); FC(3); FD(3); FE(3); FT(3); FA(4); FB(4); FC(4); FD(4); FE(4); FT(4); FA(4); FB(4); FC(4); FD(4); FE(4); FT(4); FA(4); FB(4); FC(4); FD(4); FE(4); FT(4); FA(4); FB(4); /* clang-format on */ sha_info->digest[0] = T32(sha_info->digest[0] + E); sha_info->digest[1] = T32(sha_info->digest[1] + T); sha_info->digest[2] = T32(sha_info->digest[2] + A); sha_info->digest[3] = T32(sha_info->digest[3] + B); sha_info->digest[4] = T32(sha_info->digest[4] + C); #else # ifdef UNROLL_LOOPS /* clang-format off */ FG(1); FG(1); FG(1); FG(1); FG(1); FG(1); FG(1); FG(1); FG(1); FG(1); FG(1); FG(1); FG(1); FG(1); FG(1); FG(1); FG(1); FG(1); FG(1); FG(1); FG(2); FG(2); FG(2); FG(2); FG(2); FG(2); FG(2); FG(2); FG(2); FG(2); FG(2); FG(2); FG(2); FG(2); FG(2); FG(2); FG(2); FG(2); FG(2); FG(2); FG(3); FG(3); FG(3); FG(3); FG(3); FG(3); FG(3); FG(3); FG(3); FG(3); FG(3); FG(3); FG(3); FG(3); FG(3); FG(3); FG(3); FG(3); FG(3); FG(3); FG(4); FG(4); FG(4); FG(4); FG(4); FG(4); FG(4); FG(4); FG(4); FG(4); FG(4); FG(4); FG(4); FG(4); FG(4); FG(4); FG(4); FG(4); FG(4); FG(4); /* clang-format on */ # else for (i = 0; i < 20; ++i) { FG(1); } for (i = 20; i < 40; ++i) { FG(2); } for (i = 40; i < 60; ++i) { FG(3); } for (i = 60; i < 80; ++i) { FG(4); } # endif sha_info->digest[0] = T32(sha_info->digest[0] + A); sha_info->digest[1] = T32(sha_info->digest[1] + B); sha_info->digest[2] = T32(sha_info->digest[2] + C); sha_info->digest[3] = T32(sha_info->digest[3] + D); sha_info->digest[4] = T32(sha_info->digest[4] + E); #endif } /* initialize the SHA digest */ static void sha_init(SHA_INFO* sha_info) { sha_info->digest[0] = 0x67452301L; sha_info->digest[1] = 0xefcdab89L; sha_info->digest[2] = 0x98badcfeL; sha_info->digest[3] = 0x10325476L; sha_info->digest[4] = 0xc3d2e1f0L; sha_info->count_lo = 0L; sha_info->count_hi = 0L; sha_info->local = 0; } /* update the SHA digest */ static void sha_update(SHA_INFO* sha_info, const sha_byte* buffer, int count) { int i; ULONG clo; clo = T32(sha_info->count_lo + ((ULONG)count << 3)); if (clo < sha_info->count_lo) { ++sha_info->count_hi; } sha_info->count_lo = clo; sha_info->count_hi += (ULONG)count >> 29; if (sha_info->local) { i = SHA_BLOCKSIZE - sha_info->local; if (i > count) { i = count; } memcpy(((sha_byte*)sha_info->data) + sha_info->local, buffer, i); count -= i; buffer += i; sha_info->local += i; if (sha_info->local == SHA_BLOCKSIZE) { sha_transform(sha_info); } else { return; } } while (count >= SHA_BLOCKSIZE) { memcpy(sha_info->data, buffer, SHA_BLOCKSIZE); buffer += SHA_BLOCKSIZE; count -= SHA_BLOCKSIZE; sha_transform(sha_info); } memcpy(sha_info->data, buffer, count); sha_info->local = count; } static void sha_transform_and_copy(unsigned char digest[20], SHA_INFO* sha_info) { sha_transform(sha_info); digest[0] = (unsigned char)((sha_info->digest[0] >> 24) & 0xff); digest[1] = (unsigned char)((sha_info->digest[0] >> 16) & 0xff); digest[2] = (unsigned char)((sha_info->digest[0] >> 8) & 0xff); digest[3] = (unsigned char)((sha_info->digest[0]) & 0xff); digest[4] = (unsigned char)((sha_info->digest[1] >> 24) & 0xff); digest[5] = (unsigned char)((sha_info->digest[1] >> 16) & 0xff); digest[6] = (unsigned char)((sha_info->digest[1] >> 8) & 0xff); digest[7] = (unsigned char)((sha_info->digest[1]) & 0xff); digest[8] = (unsigned char)((sha_info->digest[2] >> 24) & 0xff); digest[9] = (unsigned char)((sha_info->digest[2] >> 16) & 0xff); digest[10] = (unsigned char)((sha_info->digest[2] >> 8) & 0xff); digest[11] = (unsigned char)((sha_info->digest[2]) & 0xff); digest[12] = (unsigned char)((sha_info->digest[3] >> 24) & 0xff); digest[13] = (unsigned char)((sha_info->digest[3] >> 16) & 0xff); digest[14] = (unsigned char)((sha_info->digest[3] >> 8) & 0xff); digest[15] = (unsigned char)((sha_info->digest[3]) & 0xff); digest[16] = (unsigned char)((sha_info->digest[4] >> 24) & 0xff); digest[17] = (unsigned char)((sha_info->digest[4] >> 16) & 0xff); digest[18] = (unsigned char)((sha_info->digest[4] >> 8) & 0xff); digest[19] = (unsigned char)((sha_info->digest[4]) & 0xff); } /* finish computing the SHA digest */ static void sha_final(unsigned char digest[20], SHA_INFO* sha_info) { int count; ULONG lo_bit_count, hi_bit_count; lo_bit_count = sha_info->count_lo; hi_bit_count = sha_info->count_hi; count = (int)((lo_bit_count >> 3) & 0x3f); ((sha_byte*)sha_info->data)[count++] = 0x80; if (count > SHA_BLOCKSIZE - 8) { memset(((sha_byte*)sha_info->data) + count, 0, SHA_BLOCKSIZE - count); sha_transform(sha_info); memset((sha_byte*)sha_info->data, 0, SHA_BLOCKSIZE - 8); } else { memset(((sha_byte*)sha_info->data) + count, 0, SHA_BLOCKSIZE - 8 - count); } sha_info->data[56] = (hi_bit_count >> 24) & 0xff; sha_info->data[57] = (hi_bit_count >> 16) & 0xff; sha_info->data[58] = (hi_bit_count >> 8) & 0xff; sha_info->data[59] = (hi_bit_count >> 0) & 0xff; sha_info->data[60] = (lo_bit_count >> 24) & 0xff; sha_info->data[61] = (lo_bit_count >> 16) & 0xff; sha_info->data[62] = (lo_bit_count >> 8) & 0xff; sha_info->data[63] = (lo_bit_count >> 0) & 0xff; sha_transform_and_copy(digest, sha_info); } /********************************************************************/ /* SHA_INFO ctx; unsigned char *data; STRLEN len; unsigned char digeststr[20]; sha_init(&ctx); for (i = 0; i < items; i++) { data = (unsigned char *)(SvPVbyte(ST(i), len)); sha_update(&ctx, data, len); } sha_final(digeststr, &ctx); */ void sha_digest(char* out, const char* data, unsigned len) { SHA_INFO ctx; sha_init(&ctx); sha_update(&ctx, (const sha_byte*)data, len); sha_final((sha_byte*)out, &ctx); } void srs_hmac_init(srs_hmac_ctx_t* ctx, char* secret, unsigned len) { char sbuf[SHA_BLOCKSIZE]; unsigned i; if (len > SHA_BLOCKSIZE) { sha_digest(sbuf, secret, len); secret = sbuf; len = SHA_DIGESTSIZE; } memset(ctx->ipad, 0x36, SHA_BLOCKSIZE); memset(ctx->opad, 0x5c, SHA_BLOCKSIZE); for (i = 0; i < len; i++) { ctx->ipad[i] ^= secret[i]; ctx->opad[i] ^= secret[i]; } memset(sbuf, 0, SHA_BLOCKSIZE); sha_init(&ctx->sctx); sha_update(&ctx->sctx, (sha_byte*)ctx->ipad, SHA_BLOCKSIZE); } void srs_hmac_update(srs_hmac_ctx_t* ctx, char* data, unsigned len) { sha_update(&ctx->sctx, (sha_byte*)data, len); } void srs_hmac_fini(srs_hmac_ctx_t* ctx, char* out) { sha_byte buf[SHA_DIGESTSIZE + 1]; sha_final(buf, &ctx->sctx); sha_init(&ctx->sctx); sha_update(&ctx->sctx, (sha_byte*)ctx->opad, SHA_BLOCKSIZE); sha_update(&ctx->sctx, buf, SHA_DIGESTSIZE); sha_final((sha_byte*)out, &ctx->sctx); } roehling-postsrsd-24c678b/src/sha1.h000066400000000000000000000021131526152470400173400ustar00rootroot00000000000000/* PostSRSd - Sender Rewriting Scheme daemon for Postfix * Copyright Gisle Ass, Peter C. Gutmann, Bruce Schneier * Copyright 2004 Shevek * Copyright 2012-2026 Timo Röhling * SPDX-License-Identifier: BSD-3-Clause */ #ifndef SHA1_H #define SHA1_H typedef unsigned long ULONG; /* 32-or-more-bit quantity */ typedef unsigned char sha_byte; #define SHA_BLOCKSIZE 64 #define SHA_DIGESTSIZE 20 typedef struct { ULONG digest[5]; /* message digest */ ULONG count_lo, count_hi; /* 64-bit bit count */ sha_byte data[SHA_BLOCKSIZE]; /* SHA data buffer */ int local; /* unprocessed amount in data */ } SHA_INFO; typedef struct _srs_hmac_ctx_t { SHA_INFO sctx; char ipad[SHA_BLOCKSIZE + 1]; char opad[SHA_BLOCKSIZE + 1]; } srs_hmac_ctx_t; void sha_digest(char* out, const char* data, unsigned len); void srs_hmac_init(srs_hmac_ctx_t* ctx, char* secret, unsigned len); void srs_hmac_update(srs_hmac_ctx_t* ctx, char* data, unsigned len); void srs_hmac_fini(srs_hmac_ctx_t* ctx, char* out); #endif roehling-postsrsd-24c678b/src/srs.c000066400000000000000000000131521526152470400173130ustar00rootroot00000000000000/* PostSRSd - Sender Rewriting Scheme daemon for Postfix * Copyright 2012-2026 Timo Röhling * SPDX-License-Identifier: GPL-3.0-only * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include "srs.h" #include "sha1.h" #include "util.h" #include #include char* postsrsd_forward(const char* addr, const char* domain, srs_t* srs, database_t* db, domain_set_t* local_domains, bool* error, const char** info, const char* queue_id) { if (addr == NULL) return NULL; const char* at = strchr(addr, '@'); if (error != NULL) *error = false; if (info != NULL) *info = NULL; if (queue_id == NULL) queue_id = "NULL"; if (at == NULL) { if (info != NULL) *info = "No domain."; log_debug("%s: <%s> not rewritten: no domain", queue_id, addr); return NULL; } if (domain == NULL) { log_error("%s: <%s> not rewritten: no SRS domain configured", queue_id, addr); if (error != NULL) *error = true; if (info != NULL) *info = "Configuration error."; return NULL; } const char* input_domain = at + 1; if (domain_set_contains(local_domains, input_domain)) { if (info != NULL) *info = "Need not rewrite local domain."; log_debug("%s: <%s> not rewritten: local domain", queue_id, addr); return NULL; } char db_alias_buf[35]; char* db_alias; const char* sender = addr; if (db != NULL && !SRS_IS_SRS_ADDRESS(addr)) { char digest[20]; sha_digest(digest, addr, strlen(addr)); db_alias = b32h_encode(digest, 20, db_alias_buf, sizeof(db_alias_buf)); if (db_alias == NULL) { log_warn("<%s> not rewritten: aliasing error", addr); if (error != NULL) *error = true; if (info != NULL) *info = "Aliasing error."; return NULL; } strcat(db_alias, "@1"); if (!database_write(db, db_alias, addr, srs->maxage * 86400)) { log_warn("%s: <%s> not rewritten: database error", queue_id, addr); if (error != NULL) *error = true; if (info != NULL) *info = "Database error."; return NULL; } sender = db_alias; } char* output = NULL; int result = srs_forward_alloc(srs, &output, sender, domain); if (result == SRS_SUCCESS) { log_info("%s: <%s> forwarded as <%s>", queue_id, addr, output); return output; } free(output); if (error != NULL) *error = result != SRS_ENOTREWRITTEN; if (info != NULL) *info = srs_strerror(result); log_info("%s: <%s> not rewritten: %s", queue_id, addr, srs_strerror(result)); return NULL; } char* postsrsd_reverse(const char* addr, srs_t* srs, database_t* db, bool* error, const char** info, const char* queue_id) { char buffer[513]; if (addr == NULL) return NULL; if (error != NULL) *error = false; if (info != NULL) *info = NULL; if (queue_id == NULL) queue_id = "NOQUEUE"; int result = srs_reverse(srs, buffer, sizeof(buffer), addr); if (result != SRS_SUCCESS) { if (info != NULL) *info = srs_strerror(result); if (result != SRS_ENOTSRSADDRESS) { log_info("%s: <%s> not reversed: %s", queue_id, addr, srs_strerror(result)); } else { log_debug("%s: <%s> not reversed: %s", queue_id, addr, srs_strerror(result)); } return NULL; } const char* at = strchr(buffer, '@'); if (at == NULL) { log_info("%s: <%s> not reversed: internal error", queue_id, addr); if (error != NULL) *error = true; if (info != NULL) *info = "Internal error."; return NULL; } if (strcmp(at, "@1") == 0) { if (db != NULL) { unsigned char* p = (unsigned char*)buffer; while (*p) { *p = toupper(*p); ++p; } char* sender = database_read(db, buffer); if (sender == NULL) { log_info("%s: <%s> not reversed: unknown alias", queue_id, addr); if (info != NULL) *info = "Unknown alias."; return NULL; } log_info("%s: <%s> reversed to <%s>", queue_id, addr, sender); return sender; } else { log_warn("%s: <%s> not reversed: no database for alias", queue_id, addr); if (error != NULL) *error = true; if (info != NULL) *info = "No database for alias."; return NULL; } } log_info("%s: <%s> reversed to <%s>", queue_id, addr, buffer); return strdup(buffer); } roehling-postsrsd-24c678b/src/srs.h000066400000000000000000000023161526152470400173200ustar00rootroot00000000000000/* PostSRSd - Sender Rewriting Scheme daemon for Postfix * Copyright 2012-2026 Timo Röhling * SPDX-License-Identifier: GPL-3.0-only * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef SRS_H #define SRS_H #include "database.h" #include "srs2.h" #include "util.h" #include char* postsrsd_forward(const char* addr, const char* domain, srs_t* srs, database_t* db, domain_set_t* local_domains, bool* error, const char** info, const char* queue_id); char* postsrsd_reverse(const char* addr, srs_t* srs, database_t* db, bool* error, const char** info, const char* queue_id); #endif roehling-postsrsd-24c678b/src/srs2.c000066400000000000000000000446611526152470400174060ustar00rootroot00000000000000/* Copyright 2004 Shevek * Copyright 2012-2026 Timo Röhling * SPDX-License-Identifier: BSD-3-Clause * * This file has been copied from libsrs2. Original copyright follows: */ /* Copyright (c) 2004 Shevek (srs@anarres.org) * All rights reserved. * * This file is a part of libsrs2 from http://www.libsrs2.org/ * * Redistribution and use in source and binary forms, with or without * modification, under the terms of either the GNU General Public * License version 2 or the BSD license, at the discretion of the * user. Copies of these licenses have been included in the libsrs2 * distribution. See the the file called LICENSE for more * information. */ #include "srs2.h" #include "sha1.h" #include #include /* Use this */ #define STRINGP(s) ((s != NULL) && (*(s) != '\0')) static const char* srs_separators = "=-+"; static srs_malloc_t srs_f_malloc = malloc; static srs_realloc_t srs_f_realloc = realloc; static srs_free_t srs_f_free = free; int base64_equivalent(const char* s1, const char* s2, size_t length) { static const int TRANSLATION_START = 43; static const char TRANSLATION[] = { '-', 0, '-', 0, '_', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 0, 0, 0, 0, 0, 0, 0, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 0, 0, 0, 0, '_', 0, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'}; int comp = 0; for (size_t i = 0; i < length; ++i) { int h1 = (int)s1[i] - TRANSLATION_START; int h2 = (int)s2[i] - TRANSLATION_START; int v1 = (h1 >= 0 && (size_t)h1 < sizeof(TRANSLATION)) ? TRANSLATION[h1] : 0; int v2 = (h2 >= 0 && (size_t)h2 < sizeof(TRANSLATION)) ? TRANSLATION[h2] : 0; comp |= (v1 ^ v2) | (v1 == 0) | (v2 == 0); } return comp == 0; } int srs_set_malloc(srs_malloc_t m, srs_realloc_t r, srs_free_t f) { srs_f_malloc = m; srs_f_realloc = r; srs_f_free = f; return SRS_SUCCESS; } const char* srs_strerror(int code) { switch (code) { /* Simple errors */ case SRS_SUCCESS: return "Success"; case SRS_ENOTSRSADDRESS: return "Not an SRS address."; /* Config errors */ case SRS_ENOSECRETS: return "No secrets in SRS configuration."; case SRS_ESEPARATORINVALID: return "Invalid separator suggested."; /* Input errors */ case SRS_ENOSENDERATSIGN: return "No at sign in sender address"; case SRS_EBUFTOOSMALL: return "Buffer too small."; /* Syntax errors */ case SRS_ENOSRS0HOST: return "No host in SRS0 address."; case SRS_ENOSRS0USER: return "No user in SRS0 address."; case SRS_ENOSRS0HASH: return "No hash in SRS0 address."; case SRS_ENOSRS0STAMP: return "No timestamp in SRS0 address."; case SRS_ENOSRS1HOST: return "No host in SRS1 address."; case SRS_ENOSRS1USER: return "No user in SRS1 address."; case SRS_ENOSRS1HASH: return "No hash in SRS1 address."; case SRS_EBADTIMESTAMPCHAR: return "Bad base32 character in timestamp."; case SRS_EHASHTOOSHORT: return "Hash too short in SRS address."; /* SRS errors */ case SRS_ETIMESTAMPOUTOFDATE: return "Time stamp out of date."; case SRS_EHASHINVALID: return "Hash invalid in SRS address."; default: return "Unknown error in SRS library."; } } srs_t* srs_new() { srs_t* srs = (srs_t*)srs_f_malloc(sizeof(srs_t)); srs_init(srs); return srs; } void srs_init(srs_t* srs) { memset(srs, 0, sizeof(srs_t)); srs->secrets = NULL; srs->numsecrets = 0; srs->separator = '='; srs->maxage = 21; srs->hashlength = 4; srs->hashmin = srs->hashlength; srs->alwaysrewrite = FALSE; srs->faketime = 0; } void srs_free(srs_t* srs) { int i; for (i = 0; i < srs->numsecrets; i++) { memset(srs->secrets[i], 0, strlen(srs->secrets[i])); srs_f_free(srs->secrets[i]); srs->secrets[i] = 0; } srs_f_free(srs->secrets); srs_f_free(srs); } int srs_add_secret(srs_t* srs, const char* secret) { int newlen = (srs->numsecrets + 1) * sizeof(char*); srs->secrets = (char**)srs_f_realloc(srs->secrets, newlen); srs->secrets[srs->numsecrets++] = strdup(secret); return SRS_SUCCESS; } const char* srs_get_secret(srs_t* srs, int idx) { if (idx < srs->numsecrets) return srs->secrets[idx]; return NULL; } #define SRS_PARAM_DEFINE(n, t) \ int srs_set_##n(srs_t* srs, t value) \ { \ srs->n = value; \ return SRS_SUCCESS; \ } \ t srs_get_##n(srs_t* srs) \ { \ return srs->n; \ } int srs_set_separator(srs_t* srs, char value) { if (strchr(srs_separators, value) == NULL) return SRS_ESEPARATORINVALID; srs->separator = value; return SRS_SUCCESS; } char srs_get_separator(srs_t* srs) { return srs->separator; } SRS_PARAM_DEFINE(maxage, int) /* XXX Check hashlength >= hashmin */ SRS_PARAM_DEFINE(hashlength, int) SRS_PARAM_DEFINE(hashmin, int) SRS_PARAM_DEFINE(alwaysrewrite, srs_bool) SRS_PARAM_DEFINE(noforward, srs_bool) SRS_PARAM_DEFINE(noreverse, srs_bool) /* Don't mess with these unless you know what you're doing well * enough to rewrite the timestamp functions. These are based on * a 2 character timestamp. Changing these in the wild is probably * a bad idea. */ #define SRS_TIME_PRECISION (60 * 60 * 24) /* One day */ #define SRS_TIME_BASEBITS 5 /* 2^5 = 32 = strlen(CHARS) */ /* This had better be a real variable since we do arithmethic * with it. */ const char* SRS_TIME_BASECHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; #define SRS_TIME_SIZE 2 #define SRS_TIME_SLOTS (1 << (SRS_TIME_BASEBITS << (SRS_TIME_SIZE - 1))) int srs_timestamp_create(srs_t* srs __attribute__((unused)), char* buf, time_t now) { now = now / SRS_TIME_PRECISION; buf[1] = SRS_TIME_BASECHARS[now & ((1 << SRS_TIME_BASEBITS) - 1)]; now = now >> SRS_TIME_BASEBITS; buf[0] = SRS_TIME_BASECHARS[now & ((1 << SRS_TIME_BASEBITS) - 1)]; buf[2] = '\0'; return SRS_SUCCESS; } int srs_timestamp_check(srs_t* srs, const char* stamp) { const char* sp; const char* bp; int off; time_t now; time_t then; if (strlen(stamp) != 2) return SRS_ETIMESTAMPOUTOFDATE; /* We had better go around this loop exactly twice! */ then = 0; for (sp = stamp; *sp; sp++) { bp = strchr(SRS_TIME_BASECHARS, toupper((unsigned char)*sp)); if (bp == NULL) return SRS_EBADTIMESTAMPCHAR; off = bp - SRS_TIME_BASECHARS; then = (then << SRS_TIME_BASEBITS) | off; } if (srs->faketime) now = srs->faketime; else time(&now); now = (now / SRS_TIME_PRECISION) % SRS_TIME_SLOTS; while (now < then) now = now + SRS_TIME_SLOTS; if (now <= then + srs->maxage) return SRS_SUCCESS; return SRS_ETIMESTAMPOUTOFDATE; } const char* SRS_HASH_BASECHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz" "0123456789-_"; static void srs_hash_create_v(srs_t* srs, int idx, char* buf, int nargs, va_list ap) { #ifdef USE_OPENSSL HMAC_CTX ctx; int srshashlen; char srshash[EVP_MAX_MD_SIZE + 1]; #else srs_hmac_ctx_t ctx; char srshash[SHA_DIGESTSIZE + 1]; #endif char* secret; char* data; int len; unsigned char* hp; char* bp; int i; int j; secret = srs->secrets[idx]; #ifdef USE_OPENSSL HMAC_CTX_init(&ctx); HMAC_Init(&ctx, secret, strlen(secret), EVP_sha1()); #else srs_hmac_init(&ctx, secret, strlen(secret)); #endif for (i = 0; i < nargs; i++) { data = va_arg(ap, char*); len = strlen(data); char lcdata[len + 1]; for (j = 0; j < len; j++) { if (isupper((unsigned char)data[j])) lcdata[j] = tolower((unsigned char)data[j]); else lcdata[j] = data[j]; } #ifdef USE_OPENSSL HMAC_Update(&ctx, lcdata, len); #else srs_hmac_update(&ctx, lcdata, len); #endif } #ifdef USE_OPENSSL HMAC_Final(&ctx, srshash, &srshashlen); HMAC_CTX_cleanup(&ctx); srshash[EVP_MAX_MD_SIZE] = '\0'; #else srs_hmac_fini(&ctx, srshash); srshash[SHA_DIGESTSIZE] = '\0'; #endif /* A little base64 encoding. Just a little. */ hp = (unsigned char*)srshash; bp = buf; for (i = 0; i < srs->hashlength; i++) { switch (i & 0x03) { default: /* NOTREACHED */ case 0: j = (*hp >> 2); break; case 1: j = ((*hp & 0x03) << 4) | ((*(hp + 1) & 0xF0) >> 4); hp++; break; case 2: j = ((*hp & 0x0F) << 2) | ((*(hp + 1) & 0xC0) >> 6); hp++; break; case 3: j = (*hp++ & 0x3F); break; } *bp++ = SRS_HASH_BASECHARS[j]; } *bp = '\0'; buf[srs->hashlength] = '\0'; } int srs_hash_create(srs_t* srs, char* buf, int nargs, ...) { va_list ap; if (srs->numsecrets == 0) return SRS_ENOSECRETS; if (srs->secrets == NULL) return SRS_ENOSECRETS; if (srs->secrets[0] == NULL) return SRS_ENOSECRETS; va_start(ap, nargs); srs_hash_create_v(srs, 0, buf, nargs, ap); va_end(ap); return SRS_SUCCESS; } int srs_hash_check(srs_t* srs, char* hash, int nargs, ...) { va_list ap; int len; int i; len = strlen(hash); if (len < srs->hashmin) return SRS_EHASHTOOSHORT; if (len > srs->hashlength) { len = srs->hashlength; } char srshash[srs->hashlength + 1]; for (i = 0; i < srs->numsecrets; i++) { va_start(ap, nargs); srs_hash_create_v(srs, i, srshash, nargs, ap); va_end(ap); if (base64_equivalent(hash, srshash, len)) return SRS_SUCCESS; } return SRS_EHASHINVALID; } int srs_compile_shortcut(srs_t* srs, char* buf, int buflen, char* sendhost, char* senduser, const char* aliashost) { char srsstamp[SRS_TIME_SIZE + 1]; int len; int ret; /* This never happens if we get called from guarded() */ if ((strncasecmp(senduser, SRS0TAG, 4) == 0) && (strchr(srs_separators, senduser[4]) != NULL)) { sendhost = senduser + 5; if (*sendhost == '\0') return SRS_ENOSRS0HOST; senduser = strchr(sendhost, SRSSEP); if ((senduser == NULL) || (*senduser == '\0')) return SRS_ENOSRS0USER; } len = strlen(SRS0TAG) + 1 + srs->hashlength + 1 + SRS_TIME_SIZE + 1 + strlen(sendhost) + 1 + strlen(senduser) + 1 + strlen(aliashost); if (len >= buflen) return SRS_EBUFTOOSMALL; ret = srs_timestamp_create(srs, srsstamp, srs->faketime ? srs->faketime : time(NULL)); if (ret != SRS_SUCCESS) return ret; char srshash[srs->hashlength + 1]; ret = srs_hash_create(srs, srshash, 3, srsstamp, sendhost, senduser); if (ret != SRS_SUCCESS) return ret; sprintf(buf, SRS0TAG "%c%s%c%s%c%s%c%s@%s", srs->separator, srshash, SRSSEP, srsstamp, SRSSEP, sendhost, SRSSEP, senduser, aliashost); return SRS_SUCCESS; } int srs_compile_guarded(srs_t* srs, char* buf, int buflen, char* sendhost, char* senduser, const char* aliashost) { char* srshost; char* srsuser; int len; int ret; if ((strncasecmp(senduser, SRS1TAG, 4) == 0) && (strchr(srs_separators, senduser[4]) != NULL)) { /* Used as a temporary convenience var */ char* tmp = senduser + 5; if (*tmp == '\0') return SRS_ENOSRS1HASH; /* Used as a temporary convenience var */ srshost = strchr(tmp, SRSSEP); if (!STRINGP(srshost)) return SRS_ENOSRS1HOST; *srshost++ = '\0'; srsuser = strchr(srshost, SRSSEP); if (!STRINGP(srsuser)) return SRS_ENOSRS1USER; *srsuser++ = '\0'; char srshash[srs->hashlength + 1]; ret = srs_hash_create(srs, srshash, 2, srshost, srsuser); if (ret != SRS_SUCCESS) return ret; len = strlen(SRS1TAG) + 1 + srs->hashlength + 1 + strlen(srshost) + 1 + strlen(srsuser) + 1 + strlen(aliashost); if (len >= buflen) return SRS_EBUFTOOSMALL; sprintf(buf, SRS1TAG "%c%s%c%s%c%s@%s", srs->separator, srshash, SRSSEP, srshost, SRSSEP, srsuser, aliashost); return SRS_SUCCESS; } else if ((strncasecmp(senduser, SRS0TAG, 4) == 0) && (strchr(srs_separators, senduser[4]) != NULL)) { srsuser = senduser + 4; srshost = sendhost; char srshash[srs->hashlength + 1]; ret = srs_hash_create(srs, srshash, 2, srshost, srsuser); if (ret != SRS_SUCCESS) return ret; len = strlen(SRS1TAG) + 1 + srs->hashlength + 1 + strlen(srshost) + 1 + strlen(srsuser) + 1 + strlen(aliashost); if (len >= buflen) return SRS_EBUFTOOSMALL; sprintf(buf, SRS1TAG "%c%s%c%s%c%s@%s", srs->separator, srshash, SRSSEP, srshost, SRSSEP, srsuser, aliashost); } else { return srs_compile_shortcut(srs, buf, buflen, sendhost, senduser, aliashost); } return SRS_SUCCESS; } int srs_parse_shortcut(srs_t* srs, char* buf, unsigned buflen, char* senduser) { char* srshash; char* srsstamp; char* srshost; char* srsuser; int ret; if (strncasecmp(senduser, SRS0TAG, 4) == 0) { srshash = senduser + 5; if (!STRINGP(srshash)) return SRS_ENOSRS0HASH; srsstamp = strchr(srshash, SRSSEP); if (!STRINGP(srsstamp)) return SRS_ENOSRS0STAMP; *srsstamp++ = '\0'; srshost = strchr(srsstamp, SRSSEP); if (!STRINGP(srshost)) return SRS_ENOSRS0HOST; *srshost++ = '\0'; srsuser = strchr(srshost, SRSSEP); if (!STRINGP(srsuser)) return SRS_ENOSRS0USER; *srsuser++ = '\0'; ret = srs_timestamp_check(srs, srsstamp); if (ret != SRS_SUCCESS) return ret; ret = srs_hash_check(srs, srshash, 3, srsstamp, srshost, srsuser); if (ret != SRS_SUCCESS) return ret; snprintf(buf, buflen, "%s@%s", srsuser, srshost); return SRS_SUCCESS; } return SRS_ENOTSRSADDRESS; } int srs_parse_guarded(srs_t* srs, char* buf, int buflen, char* senduser) { char* srshash; char* srshost; char* srsuser; int ret; if (strncasecmp(senduser, SRS1TAG, 4) == 0) { srshash = senduser + 5; if (!STRINGP(srshash)) return SRS_ENOSRS1HASH; srshost = strchr(srshash, SRSSEP); if (!STRINGP(srshost)) return SRS_ENOSRS1HOST; *srshost++ = '\0'; srsuser = strchr(srshost, SRSSEP); if (!STRINGP(srsuser)) return SRS_ENOSRS1USER; *srsuser++ = '\0'; ret = srs_hash_check(srs, srshash, 2, srshost, srsuser); if (ret != SRS_SUCCESS) return ret; sprintf(buf, SRS0TAG "%s@%s", srsuser, srshost); return SRS_SUCCESS; } else { return srs_parse_shortcut(srs, buf, buflen, senduser); } } int srs_forward(srs_t* srs, char* buf, unsigned buflen, const char* sender, const char* alias) { char* sendhost; const char* at; unsigned len; if (srs->noforward) return SRS_ENOTREWRITTEN; /* This is allowed to be a plain domain */ while ((at = strchr(alias, '@')) != NULL) alias = at + 1; at = strchr(sender, '@'); if (at == NULL) return SRS_ENOSENDERATSIGN; len = strlen(sender); if (!srs->alwaysrewrite) { if (strcasecmp(at + 1, alias) == 0) { if (strlen(sender) >= buflen) return SRS_EBUFTOOSMALL; strcpy(buf, sender); return SRS_SUCCESS; } } char senduser[len + 1]; strcpy(senduser, sender); char* tmp = (senduser + (at - sender)); sendhost = tmp + 1; *tmp = '\0'; return srs_compile_guarded(srs, buf, buflen, sendhost, senduser, alias); } int srs_forward_alloc(srs_t* srs, char** sptr, const char* sender, const char* alias) { char* buf; int slen; int alen; int len; int ret; if (srs->noforward) return SRS_ENOTREWRITTEN; slen = strlen(sender); alen = strlen(alias); /* strlen(SRSxTAG) + strlen("====+@") < 64 */ len = slen + alen + srs->hashlength + SRS_TIME_SIZE + 64; buf = (char*)srs_f_malloc(len); ret = srs_forward(srs, buf, len, sender, alias); if (ret == SRS_SUCCESS) *sptr = buf; else srs_f_free(buf); return ret; } int srs_reverse(srs_t* srs, char* buf, unsigned buflen, const char* sender) { char* tmp; unsigned len = strlen(sender); if (len < 5) return SRS_ENOTSRSADDRESS; if (!SRS_IS_SRS_ADDRESS(sender)) return SRS_ENOTSRSADDRESS; if (srs->noreverse) return SRS_ENOTREWRITTEN; if (len >= buflen) return SRS_EBUFTOOSMALL; char senduser[len + 1]; strcpy(senduser, sender); /* We don't really care about the host for reversal. */ tmp = strchr(senduser, '@'); if (tmp != NULL) *tmp = '\0'; return srs_parse_guarded(srs, buf, buflen, senduser); } int srs_reverse_alloc(srs_t* srs, char** sptr, const char* sender) { char* buf; int len; int ret; *sptr = NULL; if (!SRS_IS_SRS_ADDRESS(sender)) return SRS_ENOTSRSADDRESS; if (srs->noreverse) return SRS_ENOTREWRITTEN; len = strlen(sender) + 1; buf = (char*)srs_f_malloc(len); ret = srs_reverse(srs, buf, len, sender); if (ret == SRS_SUCCESS) *sptr = buf; else srs_f_free(buf); return ret; } roehling-postsrsd-24c678b/src/srs2.h000066400000000000000000000115401526152470400174010ustar00rootroot00000000000000/* Copyright 2004 Shevek * Copyright 2012-2026 Timo Röhling * SPDX-License-Identifier: BSD-3-Clause * * This file has been copied from libsrs2. Original copyright follows: */ /* Copyright (c) 2004 Shevek (srs@anarres.org) * All rights reserved. * * This file is a part of libsrs2 from http://www.libsrs2.org/ * * Redistribution and use in source and binary forms, with or without * modification, under the terms of either the GNU General Public * License version 2 or the BSD license, at the discretion of the * user. Copies of these licenses have been included in the libsrs2 * distribution. See the the file called LICENSE for more * information. */ #ifndef __SRS2_H__ #define __SRS2_H__ #include #include #include #include #include #include #ifdef HAVE_SYS_TIME_H # include #endif #ifdef HAVE_TIME_H # include #endif #ifndef __BEGIN_DECLS # define __BEGIN_DECLS # define __END_DECLS #endif __BEGIN_DECLS #define SRS_VERSION_MAJOR 1 #define SRS_VERSION_MINOR 0 #define SRS_VERSION_PATCHLEVEL 14 #define SRS_VERSION_FROM(m, n, p) (((m) << 16) + ((n) << 8) + (p)) #define SRS_VERSION \ SRS_VERSION_FROM(SRS_VERSION_MAJOR, SRS_VERSION_MINOR, \ SRS_VERSION_PATCHLEVEL) /* This is ugly, but reasonably safe. */ #undef TRUE #define TRUE 1 #undef FALSE #define FALSE 0 #define SRSSEP '=' #define SRS0TAG "SRS0" #define SRS1TAG "SRS1" /* Error codes */ #define SRS_ERRTYPE_MASK 0xF000 #define SRS_ERRTYPE_NONE 0x0000 #define SRS_ERRTYPE_CONFIG 0x1000 #define SRS_ERRTYPE_INPUT 0x2000 #define SRS_ERRTYPE_SYNTAX 0x4000 #define SRS_ERRTYPE_SRS 0x8000 #define SRS_SUCCESS (0) #define SRS_ENOTSRSADDRESS (1) #define SRS_ENOTREWRITTEN (2) #define SRS_ENOSECRETS (SRS_ERRTYPE_CONFIG | 1) #define SRS_ESEPARATORINVALID (SRS_ERRTYPE_CONFIG | 2) #define SRS_ENOSENDERATSIGN (SRS_ERRTYPE_INPUT | 1) #define SRS_EBUFTOOSMALL (SRS_ERRTYPE_INPUT | 2) #define SRS_ENOSRS0HOST (SRS_ERRTYPE_SYNTAX | 1) #define SRS_ENOSRS0USER (SRS_ERRTYPE_SYNTAX | 2) #define SRS_ENOSRS0HASH (SRS_ERRTYPE_SYNTAX | 3) #define SRS_ENOSRS0STAMP (SRS_ERRTYPE_SYNTAX | 4) #define SRS_ENOSRS1HOST (SRS_ERRTYPE_SYNTAX | 5) #define SRS_ENOSRS1USER (SRS_ERRTYPE_SYNTAX | 6) #define SRS_ENOSRS1HASH (SRS_ERRTYPE_SYNTAX | 7) #define SRS_EBADTIMESTAMPCHAR (SRS_ERRTYPE_SYNTAX | 8) #define SRS_EHASHTOOSHORT (SRS_ERRTYPE_SYNTAX | 9) #define SRS_ETIMESTAMPOUTOFDATE (SRS_ERRTYPE_SRS | 1) #define SRS_EHASHINVALID (SRS_ERRTYPE_SRS | 2) #define SRS_ERROR_TYPE(x) ((x) & SRS_ERRTYPE_MASK) /* SRS implementation */ #define SRS_IS_SRS_ADDRESS(x) \ ((strncasecmp((x), "SRS", 3) == 0) && (strchr("01", (x)[3]) != NULL) \ && (strchr("-+=", (x)[4]) != NULL)) typedef void* (*srs_malloc_t)(size_t); typedef void* (*srs_realloc_t)(void*, size_t); typedef void (*srs_free_t)(void*); typedef int srs_bool; typedef struct _srs_t { /* Rewriting parameters */ char** secrets; int numsecrets; char separator; /* Security parameters */ int maxage; /* Maximum allowed age in seconds */ int hashlength; int hashmin; /* Behaviour parameters */ srs_bool alwaysrewrite; /* Rewrite even into same domain? */ srs_bool noforward; /* Never perform forwards rewriting */ srs_bool noreverse; /* Never perform reverse rewriting */ char** neverrewrite; /* A list of non-rewritten domains */ time_t faketime; /* Added for testing purposes */ } srs_t; /* Interface */ int srs_set_malloc(srs_malloc_t m, srs_realloc_t r, srs_free_t f); srs_t* srs_new(); void srs_init(srs_t* srs); void srs_free(srs_t* srs); int srs_forward(srs_t* srs, char* buf, unsigned buflen, const char* sender, const char* alias); int srs_forward_alloc(srs_t* srs, char** sptr, const char* sender, const char* alias); int srs_reverse(srs_t* srs, char* buf, unsigned buflen, const char* sender); int srs_reverse_alloc(srs_t* srs, char** sptr, const char* sender); const char* srs_strerror(int code); int srs_add_secret(srs_t* srs, const char* secret); const char* srs_get_secret(srs_t* srs, int idx); /* You probably shouldn't call these. */ int srs_timestamp_create(srs_t* srs, char* buf, time_t now); int srs_timestamp_check(srs_t* srs, const char* stamp); #define SRS_PARAM_DECLARE(n, t) \ int srs_set_##n(srs_t* srs, t value); \ t srs_get_##n(srs_t* srs); SRS_PARAM_DECLARE(alwaysrewrite, srs_bool) SRS_PARAM_DECLARE(separator, char) SRS_PARAM_DECLARE(maxage, int) SRS_PARAM_DECLARE(hashlength, int) SRS_PARAM_DECLARE(hashmin, int) SRS_PARAM_DECLARE(noforward, srs_bool) SRS_PARAM_DECLARE(noreverse, srs_bool) __END_DECLS #endif roehling-postsrsd-24c678b/src/util.c000066400000000000000000001015221526152470400174600ustar00rootroot00000000000000/* PostSRSd - Sender Rewriting Scheme daemon for Postfix * Copyright 2012-2026 Timo Röhling * SPDX-License-Identifier: GPL-3.0-only * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include "util.h" #include "postsrsd_build_config.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #ifdef HAVE_SYS_INOTIFY_H # include #endif #ifdef HAVE_SYS_TIME_H # include #endif #ifdef HAVE_TIME_H # include #endif #ifdef SOCK_CLOEXEC # define HAVE_SOCK_CLOEXEC 1 #else # define SOCK_CLOEXEC 0 #endif #ifdef WITH_SECCOMP # include # include #endif bool string_equal(const void* s1, const void* s2) { return strcmp(s1, s2) == 0; } void string_set(char** var, char* value) { free(*var); *var = value; } char* b32h_encode(const char* data, size_t length, char* buffer, size_t bufsize) { static const char B32H_CHARS[32] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V'}; if (data == NULL) return NULL; if ((bufsize <= 8 * ((length + 4) / 5))) return NULL; char* out = buffer; size_t i, j; for (i = 0, j = 0; i + 4 < length; i += 5, j += 8) { uint64_t tmp = (((uint64_t)data[i] & 0xFF) << 32) | (((uint64_t)data[i + 1] & 0xFF) << 24) | (((uint64_t)data[i + 2] & 0xFF) << 16) | (((uint64_t)data[i + 3] & 0xFF) << 8) | ((uint64_t)data[i + 4] & 0xFF); out[j + 7] = B32H_CHARS[tmp & 0x1F]; tmp >>= 5; out[j + 6] = B32H_CHARS[tmp & 0x1F]; tmp >>= 5; out[j + 5] = B32H_CHARS[tmp & 0x1F]; tmp >>= 5; out[j + 4] = B32H_CHARS[tmp & 0x1F]; tmp >>= 5; out[j + 3] = B32H_CHARS[tmp & 0x1F]; tmp >>= 5; out[j + 2] = B32H_CHARS[tmp & 0x1F]; tmp >>= 5; out[j + 1] = B32H_CHARS[tmp & 0x1F]; tmp >>= 5; out[j] = B32H_CHARS[tmp & 0x1F]; } if (i < length) { uint64_t tmp = (uint64_t)data[i]; tmp <<= 8; if (i + 1 < length) tmp |= (uint64_t)data[i + 1]; tmp <<= 8; if (i + 2 < length) tmp |= (uint64_t)data[i + 2]; tmp <<= 8; if (i + 3 < length) tmp |= (uint64_t)data[i + 3]; out[j + 7] = '='; tmp <<= 3; out[j + 6] = i + 3 < length ? B32H_CHARS[tmp & 0x1F] : '='; tmp >>= 5; out[j + 5] = i + 3 < length ? B32H_CHARS[tmp & 0x1F] : '='; tmp >>= 5; out[j + 4] = i + 2 < length ? B32H_CHARS[tmp & 0x1F] : '='; tmp >>= 5; out[j + 3] = i + 1 < length ? B32H_CHARS[tmp & 0x1F] : '='; tmp >>= 5; out[j + 2] = i + 1 < length ? B32H_CHARS[tmp & 0x1F] : '='; tmp >>= 5; out[j + 1] = B32H_CHARS[tmp & 0x1F]; tmp >>= 5; out[j] = B32H_CHARS[tmp & 0x1F]; j += 8; } out[j] = 0; return buffer; } bool file_exists(const char* filename) { struct stat st; if (stat(filename, &st) < 0) return false; return S_ISREG(st.st_mode); } bool directory_exists(const char* dirname) { struct stat st; if (stat(dirname, &st) < 0) return false; return S_ISDIR(st.st_mode); } int lock_acquire(const char* path) { MAYBE_UNUSED(path); #if defined(LOCK_EX) && defined(LOCK_NB) size_t len = strlen(path); if (len > SIZE_MAX - 6) return -1; char* lock_path = malloc(len + 6); /* ".lock" + "\0" */ if (lock_path == NULL) return -1; stpcpy(stpcpy(lock_path, path), ".lock"); int fd = open(lock_path, O_RDONLY | O_CREAT | O_CLOEXEC, 0600); free(lock_path); if (fd < 0) return -1; if (flock(fd, LOCK_EX | LOCK_NB) < 0) { close(fd); return -1; } return fd; #else return 0; #endif } void lock_release(const char* path, int fd) { MAYBE_UNUSED(path); MAYBE_UNUSED(fd); #if defined(LOCK_EX) && defined(LOCK_NB) size_t len = strlen(path); if (len <= SIZE_MAX - 6) { char* lock_path = malloc(len + 6); /* ".lock" + "\0" */ if (lock_path != NULL) { stpcpy(stpcpy(lock_path, path), ".lock"); unlink(lock_path); free(lock_path); } } close(fd); #endif } bool read_all(int fd, void* buffer, size_t size) { size_t total = 0; while (total < size) { ssize_t r = read(fd, buffer + total, size - total); if (r <= 0) return false; total += r; } return true; } bool writev_all(int fd, struct iovec* iov, size_t numv) { size_t i = 0; do { ssize_t written = writev(fd, iov + i, numv - i); if (written <= 0) return false; while (written > 0) { if ((size_t)written >= iov[i].iov_len) { written -= iov[i].iov_len; ++i; } else { iov[i].iov_len -= written; iov[i].iov_base += written; written = 0; } } } while (i < numv); return true; } /* The domain set is implemented as a common prefix tree */ struct domain_set { /* Membership; is the string up to this point a set member? */ bool m; /* Child node for subdomain components, effectively (".") */ struct domain_set* s; /* Child nodes for letters A-Z, numbers 0-9, and dash ("-"), in that order */ struct domain_set* c[37]; }; #define DOMAIN_SET_ADD 1 #define DOMAIN_SET_PARENTS_MATCH 2 domain_set_t* domain_set_create() { domain_set_t* D = malloc(sizeof(struct domain_set)); for (unsigned i = 0; i < sizeof(D->c) / sizeof(D->c[0]); ++i) D->c[i] = NULL; D->s = NULL; D->m = false; return D; } void domain_set_destroy(domain_set_t* D) { for (unsigned i = 0; i < sizeof(D->c) / sizeof(D->c[0]); ++i) if (D->c[i]) domain_set_destroy(D->c[i]); if (D->s != NULL) domain_set_destroy(D->s); free(D); } static bool walk_domain_set(domain_set_t* D, char* domain, int flags) { char* dot = strrchr(domain, '.'); char* subdomain = domain; if (dot != NULL) { subdomain = dot + 1; *dot = 0; } int ch; while ((ch = *subdomain++)) { if (ch >= 'A' && ch <= 'Z') ch -= 'A'; else if (ch >= 'a' && ch <= 'z') ch -= 'a'; else if (ch >= '0' && ch <= '9') ch = ch - '0' + 26; else if (ch == '-') ch = 36; else return 0; if (D->c[ch] == NULL) { if (!(flags & DOMAIN_SET_ADD)) return 0; D->c[ch] = domain_set_create(); } D = D->c[ch]; } if (dot != NULL) { if (D->s == NULL) { if (!(flags & DOMAIN_SET_ADD)) return 0; D->s = domain_set_create(); } if (D->s->m && (flags & DOMAIN_SET_PARENTS_MATCH)) return 1; return walk_domain_set(D->s, domain, flags); } bool result = D->m; if (flags == DOMAIN_SET_ADD) D->m = true; return result; } bool domain_set_add(domain_set_t* D, const char* domain) { if (D == NULL) return false; char buffer[512]; char* end = stpncpy(buffer, domain, sizeof(buffer) - 1); if (end - buffer >= (ptrdiff_t)sizeof(buffer) - 1) return false; return !walk_domain_set(D, buffer, DOMAIN_SET_ADD); } bool domain_set_contains(domain_set_t* D, const char* domain) { if (D == NULL) return false; char buffer[512]; char* end = stpncpy(buffer, domain, sizeof(buffer) - 1); if (end - buffer >= (ptrdiff_t)sizeof(buffer) - 1) return false; return walk_domain_set(D, buffer, DOMAIN_SET_PARENTS_MATCH); } struct pid_set { size_t capacity; size_t size; pid_t* entries; }; pid_set_t* pid_set_create() { pid_set_t* P = malloc(sizeof(pid_set_t)); if (P != NULL) { P->capacity = 0; P->size = 0; P->entries = NULL; } return P; } size_t pid_set_size(pid_set_t* P) { return P != NULL ? P->size : 0; } bool pid_set_add(pid_set_t* P, pid_t pid) { if (P == NULL) return false; if (pid <= 0) return false; for (size_t i = 0; i < P->size; ++i) { if (P->entries[i] == pid) return false; } if (P->capacity == P->size) { if (P->capacity == 0) { P->entries = malloc(16 * sizeof(pid_t)); if (P->entries == NULL) return false; P->capacity = 4; } else { pid_t* new_entries = realloc(P->entries, 2 * P->capacity * sizeof(pid_t)); if (new_entries == NULL) return false; P->entries = new_entries; P->capacity *= 2; } } P->entries[P->size++] = pid; return true; } bool pid_set_remove(pid_set_t* P, pid_t pid) { if (P == NULL) return false; for (size_t i = 0; i < P->size; ++i) { if (P->entries[i] == pid) { --P->size; P->entries[i] = P->entries[P->size]; return true; } } return false; } bool pid_set_kill(pid_set_t* P, int signal) { if (P == NULL) return false; for (size_t i = 0; i < P->size;) { if (kill(P->entries[i], signal) < 0) { if (errno == EINVAL) return false; if (errno == ESRCH || errno == EPERM) { --P->size; P->entries[i] = P->entries[P->size]; continue; } } ++i; } return true; } void pid_set_wait(pid_set_t* P) { if (P == NULL) return; while (P->size > 0) { int status; pid_t pid = wait(&status); pid_set_remove(P, pid); } } void pid_set_destroy(pid_set_t* P) { if (P == NULL) return; free(P->entries); free(P); } struct list { size_t capacity; size_t size; void** entries; }; list_t* list_create() { list_t* L = malloc(sizeof(list_t)); if (L != NULL) { L->capacity = 0; L->size = 0; L->entries = NULL; } return L; } void* list_get(list_t* L, size_t i) { if (L != NULL && i < L->size) return L->entries[i]; return NULL; } int list_find(list_t* L, list_compare_t compare, const void* value) { if (L != NULL) { for (size_t i = 0; i < L->size; ++i) if (compare(L->entries[i], value)) return i; } return -1; } bool list_append(list_t* L, void* entry) { if (L == NULL) return false; if (L->size >= L->capacity) { if (L->capacity == 0) { L->entries = malloc(4 * sizeof(void*)); if (L->entries == NULL) return false; L->capacity = 4; } else { void** new_entries = realloc(L->entries, 2 * L->capacity * sizeof(void*)); if (new_entries == NULL) return false; L->entries = new_entries; L->capacity *= 2; } } L->entries[L->size++] = entry; return true; } bool list_replace_at(list_t* L, size_t i, void* entry, list_deleter_t deleter) { if (L == NULL) return false; if (i >= L->size) return false; if (deleter != NULL) deleter(L->entries[i]); L->entries[i] = entry; return true; } bool list_remove_at(list_t* L, size_t i, list_deleter_t deleter) { if (L == NULL) return false; if (i >= L->size) return false; if (deleter != NULL) deleter(L->entries[i]); for (size_t j = i; j < L->size - 1; ++j) L->entries[j] = L->entries[j + 1]; --L->size; return true; } size_t list_remove_if(list_t* L, list_predicate_t predicate, list_deleter_t deleter) { if (L == NULL) return 0; if (predicate == NULL) return 0; size_t j = 0, removed = 0; for (size_t i = 0; i < L->size; ++i) { if (predicate(L->entries[i])) { if (deleter != NULL) deleter(L->entries[i]); ++removed; } else { L->entries[j++] = L->entries[i]; } } L->size = j; return removed; } size_t list_remove_if_value(list_t* L, list_compare_t compare, const void* value, list_deleter_t deleter) { if (L == NULL) return 0; if (compare == NULL) return 0; size_t j = 0, removed = 0; for (size_t i = 0; i < L->size; ++i) { if (compare(L->entries[i], value)) { if (deleter != NULL) deleter(L->entries[i]); ++removed; } else { L->entries[j++] = L->entries[i]; } } L->size = j; return removed; } size_t list_size(list_t* L) { if (L != NULL) return L->size; return 0; } void list_clear(list_t* L, list_deleter_t deleter) { if (L == NULL) return; if (deleter != NULL) { for (size_t i = 0; i < L->size; ++i) { deleter(L->entries[i]); } } L->size = 0; } void list_destroy(list_t* L, list_deleter_t deleter) { if (L == NULL) return; list_clear(L, deleter); free(L->entries); free(L); } #define MAX_WD 16 struct file_watch_entry { int wd; unsigned mask; char* path; char* filter; file_watch_cb_t cb; }; struct file_watch { int fd; list_t* entries; }; #ifdef HAVE_SYS_INOTIFY_H static bool file_watch__is_matching_wd(const void* value1, const void* value2) { return ((const struct file_watch_entry*)value1)->wd == *(const int*)value2; } static bool file_watch__same_path(const void* value1, const void* value2) { return strcmp(((const struct file_watch_entry*)value1)->path, (const char*)value2) == 0; } #endif static void file_watch__delete_entry(void* value) { struct file_watch_entry* entry = (struct file_watch_entry*)value; free(entry->path); free(entry->filter); free(entry); } file_watch_t* file_watch_create() { #ifdef HAVE_SYS_INOTIFY_H file_watch_t* W = malloc(sizeof(file_watch_t)); if (W != NULL) { W->fd = inotify_init1(IN_NONBLOCK | IN_CLOEXEC); W->entries = list_create(); } return W; #else log_warn("inotify API is not supported on this system"); return NULL; #endif } int file_watch_poll_fd(file_watch_t* W) { return W != NULL ? W->fd : -1; } size_t file_watch_prepare_poll(file_watch_t* W, struct pollfd* pollfds, size_t max_fds) { if (W != NULL && max_fds >= 1) { pollfds[0].fd = W->fd; pollfds[0].events = POLLIN; pollfds[0].revents = 0; return 1; } return 0; } void file_watch_process_events(file_watch_t* W) { if (W == NULL) return; #ifdef HAVE_SYS_INOTIFY_H char buf[4096] ATTRIBUTE(aligned(__alignof__(struct inotify_event))); char filepath[1024]; filepath[sizeof(filepath) - 1] = 0; const struct inotify_event* event; ssize_t size = read(W->fd, buf, sizeof(buf)); if (size <= 0) return; size_t num_wd = list_size(W->entries); for (char* ptr = buf; ptr < buf + size; ptr += sizeof(struct inotify_event) + event->len) { event = (const struct inotify_event*)ptr; unsigned what = 0; if (event->mask & (IN_CREATE | IN_MOVED_TO)) what |= FW_CREATED; if (event->mask & (IN_CLOSE_WRITE | IN_MOVED_TO)) what |= FW_MODIFIED; if (event->mask & (IN_DELETE | IN_DELETE_SELF | IN_MOVED_FROM)) what |= FW_DELETED; if (event->mask & IN_MODIFY) what |= FW_CHANGING; if (event->len > 0) log_debug("inotify: watch event [wd=%d, mask=%#x, name=\"%s\"]", event->wd, event->mask, event->name); else log_debug("inotify: watch event [wd=%d, mask=%#x, name=NULL]", event->wd, event->mask); if (what != 0) { for (size_t i = 0; i < num_wd; ++i) { const struct file_watch_entry* entry = (const struct file_watch_entry*)list_get(W->entries, i); if (entry->wd == event->wd) { if (entry->filter != NULL && (event->len == 0 || strcmp(entry->filter, event->name) != 0)) continue; char* fp_end = stpncpy(filepath, entry->path, sizeof(filepath) - 1); if (event->len > 0 && event->len < sizeof(filepath) - (fp_end - filepath) - 2) { fp_end = stpcpy(fp_end, "/"); stpncpy(fp_end, event->name, event->len); if (entry->mask && list_find(W->entries, file_watch__same_path, filepath) < 0) { struct file_watch_entry* new_entry = (struct file_watch_entry*)malloc( sizeof(struct file_watch_entry)); if (new_entry != NULL) { new_entry->wd = inotify_add_watch( W->fd, filepath, entry->mask); new_entry->path = strdup(filepath); new_entry->mask = 0; new_entry->filter = NULL; new_entry->cb = entry->cb; list_append(W->entries, new_entry); log_debug("inotify: watching '%s' [wd=%d]", new_entry->path, new_entry->wd); } } log_debug("inotify: directory event for '%s'", event->name); } entry->cb(filepath, what, event->cookie); break; } } } if (event->mask & IN_IGNORED) { log_debug("inotify: removing entries for [wd=%d]", event->wd); num_wd -= list_remove_if_value(W->entries, file_watch__is_matching_wd, &event->wd, file_watch__delete_entry); } } #endif } bool file_watch_if_modified(file_watch_t* W, const char* path, file_watch_cb_t callback) { if (W == NULL || path == NULL || callback == NULL) return false; #ifdef HAVE_SYS_INOTIFY_H struct file_watch_entry* entry = (struct file_watch_entry*)malloc(sizeof(struct file_watch_entry)); if (entry == NULL) return false; entry->wd = inotify_add_watch(W->fd, path, IN_CLOSE_WRITE | IN_DELETE_SELF | IN_MODIFY); entry->mask = 0; entry->path = strdup(path); entry->filter = NULL; entry->cb = callback; list_append(W->entries, entry); log_debug("inotify: watching '%s' [wd=%d]", entry->path, entry->wd); const char* slash = strrchr(path, '/'); if (slash != NULL) { entry = (struct file_watch_entry*)malloc(sizeof(struct file_watch_entry)); entry->path = strndup(path, slash - path); entry->wd = inotify_add_watch(W->fd, entry->path, IN_MOVE | IN_CREATE); entry->mask = IN_CLOSE_WRITE | IN_DELETE_SELF | IN_MODIFY; entry->filter = strdup(slash + 1); entry->cb = callback; list_append(W->entries, entry); log_debug("inotify: watching '%s' [wd=%d]", entry->path, entry->wd); } return true; #else return false; #endif } bool file_watch_remove(file_watch_t* W, int wd) { if (W != NULL && wd >= 0) { #ifdef HAVE_SYS_INOTIFY_H return inotify_rm_watch(W->fd, wd) == 0; #endif } return false; } void file_watch_destroy(file_watch_t* W) { if (W != NULL) { list_destroy(W->entries, file_watch__delete_entry); close(W->fd); free(W); } } char* endpoint_for_redis(const char* s, int* port) { if (s == NULL) return NULL; const char* colon = strchr(s, ':'); const char* slash = strchr(s, '/'); if (slash || !colon) { /* Treat this as unix socket path */ *port = -1; return strdup(s); } if (colon == s) return NULL; char* end; *port = strtol(colon + 1, &end, 10); if (NONEMPTY_STRING(end) || *port <= 0) return NULL; return strndup(s, colon - s); } static enum log_priority log_prio = LogInfo; static const char* priority_labels[] = {"debug: ", "", "warn: ", "error: "}; static bool use_syslog = false; static int syslog_priorities[] = {LOG_DEBUG, LOG_INFO, LOG_WARNING, LOG_ERR}; static void vlog(enum log_priority prio, const char* fmt, va_list ap) { if (prio < log_prio) return; char buffer[1088]; size_t prefix_len = snprintf(buffer, sizeof(buffer), "postsrsd: %s", priority_labels[prio]); char* text = buffer + prefix_len; vsnprintf(text, sizeof(buffer) - prefix_len, fmt, // flawfinder: ignore ap); buffer[sizeof(buffer) - 1] = 0; fprintf(stderr, "%s\n", buffer); fflush(stderr); if (use_syslog) { syslog(LOG_MAIL | syslog_priorities[prio], "%s", text); } } void log_enable_syslog() { if (!use_syslog) { time_t now; openlog("postsrsd", LOG_PID | LOG_NDELAY, LOG_MAIL); now = time(NULL); localtime(&now); use_syslog = true; } } void log_disable_syslog() { if (use_syslog) { closelog(); use_syslog = false; } } void log_set_verbosity(enum log_priority prio) { log_prio = prio; } void log_debug(const char* fmt, ...) { va_list ap; va_start(ap, fmt); vlog(LogDebug, fmt, ap); va_end(ap); } void log_info(const char* fmt, ...) { va_list ap; va_start(ap, fmt); vlog(LogInfo, fmt, ap); va_end(ap); } void log_warn(const char* fmt, ...) { va_list ap; va_start(ap, fmt); vlog(LogWarn, fmt, ap); va_end(ap); } void log_error(const char* fmt, ...) { va_list ap; va_start(ap, fmt); vlog(LogError, fmt, ap); va_end(ap); } void log_perror(int err, const char* prefix) { char* msg = strerror(err); if (NONEMPTY_STRING(prefix)) log_error("%s: %s", prefix, msg); else log_error("%s", msg); } void log_fatal(const char* fmt, ...) { va_list ap; va_start(ap, fmt); vlog(LogError, fmt, ap); va_end(ap); exit(EXIT_FAILURE); } bool sd_notify(const char* fmt, ...) { char message[128]; if (fmt == NULL) return false; va_list ap; va_start(ap, fmt); ssize_t message_len = vsnprintf(message, sizeof(message), fmt, ap); // flawfinder: ignore if (message_len <= 0) return false; const char* notify_socket = getenv("NOTIFY_SOCKET"); if (notify_socket == NULL) return false; struct sockaddr_un sa; size_t sock_len = strlen(notify_socket); if (sock_len >= sizeof(sa.sun_path)) { log_error("NOTIFY_SOCKET path is too big"); return false; } sa.sun_family = AF_UNIX; memcpy(sa.sun_path, notify_socket, sock_len); if (sa.sun_path[0] == '@') sa.sun_path[0] = 0; int fd = socket(AF_UNIX, SOCK_DGRAM | SOCK_CLOEXEC, 0); if (fd < 0) { log_perror(errno, "sd_notify socket"); return false; } #ifndef HAVE_SOCK_CLOEXEC int flags = fcntl(fd, F_GETFL); if (fcntl(fd, F_SETFL, flags | O_CLOEXEC) < 0) { log_perror(errno, "sd_notify fcntl"); return false; } #endif if (connect(fd, (const struct sockaddr*)&sa, offsetof(struct sockaddr_un, sun_path) + sock_len) < 0) { log_perror(errno, "sd_notify connect"); close(fd); return false; } ssize_t written; do { written = send(fd, message, message_len, MSG_NOSIGNAL); } while (written < 0 && errno == EINTR); if (written != (ssize_t)message_len) { log_perror(errno, "sd_notify write"); close(fd); return false; } close(fd); return true; } sandbox_t* sandbox_init() { #ifdef WITH_SECCOMP scmp_filter_ctx scmp_ctx; scmp_ctx = seccomp_init(SCMP_ACT_KILL_PROCESS); if (scmp_ctx == NULL) return NULL; /* Syscalls without database access */ if (seccomp_rule_add(scmp_ctx, SCMP_ACT_ALLOW, SCMP_SYS(read), 0) < 0) goto fail; if (seccomp_rule_add(scmp_ctx, SCMP_ACT_ALLOW, SCMP_SYS(readv), 0) < 0) goto fail; if (seccomp_rule_add(scmp_ctx, SCMP_ACT_ALLOW, SCMP_SYS(write), 0) < 0) goto fail; if (seccomp_rule_add(scmp_ctx, SCMP_ACT_ALLOW, SCMP_SYS(writev), 0) < 0) goto fail; if (seccomp_rule_add(scmp_ctx, SCMP_ACT_ALLOW, SCMP_SYS(alarm), 0) < 0) goto fail; if (seccomp_rule_add(scmp_ctx, SCMP_ACT_ALLOW, SCMP_SYS(setitimer), 0) < 0) goto fail; if (seccomp_rule_add(scmp_ctx, SCMP_ACT_ALLOW, SCMP_SYS(sigreturn), 0) < 0) goto fail; if (seccomp_rule_add(scmp_ctx, SCMP_ACT_ALLOW, SCMP_SYS(rt_sigreturn), 0) < 0) goto fail; if (seccomp_rule_add(scmp_ctx, SCMP_ACT_ALLOW, SCMP_SYS(close), 0) < 0) goto fail; if (seccomp_rule_add(scmp_ctx, SCMP_ACT_ALLOW, SCMP_SYS(exit), 0) < 0) goto fail; if (seccomp_rule_add(scmp_ctx, SCMP_ACT_ALLOW, SCMP_SYS(exit_group), 0) < 0) goto fail; if (seccomp_rule_add(scmp_ctx, SCMP_ACT_ALLOW, SCMP_SYS(time), 0) < 0) goto fail; if (seccomp_rule_add(scmp_ctx, SCMP_ACT_ALLOW, SCMP_SYS(brk), 0) < 0) goto fail; if (seccomp_rule_add(scmp_ctx, SCMP_ACT_ALLOW, SCMP_SYS(madvise), 0) < 0) goto fail; if (seccomp_rule_add(scmp_ctx, SCMP_ACT_ALLOW, SCMP_SYS(mprotect), 1, SCMP_A2(SCMP_CMP_MASKED_EQ, PROT_EXEC, 0)) < 0) goto fail; if (seccomp_rule_add(scmp_ctx, SCMP_ACT_ALLOW, SCMP_SYS(mmap), 1, SCMP_A2(SCMP_CMP_MASKED_EQ, PROT_EXEC, 0)) < 0) goto fail; if (seccomp_rule_add(scmp_ctx, SCMP_ACT_ALLOW, SCMP_SYS(munmap), 0) < 0) goto fail; # ifdef WITH_SQLITE /* Syscalls for SQlite database access */ if (seccomp_rule_add(scmp_ctx, SCMP_ACT_ALLOW, SCMP_SYS(fstat), 0) < 0) goto fail; if (seccomp_rule_add(scmp_ctx, SCMP_ACT_ALLOW, SCMP_SYS(stat), 0) < 0) goto fail; if (seccomp_rule_add(scmp_ctx, SCMP_ACT_ALLOW, SCMP_SYS(getpid), 0) < 0) goto fail; if (seccomp_rule_add(scmp_ctx, SCMP_ACT_ALLOW, SCMP_SYS(geteuid), 0) < 0) goto fail; if (seccomp_rule_add(scmp_ctx, SCMP_ACT_ALLOW, SCMP_SYS(lseek), 0) < 0) goto fail; if (seccomp_rule_add(scmp_ctx, SCMP_ACT_ALLOW, SCMP_SYS(newfstatat), 0) < 0) goto fail; if (seccomp_rule_add(scmp_ctx, SCMP_ACT_ALLOW, SCMP_SYS(fcntl), 0) < 0) goto fail; if (seccomp_rule_add(scmp_ctx, SCMP_ACT_ALLOW, SCMP_SYS(open), 0) < 0) goto fail; if (seccomp_rule_add(scmp_ctx, SCMP_ACT_ALLOW, SCMP_SYS(openat), 0) < 0) goto fail; if (seccomp_rule_add(scmp_ctx, SCMP_ACT_ALLOW, SCMP_SYS(openat2), 0) < 0) goto fail; if (seccomp_rule_add(scmp_ctx, SCMP_ACT_ALLOW, SCMP_SYS(pread64), 0) < 0) goto fail; if (seccomp_rule_add(scmp_ctx, SCMP_ACT_ALLOW, SCMP_SYS(preadv), 0) < 0) goto fail; if (seccomp_rule_add(scmp_ctx, SCMP_ACT_ALLOW, SCMP_SYS(preadv2), 0) < 0) goto fail; if (seccomp_rule_add(scmp_ctx, SCMP_ACT_ALLOW, SCMP_SYS(pwrite64), 0) < 0) goto fail; if (seccomp_rule_add(scmp_ctx, SCMP_ACT_ALLOW, SCMP_SYS(pwritev), 0) < 0) goto fail; if (seccomp_rule_add(scmp_ctx, SCMP_ACT_ALLOW, SCMP_SYS(pwritev2), 0) < 0) goto fail; if (seccomp_rule_add(scmp_ctx, SCMP_ACT_ALLOW, SCMP_SYS(fsync), 0) < 0) goto fail; if (seccomp_rule_add(scmp_ctx, SCMP_ACT_ALLOW, SCMP_SYS(fdatasync), 0) < 0) goto fail; if (seccomp_rule_add(scmp_ctx, SCMP_ACT_ALLOW, SCMP_SYS(unlink), 0) < 0) goto fail; /* SQLite calls fchown if it detects that it is run as root */ if (seccomp_rule_add(scmp_ctx, SCMP_ACT_ERRNO(EPERM), SCMP_SYS(fchown), 0) < 0) goto fail; # endif # ifdef WITH_REDIS /* Syscalls for Redis database access */ if (seccomp_rule_add(scmp_ctx, SCMP_ACT_ALLOW, SCMP_SYS(sendto), 0) < 0) goto fail; if (seccomp_rule_add(scmp_ctx, SCMP_ACT_ALLOW, SCMP_SYS(recvfrom), 0) < 0) goto fail; # endif # ifdef __SANITIZE_ADDRESS__ /* These syscalls are used by the Address Sanitizer */ if (seccomp_rule_add(scmp_ctx, SCMP_ACT_ALLOW, SCMP_SYS(sigaltstack), 0) < 0) goto fail; if (seccomp_rule_add(scmp_ctx, SCMP_ACT_ALLOW, SCMP_SYS(rt_sigprocmask), 0) < 0) goto fail; if (seccomp_rule_add(scmp_ctx, SCMP_ACT_ALLOW, SCMP_SYS(rt_sigaction), 0) < 0) goto fail; if (seccomp_rule_add(scmp_ctx, SCMP_ACT_ALLOW, SCMP_SYS(gettid), 0) < 0) goto fail; if (seccomp_rule_add(scmp_ctx, SCMP_ACT_ALLOW, SCMP_SYS(getppid), 0) < 0) goto fail; if (seccomp_rule_add(scmp_ctx, SCMP_ACT_ALLOW, SCMP_SYS(futex), 0) < 0) goto fail; if (seccomp_rule_add(scmp_ctx, SCMP_ACT_ALLOW, SCMP_SYS(prctl), 0) < 0) goto fail; if (seccomp_rule_add(scmp_ctx, SCMP_ACT_ALLOW, SCMP_SYS(clone), 0) < 0) goto fail; if (seccomp_rule_add(scmp_ctx, SCMP_ACT_ALLOW, SCMP_SYS(wait4), 0) < 0) goto fail; if (seccomp_rule_add(scmp_ctx, SCMP_ACT_ALLOW, SCMP_SYS(sched_yield), 0) < 0) goto fail; if (seccomp_rule_add(scmp_ctx, SCMP_ACT_ALLOW, SCMP_SYS(ptrace), 0) < 0) goto fail; if (seccomp_rule_add(scmp_ctx, SCMP_ACT_ALLOW, SCMP_SYS(getdents64), 0) < 0) goto fail; if (seccomp_rule_add(scmp_ctx, SCMP_ACT_ALLOW, SCMP_SYS(readlink), // flawfinder: ignore 0) < 0) goto fail; if (seccomp_rule_add(scmp_ctx, SCMP_ACT_ERRNO(EINVAL), SCMP_SYS(ioctl), 0) < 0) goto fail; # endif return (sandbox_t*)scmp_ctx; fail: seccomp_release(scmp_ctx); return NULL; #else return NULL; #endif } bool sandbox_enable(sandbox_t* sandbox) { MAYBE_UNUSED(sandbox); #ifdef WITH_SECCOMP if (sandbox == NULL) return false; return seccomp_load((scmp_filter_ctx)sandbox) == 0; #else return false; #endif } void sandbox_release(sandbox_t* sandbox) { MAYBE_UNUSED(sandbox); #ifdef WITH_SECCOMP if (sandbox != NULL) seccomp_release((scmp_filter_ctx)sandbox); #endif } int signal_set_handler(int signum, signal_handler_t handler) { sigset_t no_signals; sigemptyset(&no_signals); struct sigaction sact = { .sa_handler = handler, .sa_mask = no_signals, .sa_flags = 0}; return sigaction(signum, &sact, NULL); } int signal_reset_handler(int signum) { sigset_t no_signals; sigemptyset(&no_signals); struct sigaction sact = { .sa_handler = SIG_DFL, .sa_mask = no_signals, .sa_flags = 0}; return sigaction(signum, &sact, NULL); } int signal_set_handler_once(int signum, signal_handler_t handler) { sigset_t no_signals; sigemptyset(&no_signals); struct sigaction sact = { .sa_handler = handler, .sa_mask = no_signals, .sa_flags = SA_RESETHAND}; return sigaction(signum, &sact, NULL); } int signal_ignore(int signum) { sigset_t no_signals; sigemptyset(&no_signals); struct sigaction sact = { .sa_handler = SIG_IGN, .sa_mask = no_signals, .sa_flags = 0}; return sigaction(signum, &sact, NULL); } roehling-postsrsd-24c678b/src/util.h000066400000000000000000000114731526152470400174720ustar00rootroot00000000000000/* PostSRSd - Sender Rewriting Scheme daemon for Postfix * Copyright 2012-2026 Timo Röhling * SPDX-License-Identifier: GPL-3.0-only * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef UTIL_H #define UTIL_H #include #include #include #include #include #define MAYBE_UNUSED(x) (void)(x) #ifdef __GNUC__ # define ATTRIBUTE(x) __attribute__((x)) #else # define ATTRIBUTE(x) #endif #define NONEMPTY_STRING(s) ((s) != NULL && *(s) != 0) #define NULL_OR_EMPTY_STRING(s) ((s) == NULL || *(s) == 0) struct pollfd; struct domain_set; typedef struct domain_set domain_set_t; struct pid_set; typedef struct pid_set pid_set_t; struct list; typedef struct list list_t; typedef void (*list_deleter_t)(void*); typedef bool (*list_predicate_t)(const void*); typedef bool (*list_compare_t)(const void*, const void*); struct file_watch; typedef struct file_watch file_watch_t; typedef void (*file_watch_cb_t)(const char*, unsigned, size_t); #define FW_CREATED 1 #define FW_MODIFIED 2 #define FW_DELETED 4 #define FW_CHANGING 8 bool string_equal(const void* s1, const void* s2); void string_set(char** var, char* value); char* b32h_encode(const char* data, size_t length, char* buffer, size_t bufsize); bool file_exists(const char* filename); bool directory_exists(const char* dirname); int lock_acquire(const char* path); void lock_release(const char* path, int fd); bool read_all(int fd, void* buffer, size_t size); bool writev_all(int fd, struct iovec* iov, size_t numv); domain_set_t* domain_set_create(); bool domain_set_add(domain_set_t* D, const char* domain); bool domain_set_contains(domain_set_t* D, const char* domain); void domain_set_destroy(domain_set_t* D); pid_set_t* pid_set_create(); size_t pid_set_size(pid_set_t* P); bool pid_set_add(pid_set_t* P, pid_t pid); bool pid_set_remove(pid_set_t* P, pid_t pid); bool pid_set_kill(pid_set_t* P, int signal); void pid_set_wait(pid_set_t* P); void pid_set_destroy(pid_set_t* P); list_t* list_create(); void* list_get(list_t* L, size_t i); int list_find(list_t* L, list_compare_t compare, const void* value); bool list_append(list_t* L, void* entry); size_t list_size(list_t* L); bool list_replace_at(list_t* L, size_t i, void* entry, list_deleter_t deleter); bool list_remove_at(list_t* L, size_t i, list_deleter_t deleter); size_t list_remove_if(list_t* L, list_predicate_t predicate, list_deleter_t deleter); size_t list_remove_if_value(list_t* L, list_compare_t compare, const void* value, list_deleter_t deleter); void list_clear(list_t* L, list_deleter_t deleter); void list_destroy(list_t* L, list_deleter_t deleter); file_watch_t* file_watch_create(); int file_watch_poll_fd(file_watch_t* W); size_t file_watch_prepare_poll(file_watch_t* W, struct pollfd* pollfds, size_t max_fds); void file_watch_process_events(file_watch_t* W); bool file_watch_if_modified(file_watch_t* W, const char* path, file_watch_cb_t callback); void file_watch_destroy(file_watch_t* W); char* endpoint_for_redis(const char* s, int* port); enum log_priority { LogDebug, LogInfo, LogWarn, LogError, }; void log_enable_syslog(); void log_disable_syslog(); void log_set_verbosity(enum log_priority prio); void log_debug(const char* fmt, ...) ATTRIBUTE(format(printf, 1, 2)); // flawfinder: ignore void log_info(const char* fmt, ...) ATTRIBUTE(format(printf, 1, 2)); // flawfinder: ignore void log_warn(const char* fmt, ...) ATTRIBUTE(format(printf, 1, 2)); // flawfinder: ignore void log_error(const char* fmt, ...) ATTRIBUTE(format(printf, 1, 2)); // flawfinder: ignore void log_perror(int errno, const char* prefix); void log_fatal(const char* fmt, ...) ATTRIBUTE(noreturn); bool sd_notify(const char* fmt, ...) ATTRIBUTE(format(printf, 1, 2)); // flawfinder: ignore struct sandbox; typedef struct sandbox sandbox_t; sandbox_t* sandbox_init(); bool sandbox_enable(sandbox_t* sandbox); void sandbox_release(sandbox_t* sandbox); typedef void (*signal_handler_t)(int); int signal_set_handler(int signum, signal_handler_t handler); int signal_set_handler_once(int signum, signal_handler_t handler); int signal_ignore(int signum); int signal_reset_handler(int signum); #endif roehling-postsrsd-24c678b/tests/000077500000000000000000000000001526152470400167115ustar00rootroot00000000000000roehling-postsrsd-24c678b/tests/CMakeLists.txt000066400000000000000000000014131526152470400214500ustar00rootroot00000000000000# PostSRSd - Sender Rewriting Scheme daemon for Postfix # Copyright 2012-2026 Timo Röhling # SPDX-License-Identifier: GPL-3.0-only # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, version 3. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # add_subdirectory(unit) add_subdirectory(blackbox) roehling-postsrsd-24c678b/tests/blackbox/000077500000000000000000000000001526152470400204765ustar00rootroot00000000000000roehling-postsrsd-24c678b/tests/blackbox/CMakeLists.txt000066400000000000000000000030461526152470400232410ustar00rootroot00000000000000# PostSRSd - Sender Rewriting Scheme daemon for Postfix # Copyright 2012-2026 Timo Röhling # SPDX-License-Identifier: GPL-3.0-only # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, version 3. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # find_package(Python3 3.5 QUIET) if(Python3_EXECUTABLE) add_test( NAME blackbox_test_socketmap COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/socketmap.py" "$" "$" "$,$>" ) add_test( NAME blackbox_test_milter COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/milter.py" "$" "$" "$,$>" ) add_test( NAME blackbox_test_daemon_reload COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/reload.py" "$" "$" ) endif() roehling-postsrsd-24c678b/tests/blackbox/milter.py000066400000000000000000000563401526152470400223540ustar00rootroot00000000000000# PostSRSd - Sender Rewriting Scheme daemon for Postfix # Copyright 2012-2026 Timo Röhling # SPDX-License-Identifier: GPL-3.0-only # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, version 3. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # import struct import sys import time from testhelper import * def mf_optneg(sock_stream: SockStream) -> bool: milter_write(sock_stream, struct.pack(">cLLL", b"O", 6, 0xFF, 0xFF)) return milter_read(sock_stream)[:1] == b"O" def mf_macro(sock_stream: SockStream, code: bytes): milter_write(sock_stream, b"D" + code + b"i\x0001234567\x00") def mf_envfrom(sock_stream: SockStream, envfrom: str) -> bytes: milter_write(sock_stream, b"M<" + envfrom.encode() + b">\x00") return milter_read(sock_stream)[:1] def mf_rcptto(sock_stream: SockStream, rcptto: str) -> bytes: milter_write(sock_stream, b"R<" + rcptto.encode() + b">\x00") return milter_read(sock_stream)[:1] def mf_eom(sock_stream: SockStream) -> tuple[bytes, str | None, list[str] | None]: new_from = None new_rcpts: list[str] | None = None milter_write(sock_stream, b"E") data = milter_read(sock_stream) code = data[:1] while code in [b"+", b"-", b"e"]: if code == b"+": new_rcpt = data[1:-1].decode() if new_rcpt[0] == "<" and new_rcpt[-1] == ">": new_rcpt = new_rcpt[1:-2] if new_rcpts is None: new_rcpts = list() new_rcpts.append(new_rcpt) if code == b"e": new_from = data[1:-1].decode() if new_from[0] == "<" and new_from[-1] == ">": new_from = new_from[1:-2] data = milter_read(sock_stream) code = data[:1] return code, new_from, new_rcpts def execute_queries( postsrsd: str, when: str, queries: list[ tuple[tuple[str, list[str]], tuple[bytes, str | None, list[str] | None]] ], database: Database = Database.NONE, socket_family: SocketFamily = SocketFamily.UNIX, ): with PostSRSd( postsrsd, when=when, database=database, socket_family=socket_family, socket_type=SocketType.MILTER, ) as daemon: with daemon.connect_stream() as sock_stream: assert mf_optneg(sock_stream), "milter option negotation failed" for query in queries: orig_from, orig_rcpts = query[0] result, new_from, new_rcpts = query[1] try: srs_from = None srs_rcpts = None mf_macro(sock_stream, b"M") srs_result = mf_envfrom(sock_stream, orig_from) if srs_result == b"c": mf_macro(sock_stream, b"R") for orig_rcpt in orig_rcpts: srs_result = mf_rcptto(sock_stream, orig_rcpt) if srs_result != b"c": break if srs_result == b"c": mf_macro(sock_stream, b"E") srs_result, srs_from, srs_rcpts = mf_eom(sock_stream) assert ( srs_result == result ), f"expected action {result!r} and got {srs_result!r}" assert ( srs_from == new_from ), f"expected from {new_from!r} and got {srs_from!r}" assert ( srs_rcpts == new_rcpts ), f"expected rcpt {new_rcpts!r} and got {srs_rcpts!r}" sys.stderr.write( f"PASS: {database!r},{socket_family!r},{query[0]!r}\n" ) except AssertionError as e: sys.stderr.write( f"*** FAIL: {database!r},{socket_family!r},{query[0]!r}: {str(e)}\n" ) return False return True def milter_protocol_violations( postsrsd: str, when: str, socket_family: SocketFamily = SocketFamily.UNIX ): def duplicate_optneg(sock_stream: SockStream): assert mf_optneg(sock_stream), "initial milter option negotiation failed" milter_write(sock_stream, struct.pack(">cLLL", b"O", 6, 0xFF, 0xFF)) code = milter_read(sock_stream)[:1] assert ( code == b"t" ), "milter should have temp-failed on repeated option negotiation" def no_optneg(sock_stream: SockStream): code = mf_envfrom(sock_stream, "sender@jumps-the-gun.com>") assert code == b"t", "milter should have temp-failed" def no_mail_command(sock_stream: SockStream): assert mf_optneg(sock_stream), "milter option negotiation failed" code = mf_rcptto(sock_stream, "somewhere@over-the-rainbow.com") assert code == b"t", "milter should have temp-failed" def no_rcpt_command(sock_stream: SockStream): assert mf_optneg(sock_stream), "milter option negotiation failed" code = mf_envfrom(sock_stream, "sender@jumps-the-gun.com") assert code == b"c", "milter should have continued" code, _, _ = mf_eom(sock_stream) assert code == b"t", "milter should have temp-failed" def send_mail_command_twice(sock_stream: SockStream): assert mf_optneg(sock_stream), "milter option negotiation failed" code = mf_envfrom(sock_stream, "sender@example.com") assert code == b"c", "milter should have continued" code = mf_envfrom(sock_stream, "sender2@example.com") assert code == b"t", "milter should have temp-failed" def unsupported_chgfrom_action(sock_stream: SockStream): milter_write(sock_stream, struct.pack(">cLLL", b"O", 6, 0x3F, 0xFF)) code = milter_read(sock_stream)[:1] assert code == b"t", "milter should have temp-failed" def unsupported_addrcpt_action(sock_stream: SockStream): milter_write(sock_stream, struct.pack(">cLLL", b"O", 6, 0xFB, 0xFF)) code = milter_read(sock_stream)[:1] assert code == b"t", "milter should have temp-failed" def unsupported_delrcpt_action(sock_stream: SockStream): milter_write(sock_stream, struct.pack(">cLLL", b"O", 6, 0xF7, 0xFF)) code = milter_read(sock_stream)[:1] assert code == b"t", "milter should have temp-failed" def missing_null_terminators(sock_stream: SockStream): assert mf_optneg(sock_stream), "milter option negotiation failed" milter_write(sock_stream, b"M") code = milter_read(sock_stream)[:1] assert code == b"c", "milter should have continued" milter_write(sock_stream, b"R") code = milter_read(sock_stream)[:1] assert code == b"c", "milter should have continued" code, new_from, new_rcpt = mf_eom(sock_stream) assert code == b"a", f"milter should have accepted" assert ( new_from == "SRS0=9KJ-=2W=otherdomain.com=sender@example.com" ), f"unexpected rewrite of envelope sender: {new_from!r}" assert new_rcpt == [ "test@otherdomain.com" ], f"unexpected rewrite of recipient: {new_rcpt!r}" def oversized_mail_command(sock_stream: SockStream): assert mf_optneg(sock_stream), "milter option negotiation failed" milter_write(sock_stream, b"M<" + (b"a" * 509) + b">\x00") code = milter_read(sock_stream)[:1] assert code == b"r", "milter should have rejected" def malformed_mail_command(sock_stream: SockStream): assert mf_optneg(sock_stream), "milter option negotiation failed" milter_write(sock_stream, b"M>test@example.com<") code = milter_read(sock_stream)[:1] assert code == b"r", "milter should have rejected" def aborted_transaction(sock_stream: SockStream): assert mf_optneg(sock_stream), "milter option negotiation failed" code = mf_envfrom(sock_stream, "mail@example.com") assert code == b"c", "milter should have continued" code = mf_rcptto(sock_stream, "recipient@example.com") assert code == b"c", "milter should have continued" milter_write(sock_stream, b"A") code = mf_envfrom(sock_stream, "sender@otherdomain.com") assert code == b"c", "milter should have continued" code = mf_rcptto(sock_stream, "SRS0=vmyz=2W=otherdomain.com=test@example.com") assert code == b"c", "milter should have continued" code, new_from, new_rcpt = mf_eom(sock_stream) assert code == b"a", f"milter should have accepted" assert ( new_from == "SRS0=9KJ-=2W=otherdomain.com=sender@example.com" ), f"unexpected rewrite of envelope sender: {new_from!r}" assert new_rcpt == [ "test@otherdomain.com" ], f"unexpected rewrite of recipient: {new_rcpt!r}" def close_on_quit(sock_stream: SockStream): assert mf_optneg(sock_stream), "milter option negotiation failed" milter_write(sock_stream, b"Q") try: mf_envfrom(sock_stream, "mail@example.com") raise AssertionError("milter should have disconnected") except (ConnectionError, TimeoutError): pass def oversized_rcpt_command(sock_stream: SockStream): assert mf_optneg(sock_stream), "milter option negotiation failed" assert mf_envfrom(sock_stream, "a" * 508), "milter MAIL command failed" milter_write(sock_stream, b"R<" + (b"a" * 509) + b">\x00") code = milter_read(sock_stream)[:1] assert code == b"r", "milter should have rejected" def too_many_recipients(sock_stream: SockStream): assert mf_optneg(sock_stream), "milter option negotiation failed" assert mf_envfrom(sock_stream, "a" * 508), "milter MAIL command failed" code = None for number in range(10): code = mf_rcptto(sock_stream, f"recipient{number}@example.com") if code == b"r": break assert code == b"r", "milter should have rejected" def malformed_rcpt_command(sock_stream: SockStream): assert mf_optneg(sock_stream), "milter option negotiation failed" assert mf_envfrom(sock_stream, "a" * 508), "milter MAIL command failed" milter_write(sock_stream, b"R>recipient@otherdomain.com<") code = milter_read(sock_stream)[:1] assert code == b"c", "milter should have continued" code, _, _ = mf_eom(sock_stream) assert code == b"r", "milter should have rejected" def send_garbage_first(sock_stream: SockStream): sock_stream.write(b"\x00\x00\xff\xff" + b"!" * 65535) assert mf_optneg(sock_stream), "milter option negotiation failed" code = mf_envfrom(sock_stream, "sender@otherdomain.com") assert code == b"c", "milter should have continued" code = mf_rcptto(sock_stream, "SRS0=vmyz=2W=otherdomain.com=test@example.com") assert code == b"c", "milter should have continued" code, new_from, new_rcpt = mf_eom(sock_stream) assert code == b"a", f"milter should have accepted" assert ( new_from == "SRS0=9KJ-=2W=otherdomain.com=sender@example.com" ), f"unexpected rewrite of envelope sender: {new_from!r}" assert new_rcpt == [ "test@otherdomain.com" ], f"unexpected rewrite of recipient: {new_rcpt!r}" def keep_alive_timeout(sock_stream: SockStream): time.sleep(2) try: mf_optneg(sock_stream) raise AssertionError("milter should have disconnected") except (ConnectionError, TimeoutError): pass with PostSRSd( postsrsd, when=when, socket_family=socket_family, socket_type=SocketType.MILTER ) as daemon: for test_func in [ duplicate_optneg, no_optneg, no_mail_command, no_rcpt_command, send_mail_command_twice, unsupported_chgfrom_action, unsupported_addrcpt_action, unsupported_delrcpt_action, oversized_mail_command, malformed_mail_command, oversized_rcpt_command, malformed_rcpt_command, too_many_recipients, missing_null_terminators, aborted_transaction, close_on_quit, keep_alive_timeout, send_garbage_first, ]: with daemon.connect_stream() as sock_stream: try: test_func(sock_stream) sys.stderr.write(f"PASS: {test_func.__name__}\n") except AssertionError as e: sys.stderr.write(f"*** FAIL: {test_func.__name__}: {str(e)}\n") return False except RuntimeError as e: sys.stderr.write( f"*** FAIL: {test_func.__name__}: {e.__class__.__name__}: {str(e)}\n" ) return False return True STATELESS_QUERIES: list[ tuple[tuple[str, list[str]], tuple[bytes, str | None, list[str] | None]] ] = [ # No rewrite for local domain (("sender@example.com", ["recipient@example.com"]), (b"a", None, None)), # No rewrite if recipient is local ( ("sender@otherdomain.com", ["recipient@example.com"]), (b"a", None, None), ), # Regular rewrite ( ("sender@otherdomain.com", ["recipient@thirddomain.com"]), (b"a", "SRS0=9KJ-=2W=otherdomain.com=sender@example.com", None), ), # Regular rewrite with multiple recipients ( ( "sender@otherdomain.com", [ "recipient@firstdomain.com", "recipient@seconddomain.com", "recipient@thirddomain.com", ], ), (b"a", "SRS0=9KJ-=2W=otherdomain.com=sender@example.com", None), ), # No rewrite for sender without domain ( ("foo", ["recipient@thirddomain.com"]), (b"a", None, None), ), # Treat recipient without domain as local ( ("sender@otherdomain.com", ["bar"]), (b"a", None, None), ), # Convert foreign SRS0 address to SRS1 address ( ("SRS0=opaque+string@otherdomain.com", ["recipient@thirddomain.com"]), (b"a", "SRS1=chaI=otherdomain.com==opaque+string@example.com", None), ), # Change domain part of foreign SRS1 address ( ( "SRS1=X=thirddomain.com==opaque+string@otherdomain.com", ["recipient@thirddomain.com"], ), (b"a", "SRS1=JIBX=thirddomain.com==opaque+string@example.com", None), ), # Recover original mail address from valid SRS0 address ( ( "sender@example.com", ["SRS0=9KJ-=2W=otherdomain.com=sender@example.com"], ), (b"a", None, ["sender@otherdomain.com"]), ), # Handle reverse rewrites for multiple recipients ( ( "sender@example.com", [ "SRS0=9KJ-=2W=otherdomain.com=sender@example.com", "recipient@example.com", "SRS1=chaI=otherdomain.com==opaque+string@example.com", ], ), (b"a", None, ["sender@otherdomain.com", "SRS0=opaque+string@otherdomain.com"]), ), # Rewrite sender if recipient turns out to be non-local ( ( "sender@otherdomain.com", ["SRS0=9KJ-=2W=otherdomain.com=sender@example.com"], ), ( b"a", "SRS0=9KJ-=2W=otherdomain.com=sender@example.com", ["sender@otherdomain.com"], ), ), # Recover original SRS0 address from valid SRS1 address ( ( "sender@example.com", ["SRS1=JIBX=thirddomain.com==opaque+string@example.com"], ), (b"a", None, ["SRS0=opaque+string@thirddomain.com"]), ), # Reject valid SRS0 address with time stamp older than 6 months ( ( "sender@otherdomain.com", ["SRS0=te87=T7=otherdomain.com=test@example.com"], ), (b"r", None, None), ), # Reject valid SRS0 address with time stamp 6 months in the future ( ( "sender@otherdomain.com", ["SRS0=VcIb=7N=otherdomain.com=test@example.com"], ), (b"r", None, None), ), # Recover mail address from all-lowercase SRS0 address ( ( "sender@example.com", ["srs0=xjo9=2v=otherdomain.com=test@example.com"], ), (b"a", None, ["test@otherdomain.com"]), ), # Recover mail address from all-uppercase SRS0 address ( ( "sender@example.com", ["SRS0=XJO9=2V=OTHERDOMAIN.COM=TEST@EXAMPLE.COM"], ), (b"a", None, ["TEST@OTHERDOMAIN.COM"]), ), # Accept SRS0 address with invalid hash but from a different signer ( ( "sender@example.com", ["SRS0=FAKE=2V=otherdomain.com=test@foreign-signer.com"], ), (b"a", None, None), ), # Accept SRS1 address with invalid hash but from a different signer ( ( "sender@example.com", ["SRS1=FAKE=otherdomain.com==opaque+string@foreign-signer.com"], ), (b"a", None, None), ), # Reject SRS0 address with invalid hash ( ( "sender@otherdomain.com", ["SRS0=FAKE=2V=otherdomain.com=test@example.com"], ), (b"r", None, None), ), # Reject SRS0 address without authenticating hash ( ( "sender@otherdomain.com", ["SRS0=@example.com"], ), (b"r", None, None), ), # Reject SRS0 address without time stamp ( ( "sender@otherdomain.com", ["SRS0=XjO9@example.com"], ), (b"r", None, None), ), # Reject SRS0 address without original domain ( ( "sender@otherdomain.com", ["SRS0=XjO9=2V@example.com"], ), (b"r", None, None), ), # Reject SRS0 address without original localpart ( ( "sender@otherdomain.com", ["SRS0=XjO9=2V=otherdomain.com@example.com"], ), (b"r", None, None), ), # Reject database alias without database backend ( ( "sender@otherdomain.com", ["SRS0=bxzH=2W=1=DCJGDE6N24LCRT41A4T0G1UIF0DTKKQJ@example.com"], ), (b"r", None, None), ), # Test long address ( ( "test@" + "a" * (508 - 9) + ".net", ["recipient@otherdomain.com"], ), (b"a", "SRS0=ckoK=2W=" + "a" * (508 - 9) + ".net=test@example.com", None), ), # Recover long address ( ( "sender@example.com", ["SRS0=845K=2W=" + "a" * (508 - 34) + ".net=test@example.com"], ), (b"a", None, ["test@" + "a" * (508 - 34) + ".net"]), ), # Test too long address ( ( "test@" + "a" * (509 - 9) + ".net", ["recipient@otherdomain.com"], ), (b"r", None, None), ), # Handle bounce mail (empty sender) ( ( "", ["SRS0=9KJ-=2W=otherdomain.com=sender@example.com"], ), (b"a", None, ["sender@otherdomain.com"]), ), ] DATABASE_QUERIES: list[ tuple[tuple[str, list[str]], tuple[bytes, str | None, list[str] | None]] ] = [ # Regular rewrite ( ("test@otherdomain.com", ["recipient@thirddomain.com"]), (b"a", "SRS0=bxzH=2W=1=DCJGDE6N24LCRT41A4T0G1UIF0DTKKQJ@example.com", None), ), # Recover address from alias ( ( "sender@example.com", ["SRS0=bxzH=2W=1=DCJGDE6N24LCRT41A4T0G1UIF0DTKKQJ@example.com"], ), (b"a", None, ["test@otherdomain.com"]), ), # Recover address from case-munged alias ( ( "sender@example.com", ["SRS0=bxzH=2W=1=dcjgde6n24lcrt41a4t0g1uif0dtkkqj@example.com"], ), (b"a", None, ["test@otherdomain.com"]), ), # Reject unknown alias ( ( "sender@example.com", ["SRS0=hdxW=2W=1=VVVVVVUNVVVVVVS1VVVVVVUIVVVTKKQJ@example.com"], ), (b"r", None, None), ), # No rewrite for SRS address which is already in the local domain ( ( "SRS0=XjO9=2V=otherdomain.com=test@example.com", ["recipient@otherdomain.com"], ), (b"a", None, None), ), # Convert foreign SRS0 address to SRS1 address ( ("SRS0=opaque+string@otherdomain.com", ["recipient@thirddomain.com"]), (b"a", "SRS1=chaI=otherdomain.com==opaque+string@example.com", None), ), # Change domain part of foreign SRS1 address ( ( "SRS1=X=thirddomain.com==opaque+string@otherdomain.com", ["recipient@thirddomain.com"], ), (b"a", "SRS1=JIBX=thirddomain.com==opaque+string@example.com", None), ), # Accept SRS0 address with invalid hash but from a different signer ( ( "sender@example.com", ["SRS0=FAKE=2V=otherdomain.com=test@foreign-signer.com"], ), (b"a", None, None), ), # Accept SRS1 address with invalid hash but from a different signer ( ( "sender@example.com", ["SRS1=FAKE=otherdomain.com==opaque+string@foreign-signer.com"], ), (b"a", None, None), ), # Recover original mail address from valid SRS0 address ( ( "sender@example.com", ["SRS0=9KJ-=2W=otherdomain.com=sender@example.com"], ), (b"a", None, ["sender@otherdomain.com"]), ), # Handle bounce mail (empty sender) ( ( "", ["SRS0=9KJ-=2W=otherdomain.com=sender@example.com"], ), (b"a", None, ["sender@otherdomain.com"]), ), ] if __name__ == "__main__": for socket_family in [SocketFamily.UNIX, SocketFamily.IP]: if not execute_queries( sys.argv[1], when="1577836860", # 2020-01-01 00:01:00 UTC queries=STATELESS_QUERIES, socket_family=socket_family, ): sys.exit(1) if sys.argv[2] == "1": if not execute_queries( sys.argv[1], when="1577836860", # 2020-01-01 00:01:00 UTC queries=DATABASE_QUERIES, database=Database.SQLITE, socket_family=socket_family, ): sys.exit(1) if sys.argv[3] == "1": if not execute_queries( sys.argv[1], when="1577836860", # 2020-01-01 00:01:00 UTC queries=DATABASE_QUERIES, database=Database.REDIS, socket_family=socket_family, ): sys.exit(1) if not milter_protocol_violations( sys.argv[1], when="1577836860", socket_family=socket_family ): sys.exit(1) sys.exit(0) roehling-postsrsd-24c678b/tests/blackbox/reload.py000066400000000000000000000102701526152470400223160ustar00rootroot00000000000000# PostSRSd - Sender Rewriting Scheme daemon for Postfix # Copyright 2012-2026 Timo Röhling # SPDX-License-Identifier: GPL-3.0-only # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, version 3. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # import itertools import sys import time from testhelper import * def run_query(sock_stream: SockStream, test_domain: str): netstring_write(sock_stream, "forward test@otherdomain.com") result = netstring_read(sock_stream) if not result.startswith("OK SRS0=") or not result.endswith( f"=otherdomain.com=test@{test_domain}" ): raise AssertionError( f"expected 'OK SRS0=...=otherdomain.com=test@{test_domain}', got {result!r}" ) def reload_daemon(postsrsd: str, use_file_watch: bool): with PostSRSd(postsrsd, use_file_watch=use_file_watch) as daemon: sock_stream = daemon.connect_stream() try: previous_domain = "example.com" run_query(sock_stream, previous_domain) for counter, test_domain in enumerate( itertools.cycle( [ "one.com", "two.com", "three.com", ] ) ): if counter % 3 == 0 or not use_file_watch: sys.stderr.write("Opening domain file and modifying content\n") with open(daemon.domains_file, "w") as f: f.write(f"{test_domain}\n") elif counter % 3 == 1: sys.stderr.write( "Renaming different file to replace the domain file\n" ) tmp_file = pathlib.Path(str(daemon.domains_file) + ".tmp") with open(tmp_file, "w") as f: f.write(f"{test_domain}\n") tmp_file.rename(daemon.domains_file) else: sys.stderr.write( "Deleting old domains file and creating a new one\n" ) daemon.domains_file.unlink() with open(daemon.domains_file, "w") as f: f.write(f"{test_domain}\n") if not use_file_watch: sys.stderr.write("Sending reload signal to daemon\n") daemon.reload() try: # We deliberately keep the connection open and continue querying # PostSRSd. The daemon should close the connection as soon as the # configuration has been reloaded. max_wait = 100 while max_wait > 0: run_query(sock_stream, previous_domain) time.sleep(0.1) max_wait -= 1 raise AssertionError("configuration update failed") except ConnectionError: pass sock_stream.close() sock_stream = daemon.connect_stream() run_query(sock_stream, test_domain) sys.stderr.write(f"PASS: reload test {counter + 1} [{test_domain}]\n") previous_domain = test_domain if counter == 8: break except Exception as e: sys.stderr.write(f"*** FAIL: {e.__class__.__name__}: {str(e)}\n") return False finally: sock_stream.close() return True if __name__ == "__main__": if not reload_daemon(sys.argv[1], use_file_watch=False): sys.exit(1) if sys.argv[2] == "1": if not reload_daemon(sys.argv[1], use_file_watch=True): sys.exit(1) sys.exit(0) roehling-postsrsd-24c678b/tests/blackbox/socketmap.py000066400000000000000000000252671526152470400230520ustar00rootroot00000000000000# PostSRSd - Sender Rewriting Scheme daemon for Postfix # Copyright 2012-2026 Timo Röhling # SPDX-License-Identifier: GPL-3.0-only # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, version 3. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # import sys from testhelper import * from collections.abc import Iterable def execute_queries( postsrsd: str, when: str, queries: Iterable[tuple[str, str]], database: Database = Database.NONE, socket_family: SocketFamily = SocketFamily.UNIX, ): with PostSRSd( postsrsd, when=when, database=database, socket_family=socket_family, socket_type=SocketType.SOCKETMAP, ) as daemon: with daemon.connect_stream() as sock_stream: try: for query in queries: netstring_write(sock_stream, query[0]) result = netstring_read(sock_stream) if result != query[1]: raise AssertionError( f"{query[0]!r}: expected reply {query[1]!r}, got: {result!r}" ) sys.stderr.write( f"PASS: {database!r},{socket_family!r},{query[0]!r}\n" ) except AssertionError as e: sys.stderr.write(f"*** FAIL: {database!r},{socket_family!r},{str(e)}\n") return False return True def socketmap_protocol_violations( postsrsd: str, when: str, queries: Iterable[bytes], socket_family: SocketFamily ): with PostSRSd(postsrsd, when=when, socket_family=socket_family) as daemon: for query in queries: with daemon.connect_stream() as sock_stream: try: sock_stream.write(query) result = netstring_read(sock_stream) if result != "PERM Invalid query.": raise AssertionError( f"expected reply 'PERM Invalid query.', got: {result!r}" ) try: netstring_write(sock_stream, "forward test@example.com") result = netstring_read(sock_stream) raise AssertionError( f"expected connection closed, got: {result!r}" ) except ConnectionError: # Expected behavior pass sys.stderr.write(f"PASS: {socket_family!r},{query!r}\n") except AssertionError as e: sys.stderr.write( f"*** FAIL: {socket_family!r},{query!r}: {str(e)}\n" ) return False return True STATELESS_QUERIES = [ # No rewrite for local domain ("forward test@example.com", "NOTFOUND Need not rewrite local domain."), # Regular rewrite ( "forward test@otherdomain.com", "OK SRS0=vmyz=2W=otherdomain.com=test@example.com", ), # No rerwite for mail address without domain ("forward foo", "NOTFOUND No domain."), # No rewrite for SRS address which is already in the local domain ( "forward SRS0=XjO9=2V=otherdomain.com=test@example.com", "NOTFOUND Need not rewrite local domain.", ), # Convert foreign SRS0 address to SRS1 address ( "forward SRS0=opaque+string@otherdomain.com", "OK SRS1=chaI=otherdomain.com==opaque+string@example.com", ), # Change domain part of foreign SRS1 address ( "forward SRS1=X=thirddomain.com==opaque+string@otherdomain.com", "OK SRS1=JIBX=thirddomain.com==opaque+string@example.com", ), # Recover original mail address from valid SRS0 address ( "reverse SRS0=XjO9=2V=otherdomain.com=test@example.com", "OK test@otherdomain.com", ), # Recover original SRS0 address from valid SRS1 address ( "reverse SRS1=JIBX=thirddomain.com==opaque+string@example.com", "OK SRS0=opaque+string@thirddomain.com", ), # Do not rewrite mail address which is not an SRS address ( "reverse test@example.com", "NOTFOUND Not an SRS address.", ), # Ignore valid SRS0 address with time stamp older than 6 months ( "reverse SRS0=te87=T7=otherdomain.com=test@example.com", "NOTFOUND Time stamp out of date.", ), # Ignore valid SRS0 address with time stamp 6 months in the future ( "reverse SRS0=VcIb=7N=otherdomain.com=test@example.com", "NOTFOUND Time stamp out of date.", ), # Ignore SRS0 address with invalid hash (locally created) ( "reverse SRS0=FAKE=2V=otherdomain.com=test@example.com", "NOTFOUND Hash invalid in SRS address.", ), # Ignore SRS0 address with invalid hash (foreign sender) ( "reverse SRS0=FAKE=2V=otherdomain.com=test@foreign.example", "NOTFOUND Hash invalid in SRS address.", ), # Recover mail address from all-lowercase SRS0 address ( "reverse srs0=xjo9=2v=otherdomain.com=test@example.com", "OK test@otherdomain.com", ), # Recover mail address from all-uppcase SRS0 address ( "reverse SRS0=XJO9=2V=OTHERDOMAIN.COM=TEST@EXAMPLE.COM", "OK TEST@OTHERDOMAIN.COM", ), # Check base64url hash encoding ( "forward hash234@somedomain.com", "OK SRS0=-3_5=2W=somedomain.com=hash234@example.com", ), # Recover mail address from base64url encoding ( "reverse SRS0=-3_5=2W=somedomain.com=hash234@example.com", "OK hash234@somedomain.com", ), # Recover mail address from base64 encoding ( "reverse SRS0=+3/5=2W=somedomain.com=hash234@example.com", "OK hash234@somedomain.com", ), # Ignore SRS0 address without authenticating hash ( "reverse SRS0=@example.com", "NOTFOUND No hash in SRS0 address.", ), # Ignore SRS0 address without time stamp ( "reverse SRS0=XjO9@example.com", "NOTFOUND No timestamp in SRS0 address.", ), # Ignore SRS0 address without original domain ( "reverse SRS0=XjO9=2V@example.com", "NOTFOUND No host in SRS0 address.", ), # Ignore SRS0 address without original localpart ( "reverse SRS0=XjO9=2V=otherdomain.com@example.com", "NOTFOUND No user in SRS0 address.", ), # Reject Database alias ( "reverse SRS0=bxzH=2W=1=DCJGDE6N24LCRT41A4T0G1UIF0DTKKQJ@example.com", "PERM No database for alias.", ), # Reject invalid socketmap ( "test@example.com", "PERM Invalid map.", ), # Test long address ( ("forward test@" + "a" * (512 - 9) + ".net"), ("OK SRS0=G7tR=2W=" + "a" * (512 - 9) + ".net=test@example.com"), ), # Recover long address ( ("reverse SRS0=iCvJ=2W=" + "a" * (512 - 34) + ".net=test@example.com"), ("OK test@" + "a" * (512 - 34) + ".net"), ), # Test too long address ( ("forward test@" + "a" * (513 - 9) + ".net"), "PERM Too big.", ), # Test empty address ( "forward ", "NOTFOUND No domain.", ), # Test empty quotes ( 'forward ""', "NOTFOUND No domain.", ), ] DATABASE_QUERIES = [ # Regular rewrite ( "forward test@otherdomain.com", "OK SRS0=bxzH=2W=1=DCJGDE6N24LCRT41A4T0G1UIF0DTKKQJ@example.com", ), # Recover address from alias ( "reverse SRS0=bxzH=2W=1=DCJGDE6N24LCRT41A4T0G1UIF0DTKKQJ@example.com", "OK test@otherdomain.com", ), # Recover address from case-munged alias ( "reverse SRS0=bxzH=2W=1=dcjgde6n24lcrt41a4t0g1uif0dtkkqj@example.com", "OK test@otherdomain.com", ), # Reject unknown alias ( "reverse SRS0=hdxW=2W=1=VVVVVVUNVVVVVVS1VVVVVVUIVVVTKKQJ@example.com", "NOTFOUND Unknown alias.", ), # No rewrite for SRS address which is already in the local domain ( "forward SRS0=XjO9=2V=otherdomain.com=test@example.com", "NOTFOUND Need not rewrite local domain.", ), # Convert foreign SRS0 address to SRS1 address ( "forward SRS0=opaque+string@otherdomain.com", "OK SRS1=chaI=otherdomain.com==opaque+string@example.com", ), # Change domain part of foreign SRS1 address ( "forward SRS1=X=thirddomain.com==opaque+string@otherdomain.com", "OK SRS1=JIBX=thirddomain.com==opaque+string@example.com", ), # Recover original mail address from valid SRS0 address ( "reverse SRS0=XjO9=2V=otherdomain.com=test@example.com", "OK test@otherdomain.com", ), ] if __name__ == "__main__": for socket_family in [SocketFamily.UNIX, SocketFamily.IP]: if not execute_queries( sys.argv[1], when="1577836860", # 2020-01-01 00:01:00 UTC queries=STATELESS_QUERIES, socket_family=socket_family, ): sys.exit(1) if sys.argv[2] == "1": if not execute_queries( sys.argv[1], when="1577836860", # 2020-01-01 00:01:00 UTC queries=DATABASE_QUERIES, database=Database.SQLITE, socket_family=socket_family, ): sys.exit(1) if sys.argv[3] == "1": if not execute_queries( sys.argv[1], when="1577836860", # 2020-01-01 00:01:00 UTC queries=DATABASE_QUERIES, database=Database.REDIS, socket_family=socket_family, ): sys.exit(1) if not socketmap_protocol_violations( sys.argv[1], when="1577836860", queries=[ # Empty query b"0:,", # Netstring that exceeds the allowed length (b"1024:forward " + b"a" * 1016 + b","), # Old-style TCP table query b"get test@example.com\n", # Excessively large netstring length b"18446744073709551616:some data...", # Invalid netstring terminator b"28:forward test@otherdomain.com;", ], socket_family=socket_family, ): sys.exit(1) roehling-postsrsd-24c678b/tests/blackbox/testhelper.py000066400000000000000000000232441526152470400232340ustar00rootroot00000000000000# PostSRSd - Sender Rewriting Scheme daemon for Postfix # Copyright 2012-2026 Timo Röhling # SPDX-License-Identifier: GPL-3.0-only # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, version 3. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # import contextlib import enum import os import pathlib import signal import socket import struct import subprocess import tempfile import threading class SocketType(enum.Enum): SOCKETMAP = 1 MILTER = 2 class SocketFamily(enum.Enum): UNIX = 1 IP = 2 class Database(enum.Enum): NONE = 0 SQLITE = 1 REDIS = 2 class SockStream: def __init__(self, sock: socket.socket): self._sock = sock self._rdbuf = b"" def read(self, size: int): result = b"" remaining = size while remaining > len(self._rdbuf): result += self._rdbuf remaining -= len(self._rdbuf) self._rdbuf = self._sock.recv(4096) if len(self._rdbuf) == 0: raise ConnectionResetError("no data") result += self._rdbuf[:remaining] self._rdbuf = self._rdbuf[remaining:] return result def __enter__(self) -> "SockStream": return self def __exit__(self, *exc_info): # type: ignore self._sock.close() return False def write(self, data: bytes): self._sock.sendall(data) def close(self): self._sock.close() def netstring_write(sock_stream: SockStream, data: str): data_bytes = data.encode() sock_stream.write(f"{len(data_bytes)}:".encode() + data_bytes + b",") def netstring_read(sock_stream: SockStream): digit = sock_stream.read(1) data_size = 0 while digit >= b"0" and digit <= b"9": data_size = 10 * data_size + int(digit) digit = sock_stream.read(1) if digit != b":": raise ValueError("invalid netstring") data = sock_stream.read(data_size) comma = sock_stream.read(1) if comma != b",": raise ValueError("invalid netstring") return data.decode() def milter_write(sock_stream: SockStream, data: bytes): sock_stream.write(struct.pack(">L", len(data)) + data) def milter_read(sock_stream: SockStream) -> bytes: size_bytes = sock_stream.read(4) size = struct.unpack(">L", size_bytes) return sock_stream.read(*size) class PostSRSd: def __init__( self, executable: str, when: str | None = None, database: Database = Database.NONE, socket_family: SocketFamily = SocketFamily.UNIX, socket_type: SocketType = SocketType.SOCKETMAP, use_file_watch: bool = False, ): self._executable = executable self._when = when self._tmpdir = tempfile.TemporaryDirectory() self._tmpdir_path = pathlib.Path(self._tmpdir.name) self._proc: subprocess.Popen[bytes] | None = None self._notify_sock: socket.socket | None = None self._notify_thread: threading.Thread | None = None with contextlib.ExitStack() as on_failure: on_failure.push(self) socketmap_endpoint = {SocketType.SOCKETMAP: "", SocketType.MILTER: ""} if socket_family == SocketFamily.UNIX: self._family = socket.AF_UNIX self._addr = str(self._tmpdir_path / "postsrsd.sock") socketmap_endpoint[socket_type] = ( f'unix:{self._tmpdir_path / "postsrsd.sock"}' ) elif socket_family == SocketFamily.IP: # We pick a PID based port number so multiple tests can run in parallel port = 16384 + (os.getpid() % 32768) self._family = socket.AF_INET self._addr = ("127.0.0.1", port) socketmap_endpoint[socket_type] = f"inet:127.0.0.1:{port}" if database == Database.SQLITE: database_uri = f'sqlite:{self._tmpdir_path / "postsrsd.db"}' elif database == Database.REDIS: database_uri = "redis:localhost:6379" else: database_uri = "" with open(self._tmpdir_path / "postsrsd.conf", "w") as f: f.write( f'domains-file = "{self._tmpdir_path / "postsrsd.domains"}"\n' f'domains-file-watch = {"on" if use_file_watch else "off"}\n' "keep-alive = 1\n" "milter-recipient-limit = 5\n" 'chroot-dir = ""\n' 'unprivileged-user = ""\n' f'original-envelope = {"embedded" if database == Database.NONE else "database"}\n' f'envelope-database = "{database_uri}"\n' f'secrets-file = "{self._tmpdir_path / "postsrsd.secret"}"\n' f'socketmap = "{socketmap_endpoint[SocketType.SOCKETMAP]}"\n' f'milter = "{socketmap_endpoint[SocketType.MILTER]}"\n' ) with open(self._tmpdir_path / "postsrsd.secret", "w") as f: f.write("tops3cr3t\n") with open(self._tmpdir_path / "postsrsd.domains", "w") as f: f.write("example.com\n") self._notify_addr = str(self._tmpdir_path / "postsrsd.notify") self._notify_sock = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM, 0) self._notify_sock.settimeout(1) self._notify_sock.bind(self._notify_addr) self._ready = 0 self._notify_thread = threading.Thread(target=self._notify_thread_run) self._notify_cv = threading.Condition(lock=threading.Lock()) self._notify_thread.start() on_failure.pop_all() def _notify_thread_run(self): try: while self._notify_sock is not None: try: data = self._notify_sock.recv(4096) if b"READY=1" in data: with self._notify_cv: self._ready += 1 self._notify_cv.notify() except TimeoutError: pass except OSError: pass def __enter__(self) -> "PostSRSd": with contextlib.ExitStack() as on_failure: on_failure.push(self) env = os.environ.copy() env["NOTIFY_SOCKET"] = self._notify_addr if self._when is not None: env["POSTSRSD_FAKETIME"] = self._when self._proc = subprocess.Popen( [self._executable, "-C", str(self._tmpdir_path / "postsrsd.conf")], start_new_session=True, env=env, ) with self._notify_cv: if not self._notify_cv.wait_for( lambda: self._ready > 0 or (self._proc is not None and self._proc.poll() is not None), 5.0, ): raise RuntimeError("PostSRSd daemon failed to notify") retcode = self._proc.poll() if retcode is not None: raise RuntimeError(f"PostSRSd daemon failed with exit code {retcode}") on_failure.pop_all() return self def __exit__(self, *exc_args) -> bool: # type: ignore self.cleanup() return False @property def domains_file(self) -> pathlib.Path: return self._tmpdir_path / "postsrsd.domains" def cleanup(self): if self._notify_sock is not None: self._notify_sock.close() self._notify_sock = None if self._proc is not None: try: try: os.killpg(os.getpgid(self._proc.pid), signal.SIGTERM) except PermissionError: os.kill(self._proc.pid, signal.SIGTERM) except ProcessLookupError: pass try: self._proc.wait(5) except subprocess.TimeoutExpired: print("(PostSRSd does not terminate, escalating to SIGKILL)") try: os.killpg(os.getpgid(self._proc.pid), signal.SIGKILL) except PermissionError: os.kill(self._proc.pid, signal.SIGKILL) self._proc.wait() if self._notify_thread is not None: self._notify_thread.join() self._tmpdir.cleanup() def connect(self) -> socket.socket: assert self._proc is not None, "cannot reload daemon if it is not running" retcode = self._proc.poll() while retcode is None: try: sock = socket.socket(self._family, socket.SOCK_STREAM, 0) sock.settimeout(0.5) sock.connect(self._addr) return sock except ConnectionRefusedError: print("(ignoring ConnectionRefusedError)") retcode = self._proc.poll() raise RuntimeError(f"PostSRSd daemon failed with exit code {retcode}") def connect_stream(self) -> SockStream: return SockStream(self.connect()) def reload(self): assert self._proc is not None, "cannot reload daemon if it is not running" retcode = self._proc.poll() if retcode is not None: raise RuntimeError(f"PostSRSd daemon failed with exit code {retcode}") os.kill(self._proc.pid, signal.SIGHUP) roehling-postsrsd-24c678b/tests/unit/000077500000000000000000000000001526152470400176705ustar00rootroot00000000000000roehling-postsrsd-24c678b/tests/unit/CMakeLists.txt000066400000000000000000000045051526152470400224340ustar00rootroot00000000000000# PostSRSd - Sender Rewriting Scheme daemon for Postfix # Copyright 2012-2026 Timo Röhling # SPDX-License-Identifier: GPL-3.0-only # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, version 3. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # macro(add_postsrsd_test name) add_executable(${name}_executable ${name}.c ${ARGN}) target_include_directories( ${name}_executable PRIVATE ${CMAKE_BINARY_DIR} ${CMAKE_SOURCE_DIR}/src ) target_compile_definitions( ${name}_executable PRIVATE _GNU_SOURCE _FILE_OFFSET_BITS=64 ) target_link_libraries( ${name}_executable PRIVATE Check::check $<$:seccomp::seccomp> ${LIBSOCKET} ${LIBNSL} ${LIBNETWORK} ) target_compile_features(${name}_executable PRIVATE c_std_99) if(TESTS_WITH_ASAN) target_compile_options( ${name}_executable PRIVATE -fsanitize=address,undefined ) target_link_options( ${name}_executable PRIVATE -fsanitize=address,undefined ) endif() add_test(NAME unit_${name} COMMAND ${name}_executable) endmacro() set(SRCDIR ../../src) add_postsrsd_test(test_netstring ${SRCDIR}/netstring.c ${SRCDIR}/util.c) add_postsrsd_test(test_sha1 ${SRCDIR}/sha1.c) add_postsrsd_test(test_util ${SRCDIR}/util.c) add_postsrsd_test(test_database ${SRCDIR}/database.c ${SRCDIR}/util.c) target_link_libraries( test_database_executable PRIVATE $<$:sqlite3::sqlite3> $<$:${HIREDIS_TARGET}> ) add_postsrsd_test(test_srs2 ${SRCDIR}/srs2.c ${SRCDIR}/sha1.c) add_postsrsd_test( test_config ${SRCDIR}/config.c ${SRCDIR}/sha1.c ${SRCDIR}/srs2.c ${SRCDIR}/util.c ) target_link_libraries(test_config_executable PRIVATE libconfuse::confuse) add_postsrsd_test(test_milter ${SRCDIR}/milter.c ${SRCDIR}/util.c) roehling-postsrsd-24c678b/tests/unit/common.h000066400000000000000000000044171526152470400213370ustar00rootroot00000000000000/* PostSRSd - Sender Rewriting Scheme daemon for Postfix * Copyright 2012-2026 Timo Röhling * SPDX-License-Identifier: GPL-3.0-only * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef TEST_COMMON_H #define TEST_COMMON_H #include #define BEGIN_TEST_SUITE(suite) \ static Suite* suite##_suite() \ { \ Suite* ts = suite_create(#suite); \ TCase* tcase = tcase_create("tcase"); \ suite_add_tcase(ts, tcase); #define ADD_TEST_CASE(tcase) \ TCase* tcase = tcase_create(#tcase); \ suite_add_tcase(ts, tcase); #define ADD_TEST_CASE_WITH_UNCHECKED_FIXTURE(tcase, setup, teardown) \ ADD_TEST_CASE(tcase) \ tcase_add_checked_fixture(tcase, setup, teardown); #define ADD_TEST_TO_TEST_CASE(tcase, testfunc) tcase_add_test(tcase, testfunc); #define ADD_TEST(testfunc) ADD_TEST_TO_TEST_CASE(tcase, testfunc) #define END_TEST_SUITE() \ return ts; \ } #define TEST_MAIN(suite) \ int main() \ { \ Suite* s = suite##_suite(); \ SRunner* sr = srunner_create(s); \ \ srunner_run_all(sr, CK_VERBOSE); \ int number_failed = srunner_ntests_failed(sr); \ srunner_free(sr); \ return (number_failed == 0) ? EXIT_SUCCESS : EXIT_FAILURE; \ } #endif roehling-postsrsd-24c678b/tests/unit/test_config.c000066400000000000000000000050231526152470400223400ustar00rootroot00000000000000/* PostSRSd - Sender Rewriting Scheme daemon for Postfix * Copyright 2012-2026 Timo Röhling * SPDX-License-Identifier: GPL-3.0-only * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include "common.h" #include "config.h" #include #include #include static char pwd[500]; static char tmpdir[sizeof(pwd) + 7]; void setup_fs() { ck_assert_ptr_nonnull(getcwd(pwd, sizeof(pwd))); strcpy(tmpdir, pwd); strcat(tmpdir, "/XXXXXX"); ck_assert_ptr_eq(mkdtemp(tmpdir), tmpdir); ck_assert_int_eq(chdir(tmpdir), 0); } void teardown_fs() { ck_assert_int_eq(chdir(pwd), 0); ck_assert_int_eq(rmdir(tmpdir), 0); } START_TEST(config_domains_file) { FILE* f = fopen("domains.txt", "w"); fprintf(f, "# This is a comment at the beginning of the file\n" "example.com\n" " # This is a comment with preceding white space\n" "\t tabspace.org\n" "\n" "#unused.org\n" "commented.de # This is a comment after a domain name\n" "trailing.net "); fclose(f); cfg_t* cfg = config_defaults(); cfg_setstr(cfg, "domains-file", "domains.txt"); domain_set_t* D = NULL; char* srs_domain = NULL; ck_assert_int_eq(srs_domains_from_config(cfg, &srs_domain, &D), true); ck_assert_int_eq(domain_set_contains(D, "commented.de"), true); ck_assert_int_eq(domain_set_contains(D, "example.com"), true); ck_assert_int_eq(domain_set_contains(D, "tabspace.org"), true); ck_assert_int_eq(domain_set_contains(D, "trailing.net"), true); ck_assert_int_eq(domain_set_contains(D, "unused.org"), false); ck_assert_str_eq(srs_domain, "example.com"); ck_assert_int_eq(unlink("domains.txt"), 0); domain_set_destroy(D); free(srs_domain); cfg_free(cfg); } END_TEST BEGIN_TEST_SUITE(config) ADD_TEST_CASE_WITH_UNCHECKED_FIXTURE(fs, setup_fs, teardown_fs) ADD_TEST_TO_TEST_CASE(fs, config_domains_file) END_TEST_SUITE() TEST_MAIN(config) roehling-postsrsd-24c678b/tests/unit/test_database.c000066400000000000000000000055401526152470400226430ustar00rootroot00000000000000/* PostSRSd - Sender Rewriting Scheme daemon for Postfix * Copyright 2012-2026 Timo Röhling * SPDX-License-Identifier: GPL-3.0-only * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include "common.h" #include "database.h" #include #include #include #include START_TEST(invalid_database) { ck_assert_ptr_null(database_connect("invalid:", true)); } END_TEST #ifdef WITH_SQLITE START_TEST(database_sqlite_key_value) { database_t* db = database_connect("sqlite::memory:", true); ck_assert_ptr_nonnull(db); ck_assert_ptr_null(database_read(db, "mykey")); database_write(db, "mykey", "myvalue", 1); char* value = database_read(db, "mykey"); ck_assert_str_eq(value, "myvalue"); free(value); database_disconnect(db); } END_TEST START_TEST(database_sqlite_expiry) { database_t* db = database_connect("sqlite::memory:", true); ck_assert_ptr_nonnull(db); database_write(db, "mykey", "myvalue", 0); char* value = database_read(db, "mykey"); ck_assert_str_eq(value, "myvalue"); free(value); database_expire(db); ck_assert_ptr_null(database_read(db, "mykey")); database_disconnect(db); } END_TEST #endif #if defined(WITH_REDIS) && defined(TESTS_WITH_REDIS) START_TEST(database_redis_key_value) { database_t* db = database_connect("redis:localhost:6379", true); ck_assert_ptr_nonnull(db); database_write(db, "mykey", "myvalue", 1); char* value = database_read(db, "mykey"); ck_assert_str_eq(value, "myvalue"); free(value); database_disconnect(db); } END_TEST START_TEST(database_redis_expiry) { database_t* db = database_connect("redis:localhost:6379", true); ck_assert_ptr_nonnull(db); database_write(db, "mykey", "myvalue", 1); char* value = database_read(db, "mykey"); ck_assert_str_eq(value, "myvalue"); free(value); sleep(2); database_expire(db); ck_assert_ptr_null(database_read(db, "mykey")); database_disconnect(db); } END_TEST #endif BEGIN_TEST_SUITE(database) ADD_TEST(invalid_database) #ifdef WITH_SQLITE ADD_TEST(database_sqlite_key_value) ADD_TEST(database_sqlite_expiry) #endif #if defined(WITH_REDIS) && defined(TESTS_WITH_REDIS) ADD_TEST(database_redis_key_value) ADD_TEST(database_redis_expiry) #endif END_TEST_SUITE() TEST_MAIN(database) roehling-postsrsd-24c678b/tests/unit/test_milter.c000066400000000000000000000152261526152470400223750ustar00rootroot00000000000000/* PostSRSd - Sender Rewriting Scheme daemon for Postfix * Copyright 2012-2026 Timo Röhling * SPDX-License-Identifier: GPL-3.0-only * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include "common.h" #include "milter.h" #include START_TEST(milter_macros) { static const char macro_block[] = "a\000alpha\000\000unused\000b\000\000variable\000value"; char* result; result = milter_parse_macros("a", macro_block, sizeof(macro_block)); ck_assert_ptr_nonnull(result); ck_assert_str_eq(result, "alpha"); free(result); result = milter_parse_macros("b", macro_block, sizeof(macro_block)); ck_assert_ptr_nonnull(result); ck_assert_str_eq(result, ""); free(result); result = milter_parse_macros("variable", macro_block, sizeof(macro_block)); ck_assert_ptr_nonnull(result); ck_assert_str_eq(result, "value"); free(result); result = milter_parse_macros("missing", macro_block, sizeof(macro_block)); ck_assert_ptr_null(result); static const char broken_1[] = {'a'}; result = milter_parse_macros("a", broken_1, sizeof(broken_1)); ck_assert_ptr_null(result); result = milter_parse_macros("aaa", broken_1, sizeof(broken_1)); ck_assert_ptr_null(result); static const char broken_2[] = {'a', 0, '1', 0, 'b', 0}; result = milter_parse_macros("a", broken_2, sizeof(broken_2)); ck_assert_ptr_nonnull(result); ck_assert_str_eq(result, "1"); free(result); result = milter_parse_macros("b", broken_2, sizeof(broken_2)); ck_assert_ptr_null(result); } END_TEST START_TEST(milter_str_list) { static const char list_data[] = "one\000two\000three\000\000five"; list_t* L = list_create(); milter_parse_str_list(L, list_data, sizeof(list_data)); ck_assert_uint_eq(list_size(L), 5); ck_assert_str_eq(list_get(L, 0), "one"); ck_assert_str_eq(list_get(L, 1), "two"); ck_assert_str_eq(list_get(L, 2), "three"); ck_assert_str_eq(list_get(L, 3), ""); ck_assert_str_eq(list_get(L, 4), "five"); list_clear(L, free); static const char missing_nul[] = {'o', 'n', 'e'}; milter_parse_str_list(L, missing_nul, sizeof(missing_nul)); ck_assert_uint_eq(list_size(L), 1); ck_assert_str_eq(list_get(L, 0), "one"); list_destroy(L, free); } END_TEST START_TEST(milter_test_parse_address) { char* result; result = milter_parse_address(""); ck_assert_ptr_null(result); result = milter_parse_address(">test@example.com<"); ck_assert_ptr_null(result); result = milter_parse_address(""); ck_assert_str_eq(result, "test@example.com"); free(result); result = milter_parse_address("test@example.com"); ck_assert_str_eq(result, "test@example.com"); free(result); result = milter_parse_address("Test User "); ck_assert_str_eq(result, "test@example.com"); free(result); result = milter_parse_address("<>"); ck_assert_str_eq(result, ""); free(result); result = milter_parse_address(""); ck_assert_str_eq(result, "first"); free(result); ck_assert_ptr_null(milter_parse_address(NULL)); } END_TEST START_TEST(milter_test_parse_address_buf) { char buffer[32]; char* result; result = milter_parse_address_buf("", buffer, sizeof(buffer)); ck_assert_ptr_null(result); result = milter_parse_address_buf(">test@example.com<", buffer, sizeof(buffer)); ck_assert_ptr_null(result); result = milter_parse_address_buf("", buffer, sizeof(buffer)); ck_assert_str_eq(result, "test@example.com"); result = milter_parse_address_buf("test@example.com", buffer, sizeof(buffer)); ck_assert_str_eq(result, "test@example.com"); result = milter_parse_address_buf("Test User ", buffer, sizeof(buffer)); ck_assert_str_eq(result, "test@example.com"); result = milter_parse_address_buf("<>", buffer, sizeof(buffer)); ck_assert_str_eq(result, ""); result = milter_parse_address_buf("", buffer, sizeof(buffer)); ck_assert_str_eq(result, "first"); ck_assert_ptr_null(milter_parse_address_buf(NULL, buffer, sizeof(buffer))); ck_assert_ptr_null(milter_parse_address_buf( "", buffer, sizeof(buffer))); ck_assert_ptr_null(milter_parse_address_buf( "test@aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.com", buffer, sizeof(buffer))); } END_TEST START_TEST(milter_test_parse_address_n) { char* result; result = milter_parse_address_n("", 17); ck_assert_ptr_null(result); result = milter_parse_address_n("test@example.com>", 17); ck_assert_ptr_null(result); result = milter_parse_address_n(">test@example.com<", 18); ck_assert_ptr_null(result); result = milter_parse_address_n("", 18); ck_assert_str_eq(result, "test@example.com"); free(result); result = milter_parse_address_n("test@example.com", 16); ck_assert_str_eq(result, "test@example.com"); free(result); result = milter_parse_address_n("Test User ", 28); ck_assert_str_eq(result, "test@example.com"); free(result); result = milter_parse_address_n("Test User ", 11); ck_assert_ptr_null(result); result = milter_parse_address_n("<>", 2); ck_assert_str_eq(result, ""); free(result); result = milter_parse_address_n("", 15); ck_assert_str_eq(result, "first"); free(result); ck_assert_ptr_null(milter_parse_address_n(NULL, 10000)); } END_TEST BEGIN_TEST_SUITE(milter) ADD_TEST(milter_macros) ADD_TEST(milter_str_list) ADD_TEST(milter_test_parse_address) ADD_TEST(milter_test_parse_address_buf) ADD_TEST(milter_test_parse_address_n) END_TEST_SUITE() TEST_MAIN(milter) roehling-postsrsd-24c678b/tests/unit/test_netstring.c000066400000000000000000000116301526152470400231110ustar00rootroot00000000000000/* PostSRSd - Sender Rewriting Scheme daemon for Postfix * Copyright 2012-2026 Timo Röhling * SPDX-License-Identifier: GPL-3.0-only * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include "common.h" #include "netstring.h" #include #include #include START_TEST(netstring_encode_test) { char buffer[16]; char* result; size_t length; result = netstring_encode("PostSRSd", 8, buffer, sizeof(buffer), &length); ck_assert_ptr_nonnull(result); ck_assert_uint_eq(length, 11); ck_assert_mem_eq(result, "8:PostSRSd,", length); result = netstring_encode("ItBarelyFits", 12, buffer, sizeof(buffer), &length); ck_assert_ptr_nonnull(result); ck_assert_uint_eq(length, 16); ck_assert_mem_eq(result, "12:ItBarelyFits,", length); result = netstring_encode("ItDoesNotFit!", 13, buffer, sizeof(buffer), &length); ck_assert_ptr_null(result); result = netstring_encode(NULL, 0, buffer, sizeof(buffer), &length); ck_assert_ptr_null(result); result = netstring_encode("", 0, buffer, sizeof(buffer), &length); ck_assert_ptr_nonnull(result); ck_assert_uint_eq(length, 3); ck_assert_mem_eq(result, "0:,", length); } END_TEST START_TEST(netstring_decode_test) { char buffer[17]; char* result; size_t length; result = netstring_decode("8:PostSRSd,", 12, buffer, sizeof(buffer), &length); ck_assert_ptr_nonnull(result); ck_assert_uint_eq(length, 8); ck_assert_mem_eq(result, "PostSRSd", length); result = netstring_decode("16:0123456789abcdef,", 21, buffer, sizeof(buffer), &length); ck_assert_ptr_nonnull(result); ck_assert_uint_eq(length, 16); ck_assert_mem_eq(result, "0123456789abcdef", length); result = netstring_decode("0:,", 4, buffer, sizeof(buffer), &length); ck_assert_ptr_nonnull(result); ck_assert_uint_eq(length, 0); result = netstring_decode(NULL, 0, buffer, sizeof(buffer), &length); ck_assert_ptr_null(result); result = netstring_decode("1a,", 4, buffer, sizeof(buffer), &length); ck_assert_ptr_null(result); result = netstring_decode("1:a*", 5, buffer, sizeof(buffer), &length); ck_assert_ptr_null(result); result = netstring_decode("0x1:a,", 7, buffer, sizeof(buffer), &length); ck_assert_ptr_null(result); result = netstring_decode("2:,", 3, buffer, sizeof(buffer), &length); ck_assert_ptr_null(result); result = netstring_decode("0:", 2, buffer, sizeof(buffer), &length); ck_assert_ptr_null(result); } END_TEST START_TEST(netstring_io_test) { int written; char* data; char buffer[16]; size_t length; char template[] = "netstring.XXXXXX"; int f = mkstemp(template); ck_assert_int_ge(f, 0); written = netstring_write(f, "PostSRSd", 8); ck_assert_int_eq(written, 11); written = netstring_write(f, "", 0); ck_assert_int_eq(written, 3); written = netstring_write(f, "0123456789abcdefgh", 17); ck_assert_int_eq(written, 21); ck_assert_int_eq(lseek(f, 0, SEEK_SET), 0); data = netstring_read(f, buffer, sizeof(buffer), &length); ck_assert_ptr_nonnull(data); ck_assert_uint_eq(length, 8); ck_assert_mem_eq(data, "PostSRSd", length); data = netstring_read(f, buffer, sizeof(buffer), &length); ck_assert_ptr_nonnull(data); ck_assert_uint_eq(length, 0); data = netstring_read(f, buffer, sizeof(buffer), &length); ck_assert_ptr_null(data); ck_assert_int_eq(lseek(f, 0, SEEK_SET), 0); ck_assert_int_eq(ftruncate(f, 0), 0); ck_assert_int_eq(write(f, "3:abc,4:abcde", 13), 13); ck_assert_int_eq(lseek(f, 0, SEEK_SET), 0); data = netstring_read(f, buffer, sizeof(buffer), &length); ck_assert_ptr_nonnull(data); ck_assert_uint_eq(length, 3); ck_assert_mem_eq(data, "abc", length); data = netstring_read(f, buffer, sizeof(buffer), &length); ck_assert_ptr_null(data); ck_assert_int_eq(lseek(f, 0, SEEK_SET), 0); ck_assert_int_eq(ftruncate(f, 0), 0); ck_assert_int_eq(write(f, "999:obviously too short,", 24), 24); ck_assert_int_eq(lseek(f, 0, SEEK_SET), 0); data = netstring_read(f, buffer, sizeof(buffer), &length); ck_assert_ptr_null(data); close(f); } END_TEST BEGIN_TEST_SUITE(netstring) ADD_TEST(netstring_encode_test) ADD_TEST(netstring_decode_test) ADD_TEST(netstring_io_test) END_TEST_SUITE() TEST_MAIN(netstring) roehling-postsrsd-24c678b/tests/unit/test_sha1.c000066400000000000000000000064151526152470400217350ustar00rootroot00000000000000/* PostSRSd - Sender Rewriting Scheme daemon for Postfix * Copyright 2012-2026 Timo Röhling * SPDX-License-Identifier: GPL-3.0-only * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include "common.h" #include "sha1.h" #include #include START_TEST(sha1_test_vectors) { char digest[20]; sha_digest(digest, "", 0); ck_assert_mem_eq(digest, "\xda\x39\xa3\xee\x5e\x6b\x4b\x0d\x32\x55\xbf\xef\x95\x60" "\x18\x90\xaf\xd8\x07\x09", 20); sha_digest(digest, "abc", 3); ck_assert_mem_eq(digest, "\xa9\x99\x3e\x36\x47\x06\x81\x6a\xba\x3e\x25\x71\x78\x50" "\xc2\x6c\x9c\xd0\xd8\x9d", 20); char* one_million_a = (char*)malloc(1000000); ck_assert_ptr_nonnull(one_million_a); memset(one_million_a, 'a', 1000000); sha_digest(digest, one_million_a, 1000000); ck_assert_mem_eq(digest, "\x34\xaa\x97\x3c\xd4\xc4\xda\xa4\xf6\x1e\xeb\x2b\xdb\xad" "\x27\x31\x65\x34\x01\x6f", 20); free(one_million_a); } END_TEST START_TEST(hmac_sha1_test_vectors) { srs_hmac_ctx_t ctx; char digest[20]; srs_hmac_init(&ctx, "topsecret", 9); srs_hmac_update(&ctx, "PostSRSd", 8); srs_hmac_fini(&ctx, digest); ck_assert_mem_eq(digest, "\xc7\xaa\x15\x9e\x2d\x8f\x36\x6d\xe9\x50\xe5\xf9\x36\xdc" "\x7f\x65\xea\x50\xd1\x13", 20); srs_hmac_init(&ctx, "Jefe", 4); srs_hmac_update(&ctx, "what do ya want for nothing?", 28); srs_hmac_fini(&ctx, digest); ck_assert_mem_eq(digest, "\xef\xfc\xdf\x6a\xe5\xeb\x2f\xa2\xd2\x74\x16\xd5\xf1\x84" "\xdf\x9c\x25\x9a\x7c\x79", 20); srs_hmac_init( &ctx, "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa", 80); srs_hmac_update(&ctx, "Test Using Larger Than Block-Size Key and Larger Than One " "Block-Size Data", 73); srs_hmac_fini(&ctx, digest); ck_assert_mem_eq(digest, "\xe8\xe9\x9d\x0f\x45\x23\x7d\x78\x6d\x6b\xba\xa7\x96\x5c" "\x78\x08\xbb\xff\x1a\x91", 20); } BEGIN_TEST_SUITE(sha1) ADD_TEST(sha1_test_vectors) ADD_TEST(hmac_sha1_test_vectors) END_TEST_SUITE() TEST_MAIN(sha1) roehling-postsrsd-24c678b/tests/unit/test_srs2.c000066400000000000000000000043261526152470400217710ustar00rootroot00000000000000/* PostSRSd - Sender Rewriting Scheme daemon for Postfix * Copyright 2012-2026 Timo Röhling * SPDX-License-Identifier: GPL-3.0-only * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include "common.h" #include "srs2.h" #include srs_t* create_srs_t() { srs_t* srs = srs_new(); srs->faketime = 1577836860; /* 2020-01-01 00:01:00 UTC */ srs_add_secret(srs, "tops3cr3t"); return srs; } START_TEST(srs2_forwarding) { srs_t* srs = create_srs_t(); char* output = NULL; int result; result = srs_forward_alloc(srs, &output, "test@example.com", "example.com"); ck_assert_int_eq(result, SRS_SUCCESS); ck_assert_str_eq(output, "test@example.com"); free(output); result = srs_forward_alloc(srs, &output, "test@otherdomain.com", "example.com"); ck_assert_int_eq(result, SRS_SUCCESS); ck_assert_str_eq(output, "SRS0=vmyz=2W=otherdomain.com=test@example.com"); free(output); result = srs_forward_alloc(srs, &output, "foo", "example.com"); ck_assert_int_eq(result, SRS_ENOSENDERATSIGN); srs_free(srs); } END_TEST START_TEST(srs2_reversing) { srs_t* srs = create_srs_t(); char* output = NULL; int result; result = srs_reverse_alloc(srs, &output, "test@example.com"); ck_assert_int_eq(result, SRS_ENOTSRSADDRESS); result = srs_reverse_alloc(srs, &output, "SRS0=vmyz=2W=otherdomain.com=test@example.com"); ck_assert_int_eq(result, SRS_SUCCESS); ck_assert_str_eq(output, "test@otherdomain.com"); free(output); srs_free(srs); } END_TEST BEGIN_TEST_SUITE(srs2) ADD_TEST(srs2_forwarding); ADD_TEST(srs2_reversing); END_TEST_SUITE() TEST_MAIN(srs2) roehling-postsrsd-24c678b/tests/unit/test_util.c000066400000000000000000000314141526152470400220530ustar00rootroot00000000000000/* PostSRSd - Sender Rewriting Scheme daemon for Postfix * Copyright 2012-2026 Timo Röhling * SPDX-License-Identifier: GPL-3.0-only * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include "common.h" #include "postsrsd_build_config.h" #include "util.h" #include #include #include #include #include static char pwd[500]; static char tmpdir[sizeof(pwd) + 7]; void setup_fs() { ck_assert_ptr_eq(getcwd(pwd, sizeof(pwd)), pwd); strcpy(tmpdir, pwd); strcat(tmpdir, "/XXXXXX"); ck_assert_ptr_eq(mkdtemp(tmpdir), tmpdir); ck_assert_int_eq(chdir(tmpdir), 0); } void teardown_fs() { ck_assert_int_eq(chdir(pwd), 0); ck_assert_int_eq(rmdir(tmpdir), 0); } START_TEST(util_file_exists) { ck_assert(!file_exists("testfile")); ck_assert(!file_exists("testdir")); ck_assert_int_eq(mkdir("testdir", 0755), 0); FILE* f = fopen("testfile", "w"); fwrite("Test", 4, 1, f); fclose(f); ck_assert(file_exists("testfile")); ck_assert(!file_exists("testdir")); ck_assert_int_eq(unlink("testfile"), 0); ck_assert_int_eq(rmdir("testdir"), 0); ck_assert(!file_exists("testfile")); } END_TEST START_TEST(util_directory_exists) { ck_assert(!directory_exists("testfile")); ck_assert(!directory_exists("testdir")); ck_assert_int_eq(mkdir("testdir", 0755), 0); FILE* f = fopen("testfile", "w"); fwrite("Test", 4, 1, f); fclose(f); ck_assert(directory_exists("testdir")); ck_assert(!directory_exists("testfile")); ck_assert_int_eq(unlink("testfile"), 0); ck_assert_int_eq(rmdir("testdir"), 0); ck_assert(!directory_exists("testdir")); } END_TEST #ifdef HAVE_SYS_INOTIFY_H static unsigned util_file_watch__expected_what = 0; static const char* util_file_watch__expected_path = NULL; static size_t util_file_watch__callback_count = 0; static void util_file_watch__callback(const char* path, unsigned what, size_t cookie) { if (what == FW_CHANGING) return; ++util_file_watch__callback_count; MAYBE_UNUSED(path); MAYBE_UNUSED(cookie); ck_assert_uint_eq(what, util_file_watch__expected_what); ck_assert_str_eq(path, util_file_watch__expected_path); } #endif START_TEST(util_file_watch) { #ifdef HAVE_SYS_INOTIFY_H static const char* TEST_FILE = "testfile"; file_watch_t* W = file_watch_create(); ck_assert_ptr_nonnull(W); FILE* f = fopen(TEST_FILE, "w"); fwrite("Test", 4, 1, f); fclose(f); ck_assert(file_watch_if_modified(W, TEST_FILE, util_file_watch__callback)); util_file_watch__expected_path = TEST_FILE; util_file_watch__expected_what = FW_MODIFIED; ck_assert_uint_eq(util_file_watch__callback_count, 0); f = fopen(TEST_FILE, "w+"); fseek(f, 0, SEEK_SET); file_watch_process_events(W); ck_assert_uint_eq(util_file_watch__callback_count, 0); fwrite("New", 3, 1, f); file_watch_process_events(W); ck_assert_uint_eq(util_file_watch__callback_count, 0); fclose(f); file_watch_process_events(W); ck_assert_uint_eq(util_file_watch__callback_count, 1); unlink(TEST_FILE); util_file_watch__expected_what = FW_DELETED; file_watch_process_events(W); ck_assert_uint_eq(util_file_watch__callback_count, 2); file_watch_destroy(W); #endif } END_TEST START_TEST(util_string_set) { char* s = NULL; string_set(&s, strdup("Test")); ck_assert_str_eq(s, "Test"); string_set(&s, NULL); ck_assert_ptr_null(s); } END_TEST static bool util_list__is_not_b(const void* value) { return strcmp((const char*)value, "b") != 0; } START_TEST(util_list) { list_t* L = list_create(); ck_assert_ptr_nonnull(L); ck_assert_uint_eq(list_size(L), 0); ck_assert_ptr_null(list_get(L, 0)); ck_assert(list_append(L, strdup("0"))); ck_assert_uint_eq(list_size(L), 1); ck_assert_str_eq((char*)list_get(L, 0), "0"); ck_assert_ptr_null(list_get(L, 1)); ck_assert(list_append(L, strdup("1"))); ck_assert(list_append(L, strdup("2"))); ck_assert(list_append(L, strdup("3"))); ck_assert(list_append(L, strdup("4"))); ck_assert(list_append(L, strdup("5"))); ck_assert_int_eq(list_find(L, string_equal, "0"), 0); ck_assert_int_eq(list_find(L, string_equal, "5"), 5); ck_assert_int_eq(list_find(L, string_equal, "6"), -1); ck_assert_uint_eq(list_size(L), 6); ck_assert_str_eq((char*)list_get(L, 0), "0"); ck_assert_str_eq((char*)list_get(L, 1), "1"); ck_assert_str_eq((char*)list_get(L, 2), "2"); ck_assert_str_eq((char*)list_get(L, 3), "3"); ck_assert_str_eq((char*)list_get(L, 4), "4"); ck_assert_str_eq((char*)list_get(L, 5), "5"); ck_assert_ptr_null(list_get(L, 6)); ck_assert(!list_remove_at(L, 6, free)); ck_assert(list_remove_at(L, 0, free)); ck_assert_uint_eq(list_size(L), 5); ck_assert_str_eq((char*)list_get(L, 0), "1"); ck_assert_str_eq((char*)list_get(L, 1), "2"); ck_assert_str_eq((char*)list_get(L, 2), "3"); ck_assert_str_eq((char*)list_get(L, 3), "4"); ck_assert_str_eq((char*)list_get(L, 4), "5"); ck_assert_ptr_null(list_get(L, 5)); ck_assert(list_remove_at(L, 2, free)); ck_assert_uint_eq(list_size(L), 4); ck_assert_str_eq((char*)list_get(L, 0), "1"); ck_assert_str_eq((char*)list_get(L, 1), "2"); ck_assert_str_eq((char*)list_get(L, 2), "4"); ck_assert_str_eq((char*)list_get(L, 3), "5"); ck_assert_ptr_null(list_get(L, 4)); ck_assert(!list_remove_at(L, 4, free)); ck_assert_uint_eq(list_size(L), 4); ck_assert_str_eq((char*)list_get(L, 0), "1"); ck_assert_str_eq((char*)list_get(L, 1), "2"); ck_assert_str_eq((char*)list_get(L, 2), "4"); ck_assert_str_eq((char*)list_get(L, 3), "5"); ck_assert_ptr_null(list_get(L, 4)); ck_assert(list_remove_at(L, 3, free)); ck_assert_uint_eq(list_size(L), 3); ck_assert_str_eq((char*)list_get(L, 0), "1"); ck_assert_str_eq((char*)list_get(L, 1), "2"); ck_assert_str_eq((char*)list_get(L, 2), "4"); ck_assert_ptr_null(list_get(L, 3)); list_clear(L, free); ck_assert_uint_eq(list_size(L), 0); ck_assert(list_append(L, strdup("a"))); ck_assert(list_append(L, strdup("b"))); ck_assert(list_append(L, strdup("c"))); ck_assert_str_eq((char*)list_get(L, 0), "a"); ck_assert_str_eq((char*)list_get(L, 1), "b"); ck_assert_str_eq((char*)list_get(L, 2), "c"); ck_assert_ptr_null(list_get(L, 3)); ck_assert_uint_eq(list_remove_if(L, util_list__is_not_b, free), 2); ck_assert_uint_eq(list_size(L), 1); ck_assert_str_eq((char*)list_get(L, 0), "b"); ck_assert_ptr_null(list_get(L, 1)); ck_assert(list_append(L, strdup("d"))); ck_assert(list_append(L, strdup("e"))); ck_assert(list_append(L, strdup("f"))); ck_assert_uint_eq(list_remove_if_value(L, string_equal, "b", free), 1); ck_assert_uint_eq(list_remove_if_value(L, string_equal, "e", free), 1); ck_assert_uint_eq(list_size(L), 2); ck_assert_str_eq((char*)list_get(L, 0), "d"); ck_assert_str_eq((char*)list_get(L, 1), "f"); ck_assert_ptr_null(list_get(L, 2)); list_destroy(L, free); list_destroy(NULL, free); } END_TEST START_TEST(util_b32h_encode) { char buffer[41]; char* b32h; b32h = b32h_encode("", 0, buffer, sizeof(buffer)); ck_assert_ptr_nonnull(b32h); ck_assert_str_eq(b32h, ""); b32h = b32h_encode("-PostSRSd-", 10, buffer, sizeof(buffer)); ck_assert_ptr_nonnull(b32h); ck_assert_str_eq(b32h, "5L86USRKAD956P1D"); ck_assert_ptr_null(b32h_encode("BufferTooSmall!", 15, buffer, 24)); b32h = b32h_encode("BuffLargeEnough", 15, buffer, 25); ck_assert_ptr_nonnull(b32h); ck_assert_str_eq(b32h, "89QMCPICC5P6EPA5DPNNAPR8"); b32h = b32h_encode("a", 1, buffer, sizeof(buffer)); ck_assert_ptr_nonnull(b32h); ck_assert_str_eq(b32h, "C4======"); b32h = b32h_encode("ab", 2, buffer, sizeof(buffer)); ck_assert_ptr_nonnull(b32h); ck_assert_str_eq(b32h, "C5H0===="); b32h = b32h_encode("abc", 3, buffer, sizeof(buffer)); ck_assert_ptr_nonnull(b32h); ck_assert_str_eq(b32h, "C5H66==="); b32h = b32h_encode("abcd", 4, buffer, sizeof(buffer)); ck_assert_ptr_nonnull(b32h); ck_assert_str_eq(b32h, "C5H66P0="); b32h = b32h_encode("abcde", 5, buffer, sizeof(buffer)); ck_assert_ptr_nonnull(b32h); ck_assert_str_eq(b32h, "C5H66P35"); b32h = b32h_encode("\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80", 10, buffer, sizeof(buffer)); ck_assert_ptr_nonnull(b32h); ck_assert_str_eq(b32h, "G2081040G2081040"); } END_TEST START_TEST(util_dotlock) { #if defined(LOCK_EX) && defined(LOCK_NB) for (int i = 0; i < 2; ++i) { int handle = lock_acquire("testfile"); ck_assert_int_gt(handle, 0); ck_assert_int_lt(lock_acquire("testfile"), 0); lock_release("testfile", handle); } #endif } END_TEST START_TEST(util_domain_set) { struct domain_set* D = domain_set_create(); ck_assert(!domain_set_contains(D, "example.com")); ck_assert(!domain_set_contains(D, ".example.com")); ck_assert(!domain_set_contains(D, "exam.com")); domain_set_add(D, "example.com"); domain_set_add(D, "www.example.com"); ck_assert(domain_set_contains(D, "example.com")); ck_assert(domain_set_contains(D, "EXAMPLE.COM")); ck_assert(domain_set_contains(D, "www.example.com")); ck_assert(!domain_set_contains(D, ".example.com")); ck_assert(!domain_set_contains(D, "mail.example.com")); ck_assert(!domain_set_contains(D, "exam.com")); domain_set_add(D, ".example.com"); ck_assert(domain_set_contains(D, "example.com")); ck_assert(domain_set_contains(D, ".example.com")); ck_assert(domain_set_contains(D, "www.example.com")); ck_assert(domain_set_contains(D, "mail.example.com")); ck_assert(!domain_set_contains(D, "exam.com")); domain_set_add(D, ".my-examples.com"); ck_assert(!domain_set_contains(D, "my-examples.com")); ck_assert(domain_set_contains(D, "another.one.of.my-examples.com")); domain_set_add(D, "invalid$domain.net"); ck_assert(!domain_set_contains(D, "invalid$domain.net")); domain_set_add( D, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-0123456789."); ck_assert(domain_set_contains( D, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-0123456789.")); // Truncation occurs after 511 octets ck_assert(!domain_set_add( D, "mail.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.com")); ck_assert(!domain_set_contains( D, "mail.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.com")); domain_set_destroy(D); } START_TEST(util_log) { char buffer[2049]; memset(buffer, 'a', sizeof(buffer) - 1); buffer[sizeof(buffer) - 1] = 0; log_enable_syslog(); log_info("Hello %s", "World"); log_warn("Excessively long message: %s", buffer); log_error("Error?"); } END_TEST BEGIN_TEST_SUITE(util) ADD_TEST_CASE_WITH_UNCHECKED_FIXTURE(fs, setup_fs, teardown_fs) ADD_TEST_TO_TEST_CASE(fs, util_file_exists) ADD_TEST_TO_TEST_CASE(fs, util_directory_exists) ADD_TEST_TO_TEST_CASE(fs, util_dotlock) ADD_TEST_TO_TEST_CASE(fs, util_file_watch) ADD_TEST(util_string_set) ADD_TEST(util_list); ADD_TEST(util_b32h_encode) ADD_TEST(util_domain_set) ADD_TEST(util_log) END_TEST_SUITE() TEST_MAIN(util)