pax_global_header00006660000000000000000000000064147764767640014546gustar00rootroot0000000000000052 comment=a20e0b646c87f13cc013dd8aa8c221283a5a06b1 roehling-postsrsd-aefddb9/000077500000000000000000000000001477647676400160745ustar00rootroot00000000000000roehling-postsrsd-aefddb9/.clang-format000066400000000000000000000014211477647676400204450ustar00rootroot00000000000000BasedOnStyle: 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-aefddb9/.cmake-format.json000066400000000000000000000047121477647676400214170ustar00rootroot00000000000000{ "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-aefddb9/.github/000077500000000000000000000000001477647676400174345ustar00rootroot00000000000000roehling-postsrsd-aefddb9/.github/workflows/000077500000000000000000000000001477647676400214715ustar00rootroot00000000000000roehling-postsrsd-aefddb9/.github/workflows/bsd.yml000066400000000000000000000015751477647676400227740ustar00rootroot00000000000000# Copyright 2023 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: BSD on: push: branches: - main pull_request: branches: - main permissions: contents: read jobs: freebsd: runs-on: ubuntu-latest name: FreeBSD steps: - uses: actions/checkout@v4 - uses: vmactions/freebsd-vm@v1 with: usesh: true prepare: | pkg install -y cmake git gmake autoconf automake run: | mkdir _build cd _build cmake .. -DDEVELOPER_BUILD=ON -DWITH_SQLITE=ON -DWITH_REDIS=ON && gmake VERBOSE=ON && ctest --output-on-failure roehling-postsrsd-aefddb9/.github/workflows/ci.yml000066400000000000000000000041551477647676400226140ustar00rootroot00000000000000# 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. # name: Continuous Integration on: push: branches: - main pull_request: branches: - main permissions: contents: read jobs: test: runs-on: ubuntu-latest strategy: matrix: milter: [MILTER=OFF, MILTER=ON] sqlite: [SQLITE=OFF, SQLITE=ON] redis: [REDIS=OFF, REDIS=ON] deps: [vendored-deps, system-deps] steps: - uses: actions/checkout@v4 - name: Install dependencies run: | sudo apt-get update -qq sudo apt-get install -y cmake postfix redis ${{ matrix.deps == 'system-deps' && 'check libconfuse-dev libhiredis-dev libmilter-dev libsqlite3-dev' || '' }} - name: Build PostSRSd run: | mkdir _build cd _build cmake .. -DDEVELOPER_BUILD=ON -DWITH_${{ matrix.milter }} -DWITH_${{ matrix.sqlite }} -DWITH_${{ matrix.redis }} ${{ matrix.deps == 'system-deps' && '-DFETCHCONTENT_FULLY_DISCONNECTED=ON -DFETCHCONTENT_TRY_FIND_PACKAGE_MODE=ALWAYS' || '' }} cmake --build . --verbose - name: Run tests run: | cd _build ctest --output-on-failure - name: Install and start PostSRSd daemon run: | cd _build sudo make install sed -e 's/^#srs-domain.*/srs-domain = "example.com"/' /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 - name: Test Postfix integration run: | 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 roehling-postsrsd-aefddb9/.github/workflows/release.yml000066400000000000000000000024131477647676400236340ustar00rootroot00000000000000# Copyright 2023 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: Create Github release on: push: tags: - "2.*" permissions: contents: write jobs: release: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Install dependencies run: | sudo apt-get update -qq sudo apt-get install -y cmake musl-dev musl-tools - name: Build PostSRSd run: | mkdir _build cd _build cmake .. -DCMAKE_BUILD_TYPE=MinSizeRel -DCMAKE_C_COMPILER=musl-gcc -DCMAKE_EXE_LINKER_FLAGS=-static -DBUILD_TESTING=OFF -DWITH_SQLITE=ON -DWITH_REDIS=ON -DGENERATE_SRS_SECRET=OFF make VERBOSE=ON - name: Install PostSRSd run: | cd _build make install DESTDIR=$PWD/_install - name: Create TAR run: tar -C_build/_install -cvzf postsrsd-x86_64-musl.tar.gz ./ - name: Create release uses: softprops/action-gh-release@v1 with: files: postsrsd-x86_64-musl.tar.gz roehling-postsrsd-aefddb9/.pre-commit-config.yaml000066400000000000000000000011701477647676400223540ustar00rootroot00000000000000# 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: v5.0.0 hooks: - id: trailing-whitespace - id: end-of-file-fixer - id: check-yaml - id: check-added-large-files - repo: https://github.com/pre-commit/mirrors-clang-format rev: v20.1.0 hooks: - id: clang-format - repo: https://github.com/psf/black rev: 25.1.0 hooks: - id: black - repo: https://github.com/cheshirekow/cmake-format-precommit rev: v0.6.13 hooks: - id: cmake-format roehling-postsrsd-aefddb9/CHANGELOG.rst000066400000000000000000000145001477647676400201150ustar00rootroot00000000000000.. PostSRSd - Sender Rewriting Scheme daemon for Postfix Copyright 2012-2022 Timo Röhling SPDX-License-Identifier: GPL-3.0-only ######### Changelog ######### 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 `_) 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-aefddb9/CMakeLists.txt000066400000000000000000000363071477647676400206450ustar00rootroot00000000000000# 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 . # cmake_minimum_required(VERSION 3.14...3.29) project( postsrsd VERSION 2.0.11 LANGUAGES C DESCRIPTION "Sender Rewriting Scheme daemon for Postfix" HOMEPAGE_URL "https://github.com/roehling/postsrsd" ) if(CMAKE_VERSION VERSION_LESS 3.21.0) # Workaround for https://gitlab.kitware.com/cmake/cmake/-/issues/22234 if(POLICY CMP0082) cmake_policy(SET CMP0082 OLD) endif() endif() 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(WITH_MILTER "Enable SRS rewrite via Milter (requires libmilter)" OFF) add_feature_info(WITH_MILTER WITH_MILTER "run PostSRSd as milter") 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(TESTS_WITH_ASAN "Run test suite with AddressSanitizer" ON) option(DEVELOPER_BUILD "Add strict compiler options for development only" 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" ) 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(CHROOTABLE_DATADIR STREQUAL "") set(CHROOTABLE_DATADIR ".") endif() else() set(CHROOTABLE_DATADIR "${POSTSRSD_DATADIR}") endif() mark_as_advanced( TESTS_WITH_ASAN GENERATE_SRS_SECRET DEVELOPER_BUILD SYSTEMD_UNITDIR POSTSRSD_CONFIGDIR POSTSRSD_CHROOTDIR POSTSRSD_DATADIR POSTSRSD_USER ) FetchContent_Declare( Confuse URL https://github.com/libconfuse/libconfuse/releases/download/v3.3/confuse-3.3.tar.gz URL_HASH SHA3_256=da895d91a7755941872e73ff6522fd16810f1599862990df569459a0eee94515 ) FetchContent_Declare( Hiredis GIT_REPOSITORY https://github.com/redis/hiredis GIT_TAG c14775b4e48334e0262c9f168887578f4a368b5d ) FetchContent_Declare( LibMilter GIT_REPOSITORY https://github.com/roehling/libmilter GIT_TAG 3661f3c5ac5e47205f26775031d2ac276d6d47ca ) FetchContent_Declare( sqlite3 URL https://sqlite.org/2023/sqlite-amalgamation-3410200.zip URL_HASH SHA3_256=c51ca72411b8453c64e0980be23bc9b9530bdc3ec1513e06fbf022ed0fd02463 ) 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 ) set(saved_CMAKE_REQUIRED_DEFINITIONS "${CMAKE_REQUIRED_DEFINITIONS}") list(APPEND CMAKE_REQUIRED_DEFINITIONS "-D_GNU_SOURCE" "-D_FILE_OFFSET_BITS=64") check_include_file(alloca.h HAVE_ALLOCA_H) check_include_file(errno.h HAVE_ERRNO_H) check_include_file(fcntl.h HAVE_FCNTL_H) check_include_file(grp.h HAVE_GRP_H) check_include_file(netdb.h HAVE_NETDB_H) check_include_file(poll.h HAVE_POLL_H) check_include_file(pwd.h HAVE_PWD_H) check_include_file(signal.h HAVE_SIGNAL_H) check_include_file(sys/file.h HAVE_SYS_FILE_H) check_include_file(sys/inotify.h HAVE_SYS_INOTIFY_H) check_include_file(sys/socket.h HAVE_SYS_SOCKET_H) check_include_file(sys/stat.h HAVE_SYS_STAT_H) check_include_file(sys/time.h HAVE_SYS_TIME_H) check_include_file(sys/types.h HAVE_SYS_TYPES_H) check_include_file(sys/un.h HAVE_SYS_UN_H) check_include_file(sys/wait.h HAVE_SYS_WAIT_H) check_include_file(syslog.h HAVE_SYSLOG_H) check_include_file(time.h HAVE_TIME_H) check_include_file(unistd.h HAVE_UNISTD_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_symbol_exists(strcasecmp strings.h HAVE_STRCASECMP) check_symbol_exists(_stricmp string.h HAVE__STRICMP) check_symbol_exists(strncasecmp strings.h HAVE_STRNCASECMP) check_symbol_exists(_strnicmp string.h HAVE__STRNICMP) 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() set(THREADS_PREFER_PTHREAD_FLAG TRUE) find_package(Threads QUIET) add_autotools_dependency( Confuse LIBRARY_NAME confuse EXPORTED_TARGET Confuse::Confuse ) if(WITH_REDIS) set(DISABLE_TESTS ON CACHE BOOL "" FORCE ) set(BUILD_SHARED_LIBS OFF CACHE BOOL "" FORCE ) FetchContent_MakeAvailable(Hiredis) 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_MILTER) FetchContent_MakeAvailable(LibMilter) if(IS_DIRECTORY "${libmilter_SOURCE_DIR}") string(TOLOWER "${CMAKE_SYSTEM_NAME}" lc_system) set(SM_OS_H "${libmilter_SOURCE_DIR}/include/sm/os/sm_os_${lc_system}.h" ) if(EXISTS "${SM_OS_H}") execute_process( COMMAND "${CMAKE_COMMAND}" -E copy_if_different "${SM_OS_H}" "${libmilter_SOURCE_DIR}/include/sm/sm_os.h" ) add_library( milter STATIC "${libmilter_SOURCE_DIR}/errstring.c" "${libmilter_SOURCE_DIR}/strl.c" "${libmilter_SOURCE_DIR}/comm.c" "${libmilter_SOURCE_DIR}/engine.c" "${libmilter_SOURCE_DIR}/handler.c" "${libmilter_SOURCE_DIR}/listener.c" "${libmilter_SOURCE_DIR}/main.c" "${libmilter_SOURCE_DIR}/monitor.c" "${libmilter_SOURCE_DIR}/signal.c" "${libmilter_SOURCE_DIR}/smfi.c" "${libmilter_SOURCE_DIR}/sm_gethost.c" "${libmilter_SOURCE_DIR}/worker.c" ) target_compile_definitions( milter PRIVATE NOT_SENDMAIL=1 sm_snprintf=snprintf ) target_include_directories( milter PRIVATE "${libmilter_SOURCE_DIR}/smapp" PUBLIC "${libmilter_SOURCE_DIR}/include" INTERFACE "${libmilter_SOURCE_DIR}/include/libmilter" ) if(TARGET Threads::Threads) target_link_libraries(milter PRIVATE Threads::Threads) endif() add_library(LibMilter::LibMilter ALIAS milter) else() message( FATAL_ERROR "Missing support for ${CMAKE_SYSTEM_NAME} for LibMilter" ) endif() 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=$,2,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 ) if(WITH_MILTER AND TARGET Threads::Threads) target_link_libraries(sqlite3 PRIVATE Threads::Threads) endif() add_library(sqlite3::sqlite3 ALIAS sqlite3) target_link_libraries(sqlite3 PUBLIC ${CMAKE_DL_LIBS}) endif() 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 Confuse::Confuse $<$:sqlite3::sqlite3> $<$:${HIREDIS_TARGET}> $<$:LibMilter::LibMilter> ${LIBSOCKET} ${LIBNSL} ) 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}" ) 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 ) 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(BUILD_TESTING) FetchContent_MakeAvailable(Check) 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() feature_summary(WHAT ENABLED_FEATURES DISABLED_FEATURES) 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-aefddb9/LICENSES/000077500000000000000000000000001477647676400173015ustar00rootroot00000000000000roehling-postsrsd-aefddb9/LICENSES/BSD-3-Clause.txt000066400000000000000000000026271477647676400220330ustar00rootroot00000000000000Redistribution 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-aefddb9/LICENSES/FSFAP.txt000066400000000000000000000003401477647676400206760ustar00rootroot00000000000000Copying 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-aefddb9/LICENSES/FSFUL.txt000066400000000000000000000001321477647676400207150ustar00rootroot00000000000000The copyright holder gives unlimited permission to copy, distribute and modify this file. roehling-postsrsd-aefddb9/LICENSES/GPL-3.0-only.txt000066400000000000000000001045131477647676400217450ustar00rootroot00000000000000 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-aefddb9/README.rst000066400000000000000000000203141477647676400175630ustar00rootroot00000000000000.. PostSRSd - Sender Rewriting Scheme daemon for Postfix Copyright 2012-2023 Timo Röhling SPDX-License-Identifier: GPL-3.0-only ======== PostSRSd ======== Sender Rewriting Scheme daemon for Postfix 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. 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. In particular, we are currently looking for a new Debian maintainer (`#145 `_). .. _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.14 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``. - libMilter_ is needed only if you wish to configure PostSRSd as milter; enable it with ``-DWITH_MILTER=ON``. - check_ is needed if you want to build and run the unit test suite; otherwise disable it with ``-DBUILD_TESTING=OFF``. - Python_ is needed for the optional blackbox tests. 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 .. _libMilter: https://github.com/jons/libmilter .. _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 Experimental Milter Support ~~~~~~~~~~~~~~~~~~~~~~~~~~~ PostSRSd 2.x has added optional support for the Milter protocol. If you enabled it at compile time, 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 Note that the Milter code is less tested and should be considered experimental for now and not ready for production. Feel free to report bugs or open pull requests if you try it out, though. 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?** This is not supported currently but might be added to the milter at some point in the future. If PostSRSd is integrated with Postfix using the ``canonical`` maps, it is almost impossible, because the canonicalization occurs before any routing decision is made. Only if you happen to use separate Postfix server instances for forwarding and local delivery, you can trivially configure PostSRSd this way. * **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?** If PostSRSd is integrated with Postfix using the ``canonical`` maps, this is not possible, because PostSRSd processes sender and recipient addresses separately and never sees the email context. If PostSRSd is configured as milter, it might be theoretically possible, but it is not supported yet, for two reasons: 1. It is not trivial to implement and conflicts with other interesting features such as rewriting only if the email is actually forwarded. 2. The SRS address is normally not visible to the recipient anyway. 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. roehling-postsrsd-aefddb9/REUSE.toml000066400000000000000000000020761477647676400176610ustar00rootroot00000000000000version = 1 SPDX-PackageName = "PostSRSd" SPDX-PackageSupplier = "Timo Röhling " SPDX-PackageDownloadLocation = "https://github.com/roehling/postsrsd" [[annotations]] path = "**" precedence = "aggregate" SPDX-FileCopyrightText = "2012-2023, 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-2023, Timo Röhling " SPDX-License-Identifier = "FSFUL" [[annotations]] path = [".github/**", "cmake/**"] precedence = "aggregate" SPDX-FileCopyrightText = "2022-2023, 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-2023, Timo Röhling "] SPDX-License-Identifier = "BSD-3-Clause" roehling-postsrsd-aefddb9/cmake/000077500000000000000000000000001477647676400171545ustar00rootroot00000000000000roehling-postsrsd-aefddb9/cmake/FindCheck.cmake000066400000000000000000000035761477647676400220070ustar00rootroot00000000000000# 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-aefddb9/cmake/FindConfuse.cmake000066400000000000000000000020231477647676400223560ustar00rootroot00000000000000# 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_CONFUSE QUIET libconfuse) endif() find_path(Confuse_INCLUDE_DIR confuse.h HINTS ${PC_CONFUSE_INCLUDE_DIRS}) find_library(Confuse_LIBRARY confuse HINTS ${PC_CONFUSE_LIBRARY_DIRS}) find_package_handle_standard_args( Confuse FOUND_VAR Confuse_FOUND REQUIRED_VARS Confuse_INCLUDE_DIR Confuse_LIBRARY ) if(Confuse_FOUND AND NOT TARGET Confuse::Confuse) add_library(Confuse::Confuse UNKNOWN IMPORTED) set_target_properties( Confuse::Confuse PROPERTIES IMPORTED_LOCATION "${Confuse_LIBRARY}" INTERFACE_INCLUDE_DIRECTORIES "${Confuse_INCLUDE_DIR}" ) endif() roehling-postsrsd-aefddb9/cmake/FindHiredis.cmake000066400000000000000000000020641477647676400223500ustar00rootroot00000000000000# 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-aefddb9/cmake/FindLibMilter.cmake000066400000000000000000000021151477647676400226410ustar00rootroot00000000000000# 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_MILTER QUIET milter) endif() find_path( LibMilter_INCLUDE_DIR mfapi.h PATH_SUFFIXES libmilter HINTS ${PC_MILTER_INCLUDE_DIRS} ) find_library(LibMilter_LIBRARY milter HINTS ${PC_MILTER_LIBRARY_DIRS}) find_package_handle_standard_args( LibMilter FOUND_VAR LibMilter_FOUND REQUIRED_VARS LibMilter_INCLUDE_DIR LibMilter_LIBRARY ) if(LibMilter_FOUND AND NOT TARGET LibMilter::LibMilter) add_library(LibMilter::LibMilter UNKNOWN IMPORTED) set_target_properties( LibMilter::LibMilter PROPERTIES IMPORTED_LOCATION "${LibMilter_LIBRARY}" INTERFACE_INCLUDE_DIRECTORIES "${LibMilter_INCLUDE_DIR}" ) endif() roehling-postsrsd-aefddb9/cmake/Findsqlite3.cmake000066400000000000000000000020201477647676400223350ustar00rootroot00000000000000# 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-aefddb9/cmake/utils.cmake000066400000000000000000000071741477647676400213270ustar00rootroot00000000000000# Copyright 2022-2023 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(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) 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) set(${var} "${unitdir}" PARENT_SCOPE ) else() set(${var} "/usr/lib/systemd/system" PARENT_SCOPE ) endif() 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) set(${var} "${sysusersdir}" PARENT_SCOPE ) else() set(${var} "/usr/lib/sysusers.d" PARENT_SCOPE ) endif() else() set(${var} "/etc/sysusers.d" PARENT_SCOPE ) endif() endfunction() roehling-postsrsd-aefddb9/data/000077500000000000000000000000001477647676400170055ustar00rootroot00000000000000roehling-postsrsd-aefddb9/data/postsrsd.conf.in000066400000000000000000000160371477647676400221510ustar00rootroot00000000000000# PostSRSd example configuration file # Copyright 2022-2023 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" } # 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 = "@POSTSRSD_CONFIGDIR@/@PROJECT_NAME@.domains" # #domains-file = # 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. # # Example: # srs-domain = "srs.example.com" # #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 # socketmap = unix:/var/spool/postfix/srs # Socketmap connection keep-alive timeout. # After PostSRSd has served a socketmap 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. # # Examples: # keep-alive = 30 # keep-alive = 30 # 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 # #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 # 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 reads this database after it chroots and drops root privileges, so # the actual filename is the chroot directory joined with this filename. # # Examples: # envelope-database = "sqlite:@CHROOTABLE_DATADIR@/senders.db" # envelope-database = "redis:localhost:6379" # #envelope-database = "sqlite:@CHROOTABLE_DATADIR@/senders.db" # 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. # # Example: # secrets-file = "@POSTSRSD_CONFIGDIR@/@PROJECT_NAME@.secret" # secrets-file = "@POSTSRSD_CONFIGDIR@/@PROJECT_NAME@.secret" # 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. # 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. # 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. # 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. # 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. # # Example: # unprivileged-user = "nobody" # 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. # # Example: # chroot-dir = "@CMAKE_INSTALL_FULL_LOCALSTATEDIR@/lib/@PROJECT_NAME@" # 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. # syslog = off # Debug # This option makes PostSRSd more verbose in its logging, which can be useful # to hunt down configuration problems. # debug = off roehling-postsrsd-aefddb9/data/postsrsd.service.in000066400000000000000000000006751477647676400226650ustar00rootroot00000000000000# PostSRSd systemd service file # Copyright 2022-2023 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] ExecStart=@CMAKE_INSTALL_FULL_SBINDIR@/postsrsd -C @POSTSRSD_CONFIGDIR@/@PROJECT_NAME@.conf [Install] WantedBy=multi-user.target roehling-postsrsd-aefddb9/data/sysusers.conf.in000066400000000000000000000003611477647676400221610ustar00rootroot00000000000000# 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-aefddb9/doc/000077500000000000000000000000001477647676400166415ustar00rootroot00000000000000roehling-postsrsd-aefddb9/doc/packaging.rst000066400000000000000000000071741477647676400213300ustar00rootroot00000000000000.. PostSRSd - Sender Rewriting Scheme daemon for Postfix Copyright 2012-2023 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 download the sources of its dependencies at configure time, build them, and link them statically into the executable. Starting with CMake 3.24, it is possible to tweak this process and use system libraries by passing ``-DFETCHCONTENT_TRY_FIND_PACKAGE_MODE=ALWAYS`` to the CMake invocation. .. _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. - ``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. - ``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. .. _GNUInstallDirs: https://cmake.org/cmake/help/latest/module/GNUInstallDirs.html roehling-postsrsd-aefddb9/doc/postsrsd.conf000066400000000000000000000156711477647676400214030ustar00rootroot00000000000000# PostSRSd example configuration file # Copyright 2022-2023 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" } # 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" # #domains-file = # 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. # # Example: # srs-domain = "srs.example.com" # #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 # socketmap = unix:/var/spool/postfix/srs # Socketmap connection keep-alive timeout. # After PostSRSd has served a socketmap 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. # # Examples: # keep-alive = 30 # keep-alive = 30 # 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 # #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 # 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 reads this database after it chroots and drops root privileges, so # the actual filename is the chroot directory joined with this filename. # # Examples: # envelope-database = "sqlite:./senders.db" # envelope-database = "redis:localhost:6379" # #envelope-database = "sqlite:./senders.db" # 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. # # Example: # secrets-file = "/usr/local/etc/postsrsd.secret" # secrets-file = "/usr/local/etc/postsrsd.secret" # 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. # 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. # 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. # 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. # 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. # # Example: # 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. # # Example: # 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. # syslog = off # Debug # This option makes PostSRSd more verbose in its logging, which can be useful # to hunt down configuration problems. # debug = off roehling-postsrsd-aefddb9/src/000077500000000000000000000000001477647676400166635ustar00rootroot00000000000000roehling-postsrsd-aefddb9/src/config.c000066400000000000000000000274111477647676400203010ustar00rootroot00000000000000/* 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 . */ #include "config.h" #include "postsrsd_build_config.h" #include "util.h" #include #include #include #include #include #include #ifndef HAVE_STRCASECMP # ifdef HAVE__STRICMP # define strcasecmp _stricmp # endif #endif 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 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(*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 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_MILTER) "\n" "This binary has been compiled with\n" # ifdef WITH_SQLITE "* SQLite database storage support\n" # endif # ifdef WITH_REDIS "* Redis database storage support\n" # endif # ifdef WITH_MILTER "* Milter support (experimental)\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_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_STR("milter", NULL, CFGF_NODEFAULT), 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("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, "keep-alive", validate_uint); 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)) set_string(&config_file, strdup(DEFAULT_CONFIG_FILE)); while ((opt = getopt(argc, argv, "C:c:Dhp:u:v")) != -1) { switch (opt) { case '?': return 0; case 'C': set_string(&config_file, strdup(optarg)); break; case 'c': set_string(&chroot_dir, strdup(optarg)); break; case 'D': daemonize = 1; break; case 'h': show_help(); exit(0); break; case 'p': set_string(&pid_file, strdup(optarg)); break; case 'u': set_string(&unprivileged_user, strdup(optarg)); break; case 'v': puts(POSTSRSD_VERSION); exit(0); break; default: break; } } if (config_file) { 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; } set_string(&config_file, NULL); } if (pid_file) { cfg_setstr(cfg, "pid-file", pid_file); set_string(&pid_file, NULL); } if (unprivileged_user) { cfg_setstr(cfg, "unprivileged-user", unprivileged_user); set_string(&unprivileged_user, NULL); } if (chroot_dir) { cfg_setstr(cfg, "chroot-dir", chroot_dir); set_string(&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) { srs_t* srs = srs_new(); srs_set_alwaysrewrite(srs, cfg_getbool(cfg, "always-rewrite")); srs_set_hashlength(srs, cfg_getint(cfg, "hash-length")); srs_set_hashmin(srs, cfg_getint(cfg, "hash-minimum")); srs_set_separator(srs, cfg_getstr(cfg, "separator")[0]); char* secrets_file = cfg_getstr(cfg, "secrets-file"); if (secrets_file && secrets_file[0]) { FILE* f = fopen(secrets_file, "r"); if (f) { char buffer[1024]; char* secret; while ((secret = fgets(buffer, sizeof(buffer), f)) != NULL) { secret = strtok(secret, "\r\n"); if (secret && secret[0]) 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 (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 (domain && domain[0]) *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 (domain && domain[0]) { domain_set_add(*local_domains, domain); if (*srs_domain == NULL) *srs_domain = strdup(domain[0] == '.' ? domain + 1 : domain); } } char* domains_file = cfg_getstr(cfg, "domains-file"); if (domains_file && domains_file[0]) { FILE* f = fopen(domains_file, "r"); if (f) { char buffer[1024]; char* end; while ((domain = fgets(buffer, sizeof(buffer), f)) != NULL) { domain = strtok(domain, "\r\n"); if (domain == NULL) continue; while (isspace(domain[0])) ++domain; end = strchr(domain, '#'); if (end != NULL) *end = 0; end = domain + strlen(domain); while (end != domain && isspace(*(end - 1))) *--end = 0; if (domain[0] == 0) continue; if (is_valid_domain_name(domain)) { domain_set_add(*local_domains, 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; } } return true; fail: domain_set_destroy(*local_domains); *local_domains = NULL; free(*srs_domain); *srs_domain = NULL; return false; } roehling-postsrsd-aefddb9/src/config.h000066400000000000000000000022101477647676400202740ustar00rootroot00000000000000/* PostSRSd - Sender Rewriting Scheme daemon for Postfix * Copyright 2012-2022 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); #endif roehling-postsrsd-aefddb9/src/database.c000066400000000000000000000232551477647676400206020ustar00rootroot00000000000000/* 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 . */ #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) { value = strdup((const char*)sqlite3_column_text(db->read_stmt, 0)); } 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 = strdup(reply->str); } 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-aefddb9/src/database.h000066400000000000000000000022441477647676400206020ustar00rootroot00000000000000/* PostSRSd - Sender Rewriting Scheme daemon for Postfix * Copyright 2012-2022 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-aefddb9/src/endpoint.c000066400000000000000000000136431477647676400206560ustar00rootroot00000000000000/* 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 . */ #include "endpoint.h" #include "postsrsd_build_config.h" #include "util.h" #include #include #ifdef HAVE_ERRNO_H # include #endif #ifdef HAVE_SYS_TYPES_H # include #endif #ifdef HAVE_SYS_SOCKET_H # include #endif #ifdef HAVE_SYS_STAT_H # include #endif #ifdef HAVE_SYS_UN_H # include #endif #ifdef HAVE_NETDB_H # include #endif #ifdef HAVE_UNISTD_H # include #endif #if defined(AF_UNIX) # define HAVE_UNIX_SOCKETS 1 #endif #if defined(HAVE_NETDB_H) && defined(AF_UNSPEC) && defined(AF_INET) \ && defined(AF_INET6) # define HAVE_INET_SOCKETS 1 #endif #ifndef SO_REUSEPORT # define SO_REUSEPORT SO_REUSEADDR #endif #define POSTSRSD_SOCKET_LISTEN_QUEUE 16 #ifdef HAVE_UNIX_SOCKETS static int create_unix_socket(const char* path) { struct sockaddr_un sa; if (NULL_OR_EMPTY_STRING(path)) { log_error("expected file path for unix socket"); return -1; } if (acquire_lock(path) > 0) unlink(path); int sock = socket(AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0); if (sock < 0) goto fail; sa.sun_family = AF_UNIX; memset(sa.sun_path, 0, sizeof(sa.sun_path)); strncpy(sa.sun_path, path, sizeof(sa.sun_path) - 1); if (bind(sock, (const struct sockaddr*)&sa, sizeof(struct sockaddr_un)) < 0) goto fail; if (chmod(path, 0666) < 0) goto fail; if (listen(sock, POSTSRSD_SOCKET_LISTEN_QUEUE) < 0) goto fail; return sock; fail: log_perror(errno, NULL); if (sock >= 0) close(sock); return -1; } #endif #ifdef HAVE_INET_SOCKETS static int create_inet_sockets(char* addr, int family, int max_fds, int* fds) { const int one = 1; struct addrinfo hints, *ai; 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 -1; } ++addr; } *addr++ = 0; if (*addr != ':') { log_error("expected ':' separator in socket address"); return -1; } 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 -1; } 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 -1; } int sock = -1, count = 0; for (struct addrinfo* it = ai; it; it = it->ai_next) { if (max_fds == 0) break; sock = socket(it->ai_family, it->ai_socktype | SOCK_NONBLOCK | SOCK_CLOEXEC, it->ai_protocol); if (sock < 0) goto fail; 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; *fds++ = sock; max_fds--; count++; continue; fail: err = errno; log_perror(err, NULL); if (sock >= 0) close(sock); } freeaddrinfo(ai); if (count == 0 && err != 0) return -1; return count; } #endif int endpoint_create(const char* s, int max_fds, int* fds) { MAYBE_UNUSED(fds); if (max_fds < 1) return 0; #ifdef HAVE_UNIX_SOCKETS 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) { int fd = create_unix_socket(path); if (fd < 0) { log_error("failed to create endpoint '%s'", s); return -1; } *fds = fd; return 1; } #endif #ifdef HAVE_INET_SOCKETS 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) { int ret = create_inet_sockets(addr, family, max_fds, fds); free(addr); if (ret < 0) { log_error("failed to create endpoint '%s'", s); } return ret; } #endif log_error("unsupported endpoint '%s'", s); return -1; } roehling-postsrsd-aefddb9/src/endpoint.h000066400000000000000000000015231477647676400206550ustar00rootroot00000000000000/* PostSRSd - Sender Rewriting Scheme daemon for Postfix * Copyright 2012-2022 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 int endpoint_create(const char* s, int max_fd, int* fds); #endif roehling-postsrsd-aefddb9/src/main.c000066400000000000000000000272441477647676400177640ustar00rootroot00000000000000/* 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 . */ #include "config.h" #include "database.h" #include "endpoint.h" #include "milter.h" #include "netstring.h" #include "postsrsd_build_config.h" #include "srs.h" #include "util.h" #include #include #include #ifdef HAVE_FCNTL_H # include #endif #ifdef HAVE_ERRNO_H # include #endif #ifdef HAVE_SYS_SOCKET_H # include #endif #ifdef HAVE_SYS_TYPES_H # include #endif #ifdef HAVE_SYS_WAIT_H # include #endif #ifdef HAVE_SIGNAL_H # include #endif #ifdef HAVE_PWD_H # include #endif #ifdef HAVE_POLL_H # include #endif #ifdef HAVE_UNISTD_H # include #endif #ifdef HAVE_GRP_H # include #endif static volatile sig_atomic_t timeout = 0; static bool drop_privileges(cfg_t* cfg) { int target_uid = 0; int target_gid = 0; const char* user = cfg_getstr(cfg, "unprivileged-user"); const char* chroot_dir = cfg_getstr(cfg, "chroot-dir"); if (NONEMPTY_STRING(user)) { #ifdef HAVE_PWD_H struct passwd* pwd = NULL; pwd = getpwnam(user); if (pwd == NULL) { log_error("cannot drop privileges: no such user: %s", user); return false; } target_uid = pwd->pw_uid; target_gid = pwd->pw_gid; if (chdir(pwd->pw_dir) < 0 && NULL_OR_EMPTY_STRING(chroot_dir)) { log_warn("cannot chdir to home directory of user %s: %s", user, strerror(errno)); } #else log_error("cannot drop privileges: not supported by system"); return false; #endif } 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 (target_uid != 0 || target_gid != 0) { #ifdef HAVE_SETGROUPS if (setgroups(0, NULL) < 0) { log_perror(errno, "cannot drop privileges: setgroups"); return false; } #endif if (setgid(target_gid) < 0) { log_perror(errno, "cannot drop privileges: setgid"); return false; } if (setuid(target_uid) < 0) { log_perror(errno, "cannot drop privileges: setuid"); return false; } } return true; } static bool prepare_database(cfg_t* cfg) { if (cfg_getint(cfg, "original-envelope") == SRS_ENVELOPE_DATABASE) { database_t* db = database_connect(cfg_getstr(cfg, "envelope-database"), true); if (db == NULL) return false; database_expire(db); database_disconnect(db); } return true; } static bool daemonize(cfg_t* cfg) { if (!cfg_getbool(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_sigalrm(int signum) { timeout = signum; } static void handle_socketmap_client(cfg_t* cfg, srs_t* srs, const char* srs_domain, domain_set_t* local_domains, int conn) { #ifdef HAVE_FCNTL_H 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; } } #endif FILE* fp_write = fdopen(dup(conn), "w"); if (fp_write == NULL) return; FILE* fp_read = fdopen(conn, "r"); if (fp_read == NULL) return; database_t* db = NULL; if (cfg_getint(cfg, "original-envelope") == SRS_ENVELOPE_DATABASE) { db = database_connect(cfg_getstr(cfg, "envelope-database"), false); if (db == NULL) return; } signal(SIGALRM, on_sigalrm); int keep_alive = cfg_getint(cfg, "keep-alive"); for (;;) { char buffer[1024]; size_t len; char* addr; bool error; timeout = 0; alarm(keep_alive); char* request = netstring_read(fp_read, buffer, sizeof(buffer), &len); if (timeout) break; if (request == NULL) { if (!feof(fp_read) && !ferror(fp_read)) { netstring_write(fp_write, "PERM Invalid query.", 19); fflush(fp_write); log_error("invalid socketmap query, closing connection"); } break; } alarm(0); char* query_type = strtok_r(request, " ", &addr); if (query_type == NULL) { netstring_write(fp_write, "PERM Invalid query.", 19); fflush(fp_write); log_error("invalid socketmap query, closing connection"); break; } if (len > 512 + (size_t)(addr - request)) { netstring_write(fp_write, "PERM Too big.", 13); fflush(fp_write); 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, srs_domain, srs, db, local_domains, &error, &info); } else if (strcmp(query_type, "reverse") == 0) { rewritten = postsrsd_reverse(addr, srs, db, &error, &info); } else { error = true; info = "Invalid map."; log_warn("invalid key in socketmap query"); } if (rewritten) { strcpy(buffer, "OK "); strncat(buffer, rewritten, sizeof(buffer) - 4); free(rewritten); netstring_write(fp_write, buffer, strlen(buffer)); } else { if (error) { strcpy(buffer, "PERM "); } else { strcpy(buffer, "NOTFOUND "); } if (info) strncat(buffer, info, sizeof(buffer) - 10); netstring_write(fp_write, buffer, strlen(buffer)); } fflush(fp_write); } database_disconnect(db); } int main(int argc, char** argv) { cfg_t* cfg = NULL; srs_t* srs = NULL; domain_set_t* local_domains = NULL; char* srs_domain = NULL; FILE* pf = NULL; int socketmaps[4] = {-1, -1, -1, -1}; int num_sockets = 0; int milter_pid = 0; 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 cfg = config_from_commandline(argc, argv); if (cfg == NULL) goto shutdown; if (cfg_getbool(cfg, "syslog")) log_enable_syslog(); if (cfg_getbool(cfg, "debug")) log_set_verbosity(LogDebug); srs = srs_from_config(cfg); if (srs == NULL) goto shutdown; if (!srs_domains_from_config(cfg, &srs_domain, &local_domains)) goto shutdown; const char* socketmap_endpoint = cfg_getstr(cfg, "socketmap"); if (NONEMPTY_STRING(socketmap_endpoint)) { num_sockets = endpoint_create( socketmap_endpoint, sizeof(socketmaps) / sizeof(int), socketmaps); if (num_sockets < 0) goto shutdown; } const char* milter_endpoint = cfg_getstr(cfg, "milter"); if (NONEMPTY_STRING(milter_endpoint)) { if (!milter_create(milter_endpoint)) goto shutdown; } else { milter_endpoint = NULL; } const char* pid_file = cfg_getstr(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; } } if (!drop_privileges(cfg)) goto shutdown; if (!prepare_database(cfg)) goto shutdown; if (!daemonize(cfg)) goto shutdown; if (pf != NULL) { fprintf(pf, "%d", (int)getpid()); fclose(pf); pf = NULL; } signal(SIGALRM, SIG_IGN); exit_code = EXIT_SUCCESS; if (num_sockets > 0) { if (NONEMPTY_STRING(milter_endpoint)) { milter_pid = fork(); if (milter_pid == 0) { for (unsigned i = 0; i < sizeof(socketmaps) / sizeof(int); ++i) { if (socketmaps[i] >= 0) close(socketmaps[i]); socketmaps[i] = -1; } milter_main(cfg, srs, srs_domain, local_domains); goto shutdown; } } struct pollfd fds[sizeof(socketmaps) / sizeof(int)]; for (unsigned i = 0; i < (unsigned)num_sockets; ++i) { fds[i].fd = socketmaps[i]; fds[i].events = POLLIN; } for (;;) { if (poll(fds, num_sockets, 1000) < 0) { if (errno == EINTR) continue; log_perror(errno, "poll"); goto shutdown; } for (unsigned i = 0; i < (unsigned)num_sockets; ++i) { if (fds[i].revents) { int conn = accept(fds[i].fd, NULL, NULL); if (conn < 0) { log_perror(errno, "accept"); continue; } pid_t pid = fork(); if (pid == 0) { handle_socketmap_client(cfg, srs, srs_domain, local_domains, conn); exit(EXIT_SUCCESS); } if (pid < 0) { log_perror(errno, "fork"); } close(conn); } } waitpid(-1, NULL, WNOHANG); } } else if (NONEMPTY_STRING(milter_endpoint)) { milter_main(cfg, srs, srs_domain, local_domains); } shutdown: for (unsigned i = 0; i < sizeof(socketmaps) / sizeof(int); ++i) if (socketmaps[i] >= 0) close(socketmaps[i]); if (pf != NULL) fclose(pf); free(srs_domain); if (local_domains != NULL) domain_set_destroy(local_domains); if (srs != NULL) srs_free(srs); if (cfg != NULL) cfg_free(cfg); if (milter_pid > 0) { kill(milter_pid, SIGTERM); waitpid(milter_pid, NULL, 0); } return exit_code; } roehling-postsrsd-aefddb9/src/milter.c000066400000000000000000000172331477647676400203310ustar00rootroot00000000000000/* 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 . */ #include "milter.h" #include "database.h" #include "postsrsd_build_config.h" #include "srs.h" #include "util.h" #ifdef HAVE_ERRNO_H # include #endif #ifdef HAVE_FCNTL_H # include #endif #ifdef HAVE_SYS_STAT_H # include #endif #ifdef WITH_MILTER # include # ifdef HAVE_UNISTD_H # include # endif # include # include # ifndef HAVE_STRNCASECMP # ifdef HAVE__STRNICMP # define strncasecmp _strnicmp # endif # endif static char* milter_uri = NULL; static char* milter_path = NULL; static int milter_lock = -1; static cfg_t* g_cfg = NULL; static srs_t* g_srs = NULL; static domain_set_t* g_local_domains = NULL; static const char* g_srs_domain = NULL; struct privdata { char* envfrom; list_t* envrcpt; }; typedef struct privdata privdata_t; #endif #ifdef WITH_MILTER static void free_privdata(SMFICTX* ctx) { privdata_t* priv = smfi_getpriv(ctx); if (priv == NULL) return; free(priv->envfrom); list_destroy(priv->envrcpt, free); free(priv); smfi_setpriv(ctx, NULL); } static privdata_t* new_privdata(SMFICTX* ctx) { free_privdata(ctx); privdata_t* priv = malloc(sizeof(privdata_t)); if (priv == NULL) return NULL; priv->envfrom = NULL; priv->envrcpt = list_create(); if (priv->envrcpt == NULL) { free(priv); return NULL; } smfi_setpriv(ctx, priv); return priv; } static sfsistat on_envfrom(SMFICTX* ctx, char** argv) { privdata_t* priv = new_privdata(ctx); if (priv == NULL) return SMFIS_TEMPFAIL; priv->envfrom = strip_brackets(argv[0]); if (priv->envfrom == NULL) { free_privdata(ctx); return SMFIS_TEMPFAIL; } return SMFIS_CONTINUE; } static sfsistat on_envrcpt(SMFICTX* ctx, char** argv) { privdata_t* priv = smfi_getpriv(ctx); if (priv == NULL) return SMFIS_TEMPFAIL; char* rcpt = strip_brackets(argv[0]); if (rcpt == NULL) { free_privdata(ctx); return SMFIS_TEMPFAIL; } if (!list_append(priv->envrcpt, rcpt)) { free(rcpt); free_privdata(ctx); return SMFIS_TEMPFAIL; } return SMFIS_CONTINUE; } static sfsistat on_eom(SMFICTX* ctx) { sfsistat status = SMFIS_TEMPFAIL; database_t* db = NULL; privdata_t* priv = smfi_getpriv(ctx); if (priv == NULL) goto done; if (cfg_getint(g_cfg, "original-envelope") == SRS_ENVELOPE_DATABASE) { db = database_connect(cfg_getstr(g_cfg, "envelope-database"), false); if (db == NULL) goto done; } size_t rcpt_size = list_size(priv->envrcpt); bool error = false; for (size_t i = 0; i < rcpt_size; ++i) { char* rcpt = (char*)list_get(priv->envrcpt, i); char* rewritten = postsrsd_reverse(rcpt, g_srs, db, &error, NULL); if (error) goto done; if (rewritten) { char* bracketed_old_rcpt = add_brackets(rcpt); char* bracketed_new_rcpt = add_brackets(rewritten); free(rewritten); if (smfi_delrcpt(ctx, bracketed_old_rcpt) != MI_SUCCESS) { free(bracketed_old_rcpt); free(bracketed_new_rcpt); goto done; } if (smfi_addrcpt(ctx, bracketed_new_rcpt) != MI_SUCCESS) // TODO maybe add ESMTP arguments? { free(bracketed_old_rcpt); free(bracketed_new_rcpt); goto done; } free(bracketed_old_rcpt); free(bracketed_new_rcpt); } } if (*priv->envfrom) { // TODO check if mail is actually forwarded char* rewritten = postsrsd_forward(priv->envfrom, g_srs_domain, g_srs, db, g_local_domains, &error, NULL); if (error) goto done; if (rewritten) { char* bracketed_from = add_brackets(rewritten); free(rewritten); if (smfi_chgfrom(ctx, bracketed_from, NULL) != MI_SUCCESS) // TODO maybe add ESMTP arguments? { free(bracketed_from); goto done; } free(bracketed_from); } } status = SMFIS_CONTINUE; done: if (db) database_disconnect(db); free_privdata(ctx); return status; } static sfsistat on_abort(SMFICTX* ctx) { free_privdata(ctx); return SMFIS_CONTINUE; } /* clang-format off */ static struct smfiDesc smfilter = { "PostSRSd", SMFI_VERSION, SMFIF_CHGFROM | SMFIF_ADDRCPT | SMFIF_DELRCPT, NULL /* connect */, NULL /* helo */, on_envfrom, on_envrcpt, NULL /* header */, NULL /* eoh */, NULL /* body */, on_eom, on_abort, NULL /* close */, NULL /* unknown */, NULL /* data */, NULL /* negotiate */, }; /* clang-format on */ #endif bool milter_create(const char* uri) { #ifdef WITH_MILTER milter_uri = endpoint_for_milter(uri); if (milter_uri == NULL) { log_error("invalid milter endpoint: %s", uri); return false; } if (strncasecmp(milter_uri, "unix:", 5) == 0) milter_path = milter_uri + 5; else if (strncasecmp(milter_uri, "local:", 6) == 0) milter_path = milter_uri + 6; if (milter_path) milter_lock = acquire_lock(milter_path); if (milter_lock > 0) unlink(milter_path); if (smfi_setconn(milter_uri) == MI_FAILURE) { log_error("cannot start milter: smfi_setconn failed"); goto done; } if (smfi_register(smfilter) == MI_FAILURE) { log_error("cannot start milter: failed to register callbacks"); goto done; } if (smfi_opensocket(false) == MI_FAILURE) { log_error("cannot start milter: failed to open socket"); goto done; } if (milter_path) { if (chmod(milter_path, 0666) < 0) { log_perror(errno, "cannot start milter: cannot chmod() socket"); goto done; } } return true; done: if (milter_path != NULL && milter_lock > 0) { release_lock(milter_path, milter_lock); } milter_path = NULL; milter_lock = 0; free(milter_uri); return false; #else MAYBE_UNUSED(uri); log_error("no milter support"); return false; #endif } void milter_main(cfg_t* cfg, srs_t* srs, const char* srs_domain, domain_set_t* local_domains) { MAYBE_UNUSED(cfg); MAYBE_UNUSED(srs); MAYBE_UNUSED(srs_domain); MAYBE_UNUSED(local_domains); #ifdef WITH_MILTER g_cfg = cfg; g_srs = srs; g_srs_domain = srs_domain; g_local_domains = local_domains; smfi_main(); if (milter_path != NULL && milter_lock > 0) { release_lock(milter_path, milter_lock); } milter_path = NULL; milter_lock = 0; free(milter_uri); #endif } roehling-postsrsd-aefddb9/src/milter.h000066400000000000000000000017711477647676400203360ustar00rootroot00000000000000/* PostSRSd - Sender Rewriting Scheme daemon for Postfix * Copyright 2012-2022 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 "config.h" #include "srs2.h" #include "util.h" #include bool milter_create(const char* uri); void milter_main(cfg_t* cfg, srs_t* srs, const char* srs_domain, domain_set_t* local_domains); #endif roehling-postsrsd-aefddb9/src/netstring.c000066400000000000000000000050521477647676400210460ustar00rootroot00000000000000/* PostSRSd - Sender Rewriting Scheme daemon for Postfix * Copyright 2012-2022 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 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 || length >= bufsize - i) return NULL; strncpy(&buffer[i], data, length); buffer[length + i] = ','; if (encoded_length) *encoded_length = length + i + 1; return buffer; } char* netstring_decode(const char* netstring, char* buffer, size_t bufsize, size_t* decoded_length) { if (netstring == NULL) return NULL; int i = -1; size_t length; if (sscanf(netstring, "%5zu%n", &length, &i) < 1) return NULL; if (i < 0 || length >= bufsize) return NULL; if (netstring[i] != ':' || netstring[length + i + 1] != ',') return NULL; strncpy(buffer, &netstring[i + 1], length); if (decoded_length) *decoded_length = length; buffer[length] = 0; return buffer; } char* netstring_read(FILE* f, char* buffer, size_t bufsize, size_t* decoded_length) { size_t length; if (fscanf(f, "%5zu", &length) != 1) return NULL; if (fgetc(f) != ':') return NULL; if (length >= bufsize) return NULL; if (fread(buffer, 1, length, f) != length) return NULL; if (fgetc(f) != ',') return NULL; if (decoded_length) *decoded_length = length; buffer[length] = 0; return buffer; } int netstring_write(FILE* f, const char* data, size_t length) { int i = fprintf(f, "%zu:", length); if (i < 0) return -1; if (fwrite(data, 1, length, f) != length) return -1; if (fputc(',', f) != ',') return -1; return length + i + 1; } roehling-postsrsd-aefddb9/src/netstring.h000066400000000000000000000023561477647676400210570ustar00rootroot00000000000000/* PostSRSd - Sender Rewriting Scheme daemon for Postfix * Copyright 2012-2022 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, char* buffer, size_t bufsize, size_t* decoded_length); char* netstring_read(FILE* f, char* buffer, size_t bufsize, size_t* decoded_length); int netstring_write(FILE* f, const char* data, size_t length); #endif roehling-postsrsd-aefddb9/src/postsrsd_build_config.h.in000066400000000000000000000041571477647676400240350ustar00rootroot00000000000000/* 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@" #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_MILTER 1 #cmakedefine WITH_REDIS 1 #cmakedefine WITH_SQLITE 1 #cmakedefine HAVE_BIG_ENDIAN 1 #cmakedefine HAVE_CHROOT 1 #cmakedefine HAVE_CLOSE_RANGE 1 #cmakedefine HAVE_CLOSE_RANGE_GNU 1 #cmakedefine HAVE_SETGROUPS 1 #cmakedefine HAVE_STRCASECMP 1 #cmakedefine HAVE__STRICMP 1 #cmakedefine HAVE_STRNCASECMP 1 #cmakedefine HAVE__STRNICMP 1 #cmakedefine HAVE_ALLOCA_H 1 #cmakedefine HAVE_ERRNO_H 1 #cmakedefine HAVE_FCNTL_H 1 #cmakedefine HAVE_GRP_H 1 #cmakedefine HAVE_NETDB_H 1 #cmakedefine HAVE_POLL_H 1 #cmakedefine HAVE_PWD_H 1 #cmakedefine HAVE_SIGNAL_H 1 #cmakedefine HAVE_SYS_FILE_H 1 #cmakedefine HAVE_SYS_INOTIFY_H 1 #cmakedefine HAVE_SYS_SOCKET_H 1 #cmakedefine HAVE_SYS_STAT_H 1 #cmakedefine HAVE_SYS_TIME_H 1 #cmakedefine HAVE_SYS_TYPES_H 1 #cmakedefine HAVE_SYS_UN_H 1 #cmakedefine HAVE_SYS_WAIT_H 1 #cmakedefine HAVE_SYSLOG_H 1 #cmakedefine HAVE_TIME_H 1 #cmakedefine HAVE_UNISTD_H 1 #endif roehling-postsrsd-aefddb9/src/sha1.c000066400000000000000000000321421477647676400176650ustar00rootroot00000000000000/* Copyright Gisle Ass, Peter C. Gutmann, Bruce Schneier * Copyright 2004 Shevek * Copyright 2012-2022 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-aefddb9/src/sha1.h000066400000000000000000000021131477647676400176650ustar00rootroot00000000000000/* PostSRSd - Sender Rewriting Scheme daemon for Postfix * Copyright Gisle Ass, Peter C. Gutmann, Bruce Schneier * Copyright 2004 Shevek * Copyright 2012-2022 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-aefddb9/src/srs.c000066400000000000000000000113211477647676400176340ustar00rootroot00000000000000/* 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 . */ #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* at = strchr(addr, '@'); if (error != NULL) *error = false; if (info != NULL) *info = NULL; if (at == NULL) { if (info != NULL) *info = "No domain."; log_debug("<%s> not rewritten: no domain", addr); 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> not rewritten: local domain", 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) *error = true; if (info) *info = "Aliasing error."; return NULL; } strcat(db_alias, "@1"); if (!database_write(db, db_alias, addr, srs->maxage * 86400)) { log_warn("<%s> not rewritten: database error", 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> forwarded as <%s>", addr, output); return output; } free(output); if (info != NULL) *info = srs_strerror(result); log_info("<%s> not rewritten: %s", addr, srs_strerror(result)); return NULL; } char* postsrsd_reverse(const char* addr, srs_t* srs, database_t* db, bool* error, const char** info) { char buffer[513]; if (error != NULL) *error = false; if (info != NULL) *info = NULL; 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> not reversed: %s", addr, srs_strerror(result)); } else { log_debug("<%s> not reversed: %s", addr, srs_strerror(result)); } return NULL; } const char* at = strchr(buffer, '@'); if (at == NULL) { log_info("<%s> not reversed: internal error", addr); if (error != NULL) *error = true; if (info != NULL) *info = "Internal error."; return NULL; } if (strcmp(at, "@1") == 0) { if (db != NULL) { char* p = buffer; while (*p) { *p = toupper(*p); ++p; } char* sender = database_read(db, buffer); if (sender == NULL) { log_info("<%s> not reversed: unknown alias", addr); if (info != NULL) *info = "Unknown alias."; return NULL; } log_info("<%s> reversed to <%s>", addr, sender); return sender; } else { log_warn("<%s> not reversed: no database for alias", addr); if (error) *error = true; if (info) *info = "No database for alias."; return NULL; } } log_info("<%s> reversed to <%s>", addr, buffer); return strdup(buffer); } roehling-postsrsd-aefddb9/src/srs.h000066400000000000000000000022421477647676400176430ustar00rootroot00000000000000/* PostSRSd - Sender Rewriting Scheme daemon for Postfix * Copyright 2012-2022 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); char* postsrsd_reverse(const char* addr, srs_t* srs, database_t* db, bool* error, const char** info); #endif roehling-postsrsd-aefddb9/src/srs2.c000066400000000000000000000430651477647676400177300ustar00rootroot00000000000000/* Copyright 2004 Shevek * Copyright 2012-2023 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 #ifndef HAVE_STRCASECMP # ifdef HAVE__STRICMP # define strcasecmp _stricmp # endif #endif #ifndef HAVE_STRNCASECMP # ifdef HAVE__STRNICMP # define strncasecmp _strnicmp # endif #endif /* 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 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; 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(*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(data[j])) lcdata[j] = tolower(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 (strncasecmp(hash, srshash, len) == 0) 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; char* tmp; unsigned len; if (srs->noforward) return SRS_ENOTREWRITTEN; /* This is allowed to be a plain domain */ while ((tmp = strchr(alias, '@')) != NULL) alias = tmp + 1; tmp = strchr(sender, '@'); if (tmp == NULL) return SRS_ENOSENDERATSIGN; sendhost = tmp + 1; len = strlen(sender); if (!srs->alwaysrewrite) { if (strcasecmp(sendhost, alias) == 0) { if (strlen(sender) >= buflen) return SRS_EBUFTOOSMALL; strcpy(buf, sender); return SRS_SUCCESS; } } char senduser[len + 1]; strcpy(senduser, sender); tmp = (senduser + (tmp - 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; if (!SRS_IS_SRS_ADDRESS(sender)) return SRS_ENOTSRSADDRESS; if (srs->noreverse) return SRS_ENOTREWRITTEN; len = strlen(sender); 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-aefddb9/src/srs2.h000066400000000000000000000116261477647676400177330ustar00rootroot00000000000000/* Copyright 2004 Shevek * Copyright 2012-2023 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_TYPES_H # include #endif #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-aefddb9/src/util.c000066400000000000000000000324141477647676400200100ustar00rootroot00000000000000/* 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 . */ #include "util.h" #include "postsrsd_build_config.h" #include #include #include #include #include #include #ifdef HAVE_FCNTL_H # include #endif #ifdef HAVE_SYS_FILE_H # include #endif #ifdef HAVE_SYS_TYPES_H # include #endif #ifdef HAVE_SYS_STAT_H # include #endif #ifdef HAVE_SYSLOG_H # include #endif #ifdef HAVE_SYS_TIME_H # include #endif #ifdef HAVE_TIME_H # include #endif #include #ifndef HAVE_STRNCASECMP # ifdef HAVE__STRNICMP # define strncasecmp _strnicmp # endif #endif void set_string(char** var, char* value) { free(*var); *var = value; } char** argvdup(char** argv) { if (argv == NULL) return NULL; size_t num = 0; while (argv[num] != NULL) num++; char** result = malloc((num + 1) * sizeof(char*)); if (result == NULL) return NULL; for (size_t i = 0; i < num; ++i) { result[i] = strdup(argv[i]); if (result[i] == NULL) { for (size_t j = 0; j < i; ++j) { free(result[j]); } free(result); return NULL; } } result[num] = NULL; return result; } void freeargv(char** argv) { if (argv == NULL) return; size_t i = 0; while (argv[i] != NULL) { free(argv[i]); i++; } free(argv); } char* strip_brackets(const char* addr) { const char* lbrak = strchr(addr, '<'); const char* rbrak = strchr(addr, '>'); if (lbrak == NULL || rbrak == NULL) return NULL; lbrak++; char* bare = strdup(lbrak); *(bare + (rbrak - lbrak)) = 0; return bare; } char* add_brackets(const char* addr) { char* result = malloc(strlen(addr) + 3); result[0] = '<'; strcpy(result + 1, addr); strcat(result, ">"); return result; } char* b32h_encode(const char* data, size_t length, char* buffer, size_t bufsize) { static const char B32H_CHARS[32] = "0123456789ABCDEFGHIJKLMNOPQRSTUV"; 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 acquire_lock(const char* path) { MAYBE_UNUSED(path); #if defined(LOCK_EX) && defined(LOCK_NB) size_t len = strlen(path); char* lock_path = malloc(len + 6); /* ".lock" + "\0" */ strcpy(lock_path, path); strcat(lock_path, ".lock"); int fd = open(lock_path, O_RDONLY | O_CREAT, 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 release_lock(const char* path, int fd) { MAYBE_UNUSED(path); MAYBE_UNUSED(fd); #if defined(LOCK_EX) && defined(LOCK_NB) size_t len = strlen(path); char* lock_path = malloc(len + 6); /* ".lock" + "\0" */ strcpy(lock_path, path); strcat(lock_path, ".lock"); unlink(lock_path); free(lock_path); close(fd); #endif } /* 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) 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) { 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) { 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[1024]; strncpy(buffer, domain, sizeof(buffer) - 1); buffer[sizeof(buffer) - 1] = 0; 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[1024]; strncpy(buffer, domain, sizeof(buffer) - 1); buffer[sizeof(buffer) - 1] = 0; return walk_domain_set(D, buffer, DOMAIN_SET_PARENTS_MATCH); } 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; } 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; } 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) { 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); } static char* swap_host_port(const char* s, size_t prefix_len) { char* port = strchr(s + prefix_len, ':'); if (port == NULL) return NULL; if (*(port + 1) == 0) return NULL; ptrdiff_t host_len = (port - s) - prefix_len; if (host_len == 0) return NULL; char* result = strdup(s); if (result == NULL) return NULL; strcpy(result + prefix_len, port + 1); if (host_len > 1 || s[prefix_len] != '*') { strcat(result, "@"); strncat(result, s + prefix_len, host_len); } return result; } char* endpoint_for_milter(const char* s) { if (s == NULL) return NULL; if (strncasecmp(s, "unix:", 5) == 0 || strncasecmp(s, "local:", 6) == 0) return strdup(s); if (strncasecmp(s, "inet:", 5) == 0) { return swap_host_port(s, 5); } if (strncasecmp(s, "inet6:", 6) == 0) { return swap_host_port(s, 6); } return NULL; } char* endpoint_for_redis(const char* s, int* port) { if (s == NULL) return NULL; char* colon = strchr(s, ':'); 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: "}; #ifdef HAVE_SYSLOG_H static bool use_syslog = false; static int syslog_priorities[] = {LOG_DEBUG, LOG_INFO, LOG_WARNING, LOG_ERR}; #endif 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, ap); buffer[sizeof(buffer) - 1] = 0; fprintf(stderr, "%s\n", buffer); fflush(stderr); #ifdef HAVE_SYSLOG_H if (use_syslog) { syslog(LOG_MAIL | syslog_priorities[prio], "%s", text); } #endif } void log_enable_syslog() { #ifdef HAVE_SYSLOG_H time_t now; openlog("postsrsd", LOG_PID | LOG_NDELAY, LOG_MAIL); now = time(NULL); localtime(&now); use_syslog = true; #else log_warn("syslog facility is not available"); #endif } 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 (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(1); } roehling-postsrsd-aefddb9/src/util.h000066400000000000000000000052561477647676400200210ustar00rootroot00000000000000/* 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 UTIL_H #define UTIL_H #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 domain_set; typedef struct domain_set domain_set_t; struct list; typedef struct list list_t; typedef void (*list_deleter_t)(void*); void set_string(char** var, char* value); char* b32h_encode(const char* data, size_t length, char* buffer, size_t bufsize); char** argvdup(char** argv); void freeargv(char** argv); char* strip_brackets(const char* addr); char* add_brackets(const char* addr); bool file_exists(const char* filename); bool directory_exists(const char* dirname); int acquire_lock(const char* path); void release_lock(const char* path, int fd); 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); list_t* list_create(); void* list_get(list_t* L, size_t i); bool list_append(list_t* L, void* data); size_t list_size(list_t* L); void list_clear(list_t* L, list_deleter_t deleter); void list_destroy(list_t* L, list_deleter_t deleter); char* endpoint_for_milter(const char* s); char* endpoint_for_redis(const char* s, int* port); enum log_priority { LogDebug, LogInfo, LogWarn, LogError, }; void log_enable_syslog(); void log_set_verbosity(enum log_priority prio); void log_debug(const char* fmt, ...) ATTRIBUTE(format(printf, 1, 2)); void log_info(const char* fmt, ...) ATTRIBUTE(format(printf, 1, 2)); void log_warn(const char* fmt, ...) ATTRIBUTE(format(printf, 1, 2)); void log_error(const char* fmt, ...) ATTRIBUTE(format(printf, 1, 2)); void log_perror(int errno, const char* prefix); void log_fatal(const char* fmt, ...) ATTRIBUTE(noreturn); #endif roehling-postsrsd-aefddb9/tests/000077500000000000000000000000001477647676400172365ustar00rootroot00000000000000roehling-postsrsd-aefddb9/tests/CMakeLists.txt000066400000000000000000000014131477647676400217750ustar00rootroot00000000000000# PostSRSd - Sender Rewriting Scheme daemon for Postfix # Copyright 2012-2022 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-aefddb9/tests/blackbox/000077500000000000000000000000001477647676400210235ustar00rootroot00000000000000roehling-postsrsd-aefddb9/tests/blackbox/CMakeLists.txt000066400000000000000000000023161477647676400235650ustar00rootroot00000000000000# 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 . # find_package(Python3 3.3 QUIET) if(Python3_EXECUTABLE) add_test( NAME test_socketmap COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/socketmap.py" "$" "$" ) if(WITH_MILTER) add_test( NAME test_milter COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/milter.py" "$" ) endif() endif() roehling-postsrsd-aefddb9/tests/blackbox/milter.py000066400000000000000000000112501477647676400226700ustar00rootroot00000000000000# 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 . # import contextlib import os import pathlib import socket import signal import subprocess import struct import sys import tempfile import time def send_milter(sock, code, data): sock.send(struct.pack(">Lc", len(data) + 1, code) + data) def recv_milter(sock): size = struct.unpack(">L", sock.recv(4)) data = sock.recv(*size) return data[:1], data[1:] def mf_optneg(sock): send_milter(sock, b"O", struct.pack(">LLL", 6, 0xFF, 0xFF)) code, _ = recv_milter(sock) return code == b"O" def mf_connect(sock): send_milter(sock, b"C", b"mail.example.com\x00U") code, _ = recv_milter(sock) return code == b"c" def mf_envfrom(sock, envfrom): send_milter(sock, b"M", b"<" + envfrom.encode() + b">\x00") code, _ = recv_milter(sock) return code == b"c" def mf_rcptto(sock, rcptto): send_milter(sock, b"R", b"<" + rcptto.encode() + b">\x00") code, _ = recv_milter(sock) return code == b"c" def mf_eom(sock): new_from = None new_rcpt = None send_milter(sock, b"E", b"") code, data = recv_milter(sock) while code in [b"+", b"-", b"e"]: if code == b"+": new_rcpt = data[1:-2].decode() if code == b"e": new_from = data[1:-2].decode() code, data = recv_milter(sock) return code == b"c", new_from, new_rcpt @contextlib.contextmanager def postsrsd_instance(postsrsd, when): with tempfile.TemporaryDirectory() as tmpdirname: tmpdir = pathlib.Path(tmpdirname) with open(tmpdir / "postsrsd.conf", "w") as f: f.write( 'domains = {"example.com"}\n' "keep-alive = 2\n" 'chroot-dir = ""\n' 'unprivileged-user = ""\n' f"original-envelope = embedded\n" f'socketmap = ""\n' f'milter = unix:{tmpdir / "postsrsd.sock"}\n' f'secrets-file = {tmpdir / "postsrsd.secret"}\n' f'envelope-database = sqlite:{tmpdir / "postsrsd.db"}\n' ) with open(tmpdir / "postsrsd.secret", "w") as f: f.write("tops3cr3t\n") os.environ["POSTSRSD_FAKETIME"] = when proc = subprocess.Popen( [postsrsd, "-C", str(tmpdir / "postsrsd.conf")], start_new_session=True, ) wait = 50 while not (tmpdir / "postsrsd.sock").exists() and wait > 0: time.sleep(0.1) wait -= 1 try: yield str(tmpdir / "postsrsd.sock").encode() finally: os.killpg(os.getpgid(proc.pid), signal.SIGTERM) proc.wait() def execute_queries(postsrsd, when, queries): with postsrsd_instance(postsrsd, when) as endpoint: for query in queries: orig_from, orig_rcpt = query[0] new_from, new_rcpt = query[1] sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM, 0) try: sock.settimeout(0.5) sock.connect(endpoint) assert mf_optneg(sock) assert mf_connect(sock) assert mf_envfrom(sock, orig_from) assert mf_rcptto(sock, orig_rcpt) ok, srs_from, srs_rcpt = mf_eom(sock) assert ok, "mf_eom failed" assert srs_from == new_from assert srs_rcpt == new_rcpt sys.stderr.write(f"query[{query[0]}]: Passed\n") finally: sock.close() if __name__ == "__main__": execute_queries( sys.argv[1], when="1577836860", # 2020-01-01 00:01:00 UTC queries=[ (("sender@example.com", "recipient@example.com"), (None, None)), ( ("sender@otherdomain.com", "recipient@example.com"), ("SRS0=9KJ+=2W=otherdomain.com=sender@example.com", None), ), ( ("", "SRS0=9KJ+=2W=otherdomain.com=sender@example.com"), (None, "sender@otherdomain.com"), ), ], ) roehling-postsrsd-aefddb9/tests/blackbox/socketmap.py000066400000000000000000000315551477647676400233740ustar00rootroot00000000000000# 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 . # import contextlib import os import pathlib import signal import socket import stat import subprocess import sys import tempfile import time class SockStream: def __init__(self, sock): self._sock = sock self._rdbuf = b"" def read(self, size): 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 ConnectionError("no data") result += self._rdbuf[:remaining] self._rdbuf = self._rdbuf[remaining:] return result def write(self, data): self._sock.sendall(data) def write_netstring(sock_stream, data): data_bytes = data.encode() sock_stream.write(f"{len(data_bytes)}:".encode() + data_bytes + b",") def read_netstring(sock_stream): 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":": print("ERR: ':' expected") return None data = sock_stream.read(data_size) comma = sock_stream.read(1) if comma != b",": print("ERR: ',' expected") return None return data.decode() @contextlib.contextmanager def postsrsd_instance(postsrsd, when, use_database): with tempfile.TemporaryDirectory() as tmpdirname: tmpdir = pathlib.Path(tmpdirname) with open(tmpdir / "postsrsd.conf", "w") as f: f.write( 'domains = {"example.com"}\n' "keep-alive = 10\n" 'chroot-dir = ""\n' 'unprivileged-user = ""\n' f'original-envelope = {"database" if use_database else "embedded"}\n' f'socketmap = unix:{tmpdir / "postsrsd.sock"}\n' f'secrets-file = {tmpdir / "postsrsd.secret"}\n' f'envelope-database = sqlite:{tmpdir / "postsrsd.db"}\n' ) with open(tmpdir / "postsrsd.secret", "w") as f: f.write("tops3cr3t\n") os.environ["POSTSRSD_FAKETIME"] = when proc = subprocess.Popen( [postsrsd, "-C", str(tmpdir / "postsrsd.conf")], start_new_session=True, ) wait = 50 while not (tmpdir / "postsrsd.sock").exists() and wait > 0: time.sleep(0.1) wait -= 1 try: yield str(tmpdir / "postsrsd.sock").encode() finally: os.killpg(os.getpgid(proc.pid), signal.SIGTERM) proc.wait() def execute_queries(postsrsd, when, use_database, queries): with postsrsd_instance(postsrsd, when, use_database) as endpoint: st = os.stat(endpoint) assert st.st_mode & 0o777 == 0o666 sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM, 0) sock.connect(endpoint) sock_stream = SockStream(sock) try: for nr, query in enumerate(queries, start=1): write_netstring(sock_stream, query[0]) result = read_netstring(sock_stream) if result != query[1]: raise AssertionError( f"query[{query[0]}]: FAILED: Expected reply {query[1]!r}, got: {result!r}" ) sys.stderr.write(f"query[{query[0]}]: Passed\n") finally: sock.close() def execute_death_tests(postsrsd, when, use_database, queries): with postsrsd_instance(postsrsd, when, use_database) as endpoint: for nr, query in enumerate(queries, start=1): try: sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM, 0) sock.settimeout(10) sock.connect(endpoint) sock_stream = SockStream(sock) sock_stream.write(query) result = read_netstring(sock_stream) if result != "PERM Invalid query.": raise AssertionError( f"death_test[{query}]: FAILED: Expected reply 'PERM Invalid query.', got: {result!r}" ) try: write_netstring(sock_stream, "forward test@example.com") result = read_netstring(sock_stream) raise AssertionError( f"death_test[{query}]: FAILED: Expected connection closed, got: {result!r}" ) except ConnectionError: # Expected behavior pass sys.stderr.write(f"death_test[{query}]: Passed\n") finally: sock.close() if __name__ == "__main__": execute_queries( sys.argv[1], when="1577836860", # 2020-01-01 00:01:00 UTC use_database=False, 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.", ), # Reject 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.", ), # Reject valid SRS0 address with time stamp 6 month in the future ( "reverse SRS0=VcIb=7N=otherdomain.com=test@example.com", "NOTFOUND Time stamp out of date.", ), # Reject SRS0 address with invalid hash ( "reverse SRS0=FAKE=2V=otherdomain.com=test@example.com", "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", ), # Reject SRS0 address without authenticating hash ( "reverse SRS0=@example.com", "NOTFOUND No hash in SRS0 address.", ), # Reject SRS0 address without time stamp ( "reverse SRS0=XjO9@example.com", "NOTFOUND No timestamp in SRS0 address.", ), # Reject SRS0 address without original domain ( "reverse SRS0=XjO9=2V@example.com", "NOTFOUND No host in SRS0 address.", ), # Reject 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.", ), ], ) execute_death_tests( sys.argv[1], when="1577836860", # 2020-01-01 00:01:00 UTC use_database=False, 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;", ], ) if sys.argv[2] == "1": execute_queries( sys.argv[1], when="1577836860", # 2020-01-01 00:01:00 UTC use_database=True, 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", ), ], ) sys.exit(0) roehling-postsrsd-aefddb9/tests/unit/000077500000000000000000000000001477647676400202155ustar00rootroot00000000000000roehling-postsrsd-aefddb9/tests/unit/CMakeLists.txt000066400000000000000000000041621477647676400227600ustar00rootroot00000000000000# 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 . # 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) 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 ${name} COMMAND ${name}_executable) endmacro() set(SRCDIR ../../src) add_postsrsd_test(test_netstring ${SRCDIR}/netstring.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 Confuse::Confuse) roehling-postsrsd-aefddb9/tests/unit/common.h000066400000000000000000000044171477647676400216640ustar00rootroot00000000000000/* PostSRSd - Sender Rewriting Scheme daemon for Postfix * Copyright 2012-2022 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-aefddb9/tests/unit/test_config.c000066400000000000000000000046641477647676400226770ustar00rootroot00000000000000/* PostSRSd - Sender Rewriting Scheme daemon for Postfix * Copyright 2012-2024 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" "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_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-aefddb9/tests/unit/test_database.c000066400000000000000000000056441477647676400231750ustar00rootroot00000000000000/* PostSRSd - Sender Rewriting Scheme daemon for Postfix * Copyright 2012-2022 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 #ifdef HAVE_UNISTD_H # include #endif 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 #ifdef WITH_REDIS START_TEST(database_redis_key_value) { database_t* db = database_connect("redis:localhost:6379", true); if (db == NULL) return; /* skip test if no redis server is available */ 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); if (db == NULL) return; /* skip test if no redis server is available */ 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 #ifdef WITH_REDIS ADD_TEST(database_redis_key_value) ADD_TEST(database_redis_expiry) #endif END_TEST_SUITE() TEST_MAIN(database) roehling-postsrsd-aefddb9/tests/unit/test_netstring.c000066400000000000000000000112621477647676400234370ustar00rootroot00000000000000/* 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 . */ #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,", 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,", 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:,", buffer, sizeof(buffer), &length); ck_assert_ptr_nonnull(result); ck_assert_uint_eq(length, 0); result = netstring_decode(NULL, buffer, sizeof(buffer), &length); ck_assert_ptr_null(result); result = netstring_decode("1a,", buffer, sizeof(buffer), &length); ck_assert_ptr_null(result); result = netstring_decode("1:a*", buffer, sizeof(buffer), &length); ck_assert_ptr_null(result); result = netstring_decode("0x1:a,", buffer, sizeof(buffer), &length); ck_assert_ptr_null(result); result = netstring_decode("000001:a,", 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; FILE* f = tmpfile(); 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(fseek(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(fseek(f, 0, SEEK_SET), 0); ck_assert_int_eq(ftruncate(fileno(f), 0), 0); fwrite("3:abc,4:abcde", 1, 13, f); ck_assert_int_eq(fseek(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(fseek(f, 0, SEEK_SET), 0); ck_assert_int_eq(ftruncate(fileno(f), 0), 0); fwrite("999:obviously too short,", 1, 4, f); ck_assert_int_eq(fseek(f, 0, SEEK_SET), 0); data = netstring_read(f, buffer, sizeof(buffer), &length); ck_assert_ptr_null(data); fclose(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-aefddb9/tests/unit/test_sha1.c000066400000000000000000000064151477647676400222620ustar00rootroot00000000000000/* PostSRSd - Sender Rewriting Scheme daemon for Postfix * Copyright 2012-2022 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-aefddb9/tests/unit/test_srs2.c000066400000000000000000000043261477647676400223160ustar00rootroot00000000000000/* 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 . */ #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-aefddb9/tests/unit/test_util.c000066400000000000000000000240141477647676400223760ustar00rootroot00000000000000/* PostSRSd - Sender Rewriting Scheme daemon for Postfix * Copyright 2012-2022 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 #ifdef HAVE_SYS_FILE_H # include #endif #ifdef HAVE_SYS_STAT_H # include #endif #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(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 START_TEST(util_set_string) { char* s = NULL; set_string(&s, strdup("Test")); ck_assert_str_eq(s, "Test"); set_string(&s, NULL); ck_assert_ptr_null(s); } END_TEST START_TEST(util_argvdup) { const char* tokens[5] = {"one", "two", "three", "four", "five"}; char* argv[5]; ck_assert_ptr_null(argvdup(NULL)); for (size_t num = 0; num < 5; ++num) { for (size_t i = 0; i < num; ++i) { argv[i] = strdup(tokens[i]); } argv[num] = NULL; char** result = argvdup(argv); ck_assert_ptr_ne(argv, result); for (size_t i = 0; i < num; ++i) { ck_assert_ptr_ne(argv[i], result[i]); ck_assert_str_eq(argv[i], result[i]); free(argv[i]); } ck_assert_ptr_null(result[num]); freeargv(result); } freeargv(NULL); } END_TEST START_TEST(util_strip_brackets) { char* result; result = strip_brackets("test@example.com"); ck_assert_ptr_eq(result, NULL); result = strip_brackets(""); ck_assert_ptr_eq(result, NULL); result = strip_brackets(""); ck_assert_str_eq(result, "test@example.com"); free(result); result = strip_brackets("Test User "); ck_assert_str_eq(result, "test@example.com"); free(result); } END_TEST START_TEST(util_list) { list_t* L = list_create(); ck_assert_uint_eq(list_size(L), 0); ck_assert_ptr_null(list_get(L, 0)); ck_assert_uint_eq(list_append(L, strdup("0")), true); 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_uint_eq(list_append(L, strdup("1")), true); ck_assert_uint_eq(list_append(L, strdup("2")), true); ck_assert_uint_eq(list_append(L, strdup("3")), true); ck_assert_uint_eq(list_append(L, strdup("4")), true); ck_assert_uint_eq(list_append(L, strdup("5")), true); 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)); list_clear(L, free); ck_assert_uint_eq(list_size(L), 0); ck_assert_uint_eq(list_append(L, strdup("a")), true); ck_assert_str_eq((char*)list_get(L, 0), "a"); 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 = acquire_lock("testfile"); ck_assert_int_gt(handle, 0); ck_assert_int_lt(acquire_lock("testfile"), 0); release_lock("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.")); domain_set_destroy(D); } START_TEST(util_endpoint_for_milter) { char* ep; ck_assert_ptr_null(endpoint_for_milter(NULL)); ck_assert_ptr_null(endpoint_for_milter("invalid")); ck_assert_ptr_null( endpoint_for_milter("https://this.is.not.a.valid.endpoint.net")); ck_assert_ptr_null(endpoint_for_milter("inet:host.but.no.port")); ck_assert_ptr_null(endpoint_for_milter("inet:1234")); ck_assert_ptr_null(endpoint_for_milter("inet:localhost:")); ck_assert_ptr_null(endpoint_for_milter("inet::1234")); ck_assert_ptr_null(endpoint_for_milter("inet6:1234")); ck_assert_ptr_null(endpoint_for_milter("inet6:localhost:")); ck_assert_ptr_null(endpoint_for_milter("inet6::1234")); ep = endpoint_for_milter("unix:/some/path"); ck_assert_str_eq(ep, "unix:/some/path"); free(ep); ep = endpoint_for_milter("inet:localhost:1234"); ck_assert_str_eq(ep, "inet:1234@localhost"); free(ep); ep = endpoint_for_milter("inet:*:1234"); ck_assert_str_eq(ep, "inet:1234"); free(ep); ep = endpoint_for_milter("inet6:localhost:1234"); ck_assert_str_eq(ep, "inet6:1234@localhost"); free(ep); ep = endpoint_for_milter("inet6:*:1234"); ck_assert_str_eq(ep, "inet6:1234"); free(ep); } END_TEST 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(util_set_string) ADD_TEST(util_argvdup); ADD_TEST(util_strip_brackets); ADD_TEST(util_list); ADD_TEST(util_b32h_encode) ADD_TEST(util_domain_set) ADD_TEST(util_endpoint_for_milter) ADD_TEST(util_log) END_TEST_SUITE() TEST_MAIN(util)