diff --git a/docker/imap/cyrus.conf b/docker/imap/cyrus.conf index a5137fbc..c9b41321 100644 --- a/docker/imap/cyrus.conf +++ b/docker/imap/cyrus.conf @@ -1,39 +1,40 @@ START { # do not delete this entry! recover cmd="ctl_cyrusdb -r" #mupdatepush cmd="ctl_mboxlist -m" } SERVICES { http cmd="httpd" listen=0.0.0.0:11080 proto="tcp" prefork=5 imap cmd="imapd" listen=0.0.0.0:11143 proto="tcp" prefork=5 https cmd="httpd -s" listen=0.0.0.0:11443 proto="tcp" prefork=5 imaps cmd="imapd -s" listen=0.0.0.0:11993 proto="tcp" prefork=1 sieve cmd="timsieved" listen=0.0.0.0:4190 proto="tcp" prefork=0 - lmtp cmd="lmtpd" listen=0.0.0.0:11024 proto="tcp" prefork=1 + # lmtp without authentication required (-a) + lmtp cmd="lmtpd -a" listen=0.0.0.0:11024 proto="tcp" prefork=1 } EVENTS { # this is required checkpoint cmd="ctl_cyrusdb -c" period="39" # Expire deleted folders older than 28 days. deleteprune cmd="cyr_expire -E 4 -D 28" at="0400" # Expire deleted messages older than 28 days. expungeprune cmd="cyr_expire -E 4 -X 28" at="0132" # this is only necessary if caching TLS sessions tlsprune cmd="tls_prune" at="0400" # this is only necessary if using duplicate delivery suppression delprune cmd="cyr_expire -E 3" at="0400" } DAEMON { # this is only necessary if using idled for IMAP IDLE idled cmd="idled" } diff --git a/docker/imap/init.sh b/docker/imap/init.sh index aa6522bb..5573020c 100755 --- a/docker/imap/init.sh +++ b/docker/imap/init.sh @@ -1,29 +1,29 @@ #!/bin/bash sed -i -r \ -e "s|IMAP_ADMIN_LOGIN|$IMAP_ADMIN_LOGIN|g" \ -e "s|IMAP_ADMIN_PASSWORD|$IMAP_ADMIN_PASSWORD|g" \ /etc/imapd.conf sed -i -r \ -e "s|APP_DOMAIN|$APP_DOMAIN|g" \ /etc/saslauthd.conf /usr/sbin/saslauthd -m /run/saslauthd -a httpform -d & # Can't run as user because of /dev/ permissions so far. # Cyrus imap only logs to /dev/log, no way around it it seems. # sudo rsyslogd # Cyrus needs an entry in /etc/passwd. THe alternative would be perhaps the nss_wrapper # https://docs.openshift.com/container-platform/3.11/creating_images/guidelines.html#openshift-specific-guidelines # FIXME: This probably currently just works because we make /etc/ writable, which I suppose we shouldn't. ID=$(id -u) GID=$(id -g) echo "$ID:x:$ID:$GID::/opt/app-root/:/bin/bash" > /etc/passwd -exec env CYRUS_VERBOSE=9 CYRUS_USER="$ID" /usr/libexec/master -D -p /var/run/master.pid -M /etc/cyrus.conf -C /etc/imapd.conf +exec env CYRUS_VERBOSE=2 CYRUS_USER="$ID" /usr/libexec/master -D -p /var/run/master.pid -M /etc/cyrus.conf -C /etc/imapd.conf diff --git a/docker/postfix/Dockerfile b/docker/postfix/Dockerfile new file mode 100644 index 00000000..d59d201b --- /dev/null +++ b/docker/postfix/Dockerfile @@ -0,0 +1,46 @@ +FROM almalinux:8 + +LABEL maintainer="contact@apheleia-it.ch" +LABEL dist=centos8 +LABEL tier=${TIER} + +ENV DISTRO=centos8 +# ENV LANG=en_US.utf8 +# ENV LC_ALL=en_US.utf8 +# ENV APP_DOMAIN +# ENV LMTP_DESTINATION +# ENV DB_HOST +# ENV DB_USERNAME +# ENV DB_PASSWORD +# ENV DB_DATABASE + +# Add EPEL. +RUN dnf -y install dnf-plugin-config-manager && \ + dnf config-manager --set-enabled powertools && \ + dnf -y install \ + epel-release \ + python3 \ + python3-requests \ + postfix \ + postfix-mysql \ + cyrus-sasl \ + cyrus-sasl-plain \ + procps-ng \ + iputils \ + bind-utils \ + vim-enhanced && \ + dnf clean all +RUN rpm --import /etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-8 + +RUN sed -i -r -e 's/^SELINUX=.*$/SELINUX=permissive/g' /etc/selinux/config 2>/dev/null || : + +WORKDIR /root/ + +COPY /rootfs / + +VOLUME [ "/var/spool/postfix" ] +VOLUME [ "/var/lib/postfix" ] + +CMD ["/init.sh"] + +EXPOSE 10025/tcp 10587/tcp diff --git a/docker/postfix/rootfs/etc/postfix/header_checks.inbound b/docker/postfix/rootfs/etc/postfix/header_checks.inbound new file mode 100644 index 00000000..a824f848 --- /dev/null +++ b/docker/postfix/rootfs/etc/postfix/header_checks.inbound @@ -0,0 +1,6 @@ +/^X-Spam-Flag:.*YES/ REJECT +/^X-Virus-Scanned:/ IGNORE +/^X-Spam-Flag:.*NO/ IGNORE +/^X-Spam-Score:/ IGNORE +/^X-Spam-Level:/ IGNORE +/^X-Spam-Status:/ IGNORE diff --git a/docker/postfix/rootfs/etc/postfix/header_checks.internal b/docker/postfix/rootfs/etc/postfix/header_checks.internal new file mode 100644 index 00000000..29761418 --- /dev/null +++ b/docker/postfix/rootfs/etc/postfix/header_checks.internal @@ -0,0 +1 @@ +/^Received:.*127\.0\.0\.1/ IGNORE diff --git a/docker/postfix/rootfs/etc/postfix/header_checks.submission b/docker/postfix/rootfs/etc/postfix/header_checks.submission new file mode 100644 index 00000000..c11dd8ab --- /dev/null +++ b/docker/postfix/rootfs/etc/postfix/header_checks.submission @@ -0,0 +1,6 @@ +/^Received:.*with ESMTPSA/ IGNORE +/^Received:.*127\.0\.0\.1/ IGNORE +/^User-Agent:/ IGNORE +/^X-Mailer:/ IGNORE +/^Sender:/ IGNORE +/^X-Sender:/ IGNORE diff --git a/docker/postfix/rootfs/etc/postfix/main.cf b/docker/postfix/rootfs/etc/postfix/main.cf new file mode 100644 index 00000000..9c965f13 --- /dev/null +++ b/docker/postfix/rootfs/etc/postfix/main.cf @@ -0,0 +1,669 @@ +# Global Postfix configuration file. This file lists only a subset +# of all parameters. For the syntax, and for a complete parameter +# list, see the postconf(5) manual page (command: "man 5 postconf"). +# +# For common configuration examples, see BASIC_CONFIGURATION_README +# and STANDARD_CONFIGURATION_README. To find these documents, use +# the command "postconf html_directory readme_directory", or go to +# http://www.postfix.org/BASIC_CONFIGURATION_README.html etc. +# +# For best results, change no more than 2-3 parameters at a time, +# and test if Postfix still works after every change. + +# COMPATIBILITY +# +# The compatibility_level determines what default settings Postfix +# will use for main.cf and master.cf settings. These defaults will +# change over time. +# +# To avoid breaking things, Postfix will use backwards-compatible +# default settings and log where it uses those old backwards-compatible +# default settings, until the system administrator has determined +# if any backwards-compatible default settings need to be made +# permanent in main.cf or master.cf. +# +# When this review is complete, update the compatibility_level setting +# below as recommended in the RELEASE_NOTES file. +# +# The level below is what should be used with new (not upgrade) installs. +# +compatibility_level = 2 + +# SOFT BOUNCE +# +# The soft_bounce parameter provides a limited safety net for +# testing. When soft_bounce is enabled, mail will remain queued that +# would otherwise bounce. This parameter disables locally-generated +# bounces, and prevents the SMTP server from rejecting mail permanently +# (by changing 5xx replies into 4xx replies). However, soft_bounce +# is no cure for address rewriting mistakes or mail routing mistakes. +# +#soft_bounce = no + +# LOCAL PATHNAME INFORMATION +# +# The queue_directory specifies the location of the Postfix queue. +# This is also the root directory of Postfix daemons that run chrooted. +# See the files in examples/chroot-setup for setting up Postfix chroot +# environments on different UNIX systems. +# +queue_directory = /var/spool/postfix + +# The command_directory parameter specifies the location of all +# postXXX commands. +# +command_directory = /usr/sbin + +# The daemon_directory parameter specifies the location of all Postfix +# daemon programs (i.e. programs listed in the master.cf file). This +# directory must be owned by root. +# +daemon_directory = /usr/libexec/postfix + +# The data_directory parameter specifies the location of Postfix-writable +# data files (caches, random numbers). This directory must be owned +# by the mail_owner account (see below). +# +data_directory = /var/lib/postfix + +# QUEUE AND PROCESS OWNERSHIP +# +# The mail_owner parameter specifies the owner of the Postfix queue +# and of most Postfix daemon processes. Specify the name of a user +# account THAT DOES NOT SHARE ITS USER OR GROUP ID WITH OTHER ACCOUNTS +# AND THAT OWNS NO OTHER FILES OR PROCESSES ON THE SYSTEM. In +# particular, don't specify nobody or daemon. PLEASE USE A DEDICATED +# USER. +# +mail_owner = postfix + +# The default_privs parameter specifies the default rights used by +# the local delivery agent for delivery to external file or command. +# These rights are used in the absence of a recipient user context. +# DO NOT SPECIFY A PRIVILEGED USER OR THE POSTFIX OWNER. +# +#default_privs = nobody + +# INTERNET HOST AND DOMAIN NAMES +# +# The myhostname parameter specifies the internet hostname of this +# mail system. The default is to use the fully-qualified domain name +# from gethostname(). $myhostname is used as a default value for many +# other configuration parameters. +# +#myhostname = host.domain.tld +#myhostname = virtual.domain.tld + +# The mydomain parameter specifies the local internet domain name. +# The default is to use $myhostname minus the first component. +# $mydomain is used as a default value for many other configuration +# parameters. +# +#mydomain = domain.tld + +# SENDING MAIL +# +# The myorigin parameter specifies the domain that locally-posted +# mail appears to come from. The default is to append $myhostname, +# which is fine for small sites. If you run a domain with multiple +# machines, you should (1) change this to $mydomain and (2) set up +# a domain-wide alias database that aliases each user to +# user@that.users.mailhost. +# +# For the sake of consistency between sender and recipient addresses, +# myorigin also specifies the default domain name that is appended +# to recipient addresses that have no @domain part. +# +#myorigin = $myhostname +#myorigin = $mydomain + +# RECEIVING MAIL + +# The inet_interfaces parameter specifies the network interface +# addresses that this mail system receives mail on. By default, +# the software claims all active interfaces on the machine. The +# parameter also controls delivery of mail to user@[ip.address]. +# +# See also the proxy_interfaces parameter, for network addresses that +# are forwarded to us via a proxy or network address translator. +# +# Note: you need to stop/start Postfix when this parameter changes. +# +#inet_interfaces = all +#inet_interfaces = $myhostname +#inet_interfaces = $myhostname, localhost +inet_interfaces = all + +# Enable IPv4, and IPv6 if supported +inet_protocols = all + +# The proxy_interfaces parameter specifies the network interface +# addresses that this mail system receives mail on by way of a +# proxy or network address translation unit. This setting extends +# the address list specified with the inet_interfaces parameter. +# +# You must specify your proxy/NAT addresses when your system is a +# backup MX host for other domains, otherwise mail delivery loops +# will happen when the primary MX host is down. +# +#proxy_interfaces = +#proxy_interfaces = 1.2.3.4 + +# Specify which domains should be delivered locally +mydestination = APP_DOMAIN +# Required to correctly resolve the imap host in the container +lmtp_host_lookup = native +# lmtp for local transport +local_transport = lmtp:LMTP_DESTINATION + +# The unknown_local_recipient_reject_code specifies the SMTP server +# response code when a recipient domain matches $mydestination or +# ${proxy,inet}_interfaces, while $local_recipient_maps is non-empty +# and the recipient address or address local-part is not found. +# +# The default setting is 550 (reject mail) but it is safer to start +# with 450 (try again later) until you are certain that your +# local_recipient_maps settings are OK. +# +unknown_local_recipient_reject_code = 550 + +# TRUST AND RELAY CONTROL + +# The mynetworks parameter specifies the list of "trusted" SMTP +# clients that have more privileges than "strangers". +# +# In particular, "trusted" SMTP clients are allowed to relay mail +# through Postfix. See the smtpd_recipient_restrictions parameter +# in postconf(5). +# +# You can specify the list of "trusted" network addresses by hand +# or you can let Postfix do it for you (which is the default). +# +# By default (mynetworks_style = subnet), Postfix "trusts" SMTP +# clients in the same IP subnetworks as the local machine. +# On Linux, this works correctly only with interfaces specified +# with the "ifconfig" command. +# +# Specify "mynetworks_style = class" when Postfix should "trust" SMTP +# clients in the same IP class A/B/C networks as the local machine. +# Don't do this with a dialup site - it would cause Postfix to "trust" +# your entire provider's network. Instead, specify an explicit +# mynetworks list by hand, as described below. +# +# Specify "mynetworks_style = host" when Postfix should "trust" +# only the local machine. +# +#mynetworks_style = class +#mynetworks_style = subnet +#mynetworks_style = host + +# Alternatively, you can specify the mynetworks list by hand, in +# which case Postfix ignores the mynetworks_style setting. +# +# Specify an explicit list of network/netmask patterns, where the +# mask specifies the number of bits in the network part of a host +# address. +# +# You can also specify the absolute pathname of a pattern file instead +# of listing the patterns here. Specify type:table for table-based lookups +# (the value on the table right-hand side is not used). +# +#mynetworks = 168.100.189.0/28, 127.0.0.0/8 +#mynetworks = $config_directory/mynetworks +#mynetworks = hash:/etc/postfix/network_table + +# The relay_domains parameter restricts what destinations this system will +# relay mail to. See the smtpd_recipient_restrictions description in +# postconf(5) for detailed information. +# +# By default, Postfix relays mail +# - from "trusted" clients (IP address matches $mynetworks) to any destination, +# - from "untrusted" clients to destinations that match $relay_domains or +# subdomains thereof, except addresses with sender-specified routing. +# The default relay_domains value is $mydestination. +# +# In addition to the above, the Postfix SMTP server by default accepts mail +# that Postfix is final destination for: +# - destinations that match $inet_interfaces or $proxy_interfaces, +# - destinations that match $mydestination +# - destinations that match $virtual_alias_domains, +# - destinations that match $virtual_mailbox_domains. +# These destinations do not need to be listed in $relay_domains. +# +# Specify a list of hosts or domains, /file/name patterns or type:name +# lookup tables, separated by commas and/or whitespace. Continue +# long lines by starting the next line with whitespace. A file name +# is replaced by its contents; a type:name table is matched when a +# (parent) domain appears as lookup key. +# +# NOTE: Postfix will not automatically forward mail for domains that +# list this system as their primary or backup MX host. See the +# permit_mx_backup restriction description in postconf(5). +# +#relay_domains = $mydestination + +# INTERNET OR INTRANET + +# The relayhost parameter specifies the default host to send mail to +# when no entry is matched in the optional transport(5) table. When +# no relayhost is given, mail is routed directly to the destination. +# +# On an intranet, specify the organizational domain name. If your +# internal DNS uses no MX records, specify the name of the intranet +# gateway host instead. +# +# In the case of SMTP, specify a domain, host, host:port, [host]:port, +# [address] or [address]:port; the form [host] turns off MX lookups. +# +# If you're connected via UUCP, see also the default_transport parameter. +# +#relayhost = $mydomain +#relayhost = [gateway.my.domain] +#relayhost = [mailserver.isp.tld] +#relayhost = uucphost +#relayhost = [an.ip.add.ress] + +# REJECTING UNKNOWN RELAY USERS +# +# The relay_recipient_maps parameter specifies optional lookup tables +# with all addresses in the domains that match $relay_domains. +# +# If this parameter is defined, then the SMTP server will reject +# mail for unknown relay users. This feature is off by default. +# +# The right-hand side of the lookup tables is conveniently ignored. +# In the left-hand side, specify an @domain.tld wild-card, or specify +# a user@domain.tld address. +# +#relay_recipient_maps = hash:/etc/postfix/relay_recipients + +# INPUT RATE CONTROL +# +# The in_flow_delay configuration parameter implements mail input +# flow control. This feature is turned on by default, although it +# still needs further development (it's disabled on SCO UNIX due +# to an SCO bug). +# +# A Postfix process will pause for $in_flow_delay seconds before +# accepting a new message, when the message arrival rate exceeds the +# message delivery rate. With the default 100 SMTP server process +# limit, this limits the mail inflow to 100 messages a second more +# than the number of messages delivered per second. +# +# Specify 0 to disable the feature. Valid delays are 0..10. +# +#in_flow_delay = 1s + +# ADDRESS REWRITING +# +# The ADDRESS_REWRITING_README document gives information about +# address masquerading or other forms of address rewriting including +# username->Firstname.Lastname mapping. + +# ADDRESS REDIRECTION (VIRTUAL DOMAIN) +# +# The VIRTUAL_README document gives information about the many forms +# of domain hosting that Postfix supports. + +# "USER HAS MOVED" BOUNCE MESSAGES +# +# See the discussion in the ADDRESS_REWRITING_README document. + +# TRANSPORT MAP +# +# See the discussion in the ADDRESS_REWRITING_README document. + +# ALIAS DATABASE +# +# The alias_maps parameter specifies the list of alias databases used +# by the local delivery agent. The default list is system dependent. +# +# On systems with NIS, the default is to search the local alias +# database, then the NIS alias database. See aliases(5) for syntax +# details. +# +# If you change the alias database, run "postalias /etc/aliases" (or +# wherever your system stores the mail alias file), or simply run +# "newaliases" to build the necessary DBM or DB file. +# +# It will take a minute or so before changes become visible. Use +# "postfix reload" to eliminate the delay. +# +#alias_maps = dbm:/etc/aliases +alias_maps = hash:/etc/aliases +#alias_maps = hash:/etc/aliases, nis:mail.aliases +#alias_maps = netinfo:/aliases + +# The alias_database parameter specifies the alias database(s) that +# are built with "newaliases" or "sendmail -bi". This is a separate +# configuration parameter, because alias_maps (see above) may specify +# tables that are not necessarily all under control by Postfix. +# +#alias_database = dbm:/etc/aliases +#alias_database = dbm:/etc/mail/aliases +alias_database = hash:/etc/aliases +#alias_database = hash:/etc/aliases, hash:/opt/majordomo/aliases + +# ADDRESS EXTENSIONS (e.g., user+foo) +# +# The recipient_delimiter parameter specifies the separator between +# user names and address extensions (user+foo). See canonical(5), +# local(8), relocated(5) and virtual(5) for the effects this has on +# aliases, canonical, virtual, relocated and .forward file lookups. +# Basically, the software tries user+foo and .forward+foo before +# trying user and .forward. +# +#recipient_delimiter = + + +# DELIVERY TO MAILBOX +# +# The home_mailbox parameter specifies the optional pathname of a +# mailbox file relative to a user's home directory. The default +# mailbox file is /var/spool/mail/user or /var/mail/user. Specify +# "Maildir/" for qmail-style delivery (the / is required). +# +#home_mailbox = Mailbox +#home_mailbox = Maildir/ + +# The mail_spool_directory parameter specifies the directory where +# UNIX-style mailboxes are kept. The default setting depends on the +# system type. +# +#mail_spool_directory = /var/mail +#mail_spool_directory = /var/spool/mail + +# The mailbox_command parameter specifies the optional external +# command to use instead of mailbox delivery. The command is run as +# the recipient with proper HOME, SHELL and LOGNAME environment settings. +# Exception: delivery for root is done as $default_user. +# +# Other environment variables of interest: USER (recipient username), +# EXTENSION (address extension), DOMAIN (domain part of address), +# and LOCAL (the address localpart). +# +# Unlike other Postfix configuration parameters, the mailbox_command +# parameter is not subjected to $parameter substitutions. This is to +# make it easier to specify shell syntax (see example below). +# +# Avoid shell meta characters because they will force Postfix to run +# an expensive shell process. Procmail alone is expensive enough. +# +# IF YOU USE THIS TO DELIVER MAIL SYSTEM-WIDE, YOU MUST SET UP AN +# ALIAS THAT FORWARDS MAIL FOR ROOT TO A REAL USER. +# +#mailbox_command = /some/where/procmail +#mailbox_command = /some/where/procmail -a "$EXTENSION" + +# If using the cyrus-imapd IMAP server deliver local mail to the IMAP +# server using LMTP (Local Mail Transport Protocol), this is prefered +# over the older cyrus deliver program by setting the +# mailbox_transport as below: +# +# mailbox_transport = lmtp:unix:/var/lib/imap/socket/lmtp +# +# The efficiency of LMTP delivery for cyrus-imapd can be enhanced via +# these settings. +# +# local_destination_recipient_limit = 300 +# local_destination_concurrency_limit = 5 +# +# Of course you should adjust these settings as appropriate for the +# capacity of the hardware you are using. The recipient limit setting +# can be used to take advantage of the single instance message store +# capability of Cyrus. The concurrency limit can be used to control +# how many simultaneous LMTP sessions will be permitted to the Cyrus +# message store. +# +# Cyrus IMAP via command line. Uncomment the "cyrus...pipe" and +# subsequent line in master.cf. +#mailbox_transport = cyrus + +# The fallback_transport specifies the optional transport in master.cf +# to use for recipients that are not found in the UNIX passwd database. +# This parameter has precedence over the luser_relay parameter. +# +# Specify a string of the form transport:nexthop, where transport is +# the name of a mail delivery transport defined in master.cf. The +# :nexthop part is optional. For more details see the sample transport +# configuration file. +# +# NOTE: if you use this feature for accounts not in the UNIX password +# file, then you must update the "local_recipient_maps" setting in +# the main.cf file, otherwise the SMTP server will reject mail for +# non-UNIX accounts with "User unknown in local recipient table". +# +#fallback_transport = lmtp:unix:/var/lib/imap/socket/lmtp +#fallback_transport = + +# The luser_relay parameter specifies an optional destination address +# for unknown recipients. By default, mail for unknown@$mydestination, +# unknown@[$inet_interfaces] or unknown@[$proxy_interfaces] is returned +# as undeliverable. +# +# The following expansions are done on luser_relay: $user (recipient +# username), $shell (recipient shell), $home (recipient home directory), +# $recipient (full recipient address), $extension (recipient address +# extension), $domain (recipient domain), $local (entire recipient +# localpart), $recipient_delimiter. Specify ${name?value} or +# ${name:value} to expand value only when $name does (does not) exist. +# +# luser_relay works only for the default Postfix local delivery agent. +# +# NOTE: if you use this feature for accounts not in the UNIX password +# file, then you must specify "local_recipient_maps =" (i.e. empty) in +# the main.cf file, otherwise the SMTP server will reject mail for +# non-UNIX accounts with "User unknown in local recipient table". +# +#luser_relay = $user@other.host +#luser_relay = $local@other.host +#luser_relay = admin+$local + +# JUNK MAIL CONTROLS +# +# The controls listed here are only a very small subset. The file +# SMTPD_ACCESS_README provides an overview. + +# The header_checks parameter specifies an optional table with patterns +# that each logical message header is matched against, including +# headers that span multiple physical lines. +# +# By default, these patterns also apply to MIME headers and to the +# headers of attached messages. With older Postfix versions, MIME and +# attached message headers were treated as body text. +# +# For details, see "man header_checks". +# +#header_checks = regexp:/etc/postfix/header_checks + +# FAST ETRN SERVICE +# +# Postfix maintains per-destination logfiles with information about +# deferred mail, so that mail can be flushed quickly with the SMTP +# "ETRN domain.tld" command, or by executing "sendmail -qRdomain.tld". +# See the ETRN_README document for a detailed description. +# +# The fast_flush_domains parameter controls what destinations are +# eligible for this service. By default, they are all domains that +# this server is willing to relay mail to. +# +#fast_flush_domains = $relay_domains + +# SHOW SOFTWARE VERSION OR NOT +# +# The smtpd_banner parameter specifies the text that follows the 220 +# code in the SMTP server's greeting banner. Some people like to see +# the mail version advertised. By default, Postfix shows no version. +# +# You MUST specify $myhostname at the start of the text. That is an +# RFC requirement. Postfix itself does not care. +# +#smtpd_banner = $myhostname ESMTP $mail_name +#smtpd_banner = $myhostname ESMTP $mail_name ($mail_version) + +# PARALLEL DELIVERY TO THE SAME DESTINATION +# +# How many parallel deliveries to the same user or domain? With local +# delivery, it does not make sense to do massively parallel delivery +# to the same user, because mailbox updates must happen sequentially, +# and expensive pipelines in .forward files can cause disasters when +# too many are run at the same time. With SMTP deliveries, 10 +# simultaneous connections to the same domain could be sufficient to +# raise eyebrows. +# +# Each message delivery transport has its XXX_destination_concurrency_limit +# parameter. The default is $default_destination_concurrency_limit for +# most delivery transports. For the local delivery agent the default is 2. + +#local_destination_concurrency_limit = 2 +#default_destination_concurrency_limit = 20 + +# DEBUGGING CONTROL +debug_peer_level = 2 +debugger_command = + PATH=/bin:/usr/bin:/usr/local/bin:/usr/X11R6/bin + ddd $daemon_directory/$process_name $process_id & sleep 5 + +# INSTALL-TIME CONFIGURATION INFORMATION +sendmail_path = /usr/sbin/sendmail.postfix +newaliases_path = /usr/bin/newaliases.postfix +mailq_path = /usr/bin/mailq.postfix +setgid_group = postdrop +html_directory = no +manpage_directory = /usr/share/man +sample_directory = /usr/share/doc/postfix/samples +readme_directory = /usr/share/doc/postfix/README_FILES + +# TLS CONFIGURATION +# +# Basic Postfix TLS configuration by default with self-signed certificate +# for inbound SMTP and also opportunistic TLS for outbound SMTP. + +# The full pathname of a file with the Postfix SMTP server RSA certificate +# in PEM format. Intermediate certificates should be included in general, +# the server certificate first, then the issuing CA(s) (bottom-up order). +# +smtpd_tls_cert_file = /etc/pki/tls/private/postfix.pem + +# The full pathname of a file with the Postfix SMTP server RSA private key +# in PEM format. The private key must be accessible without a pass-phrase, +# i.e. it must not be encrypted. +# +smtpd_tls_key_file = /etc/pki/tls/private/postfix.pem + +# Announce STARTTLS support to remote SMTP clients, but do not require that +# clients use TLS encryption (opportunistic TLS inbound). +# +smtpd_tls_security_level = may + +# Directory with PEM format Certification Authority certificates that the +# Postfix SMTP client uses to verify a remote SMTP server certificate. +# +smtp_tls_CApath = /etc/pki/tls/certs + +# The full pathname of a file containing CA certificates of root CAs +# trusted to sign either remote SMTP server certificates or intermediate CA +# certificates. +# +smtp_tls_CAfile = /etc/pki/tls/certs/ca-bundle.crt + +# Use TLS if this is supported by the remote SMTP server, otherwise use +# plaintext (opportunistic TLS outbound). +# +smtp_tls_security_level = may +meta_directory = /etc/postfix +shlib_directory = /usr/lib64/postfix +recipient_delimiter = + +local_recipient_maps = mysql:/etc/postfix/sql/local_recipient_maps.cf +#transport_maps = ldap:/etc/postfix/ldap/transport_maps.cf, hash:/etc/postfix/transport +transport_maps = regexp:/etc/postfix/transport +#virtual_alias_maps = $alias_maps, ldap:/etc/postfix/ldap/virtual_alias_maps.cf, ldap:/etc/postfix/ldap/virtual_alias_maps_mailforwarding.cf, ldap:/etc/postfix/ldap/virtual_alias_maps_sharedfolders.cf, ldap:/etc/postfix/ldap/mailenabled_distgroups.cf, ldap:/etc/postfix/ldap/mailenabled_dynamic_distgroups.cf +virtual_alias_maps = $alias_maps +smtpd_tls_auth_only = no + +# Inbound +smtpd_client_restrictions = + #permit_mynetworks, + reject_unknown_reverse_client_hostname, + #reject_rbl_client zen.spamhaus.org, + #reject_rhsbl_reverse_client dbl.spamhaus.org +smtpd_data_restrictions = + reject_unauth_pipelining +smtpd_helo_required = yes +smtpd_helo_restrictions = + #permit_mynetworks, + reject_invalid_helo_hostname, + reject_non_fqdn_helo_hostname, + #reject_rhsbl_helo dbl.spamhaus.org +smtpd_recipient_restrictions = + #permit_mynetworks, + reject_invalid_hostname, + reject_non_fqdn_sender, + reject_non_fqdn_recipient, + reject_unauth_destination, + #reject_rhsbl_recipient dbl.spamhaus.org, + #check_recipient_access ldap:/etc/postfix/ldap/domain_suspended.cf, + #check_recipient_access ldap:/etc/postfix/ldap/account_suspended.cf, + check_policy_service unix:private/policy_greylist, + permit +smtpd_peername_lookup = yes +smtpd_sasl_auth_enable = yes + +smtpd_sender_login_maps = + mysql:/etc/postfix/sql/local_recipient_maps.cf + +smtpd_sender_restrictions = + #permit_mynetworks, + #check_sender_access hash:/etc/postfix/sender_access, + reject_unknown_sender_domain, + #check_client_access hash:/etc/postfix/client_access, + #check_client_access cidr:/etc/postfix/client_access_cidr, + reject_unlisted_sender, + # Uses smtpd_sender_login_maps + reject_unauthenticated_sender_login_mismatch, + reject_unauth_destination, + check_policy_service unix:private/policy_spf, + #reject_rhsbl_sender dbl.spamhaus.org, + permit + + +# Outbound +submission_data_restrictions = + check_policy_service unix:private/policy_ratelimit +submission_client_restrictions = + #reject_unknown_reverse_client_hostname, + #reject_rbl_client zen.spamhaus.org, + #reject_rhsbl_reverse_client dbl.spamhaus.org +submission_sender_restrictions = + reject_non_fqdn_sender, + # Uses smtpd_sender_login_maps + reject_sender_login_mismatch, + check_policy_service unix:private/policy_ratelimit + permit_sasl_authenticated, + reject +submission_helo_restrictions = +# permit_mynetworks, + reject_invalid_helo_hostname, + reject_non_fqdn_helo_hostname, + #reject_rhsbl_helo dbl.spamhaus.org +submission_recipient_restrictions = + # check_recipient_access hash:/etc/postfix/recipient_access, + # check_recipient_mx_access hash:/etc/postfix/recipient_mx_access, + # check_recipient_ns_access hash:/etc/postfix/recipient_ns_access, + check_policy_service unix:private/policy_ratelimit, + permit_sasl_authenticated, + # permit_mynetworks, + reject + +# LEGACY restrictions +#smtpd_data_restrictions = permit_mynetworks, check_policy_service unix:private/recipient_policy_incoming +#smtpd_recipient_restrictions = permit_mynetworks, reject_unauth_pipelining, reject_rbl_client zen.spamhaus.org, reject_non_fqdn_recipient, reject_invalid_helo_hostname, reject_unknown_recipient_domain, reject_unauth_destination, check_policy_service unix:private/recipient_policy_incoming, permit +#smtpd_sender_restrictions = permit_mynetworks, reject_sender_login_mismatch, check_policy_service unix:private/sender_policy_incoming + +#submission_recipient_restrictions = check_policy_service unix:private/submission_policy, permit_sasl_authenticated, reject +#submission_sender_restrictions = reject_non_fqdn_sender, check_policy_service unix:private/submission_policy, permit_sasl_authenticated, reject +#submission_data_restrictions = check_policy_service unix:private/submission_policy + +#content_filter = smtp-wallace:[127.0.0.1]:10026 +#content_filter = amavis:[127.0.0.1]:10024 + +maillog_file = /dev/stdout diff --git a/docker/postfix/rootfs/etc/postfix/master.cf b/docker/postfix/rootfs/etc/postfix/master.cf new file mode 100644 index 00000000..d895cb5a --- /dev/null +++ b/docker/postfix/rootfs/etc/postfix/master.cf @@ -0,0 +1,162 @@ +# Postfix master process configuration file. For details on the format +# of the file, see the master(5) manual page (command: "man 5 master"). +# Do not forget to execute "postfix reload" after editing this file. +# ============================================================================== +# service type private unpriv chroot wakeup maxproc command +# (yes) (yes) (yes) (never) (100) + args +# ============================================================================== + +postlog unix-dgram n - n - 1 postlogd +# Inbound, port 25, no tls +10025 inet n - n - - smtpd +# Submission, port 587, no tls, no starttls +10587 inet n - - - - smtpd + -o syslog_name=postfix/submission + -o cleanup_service_name=cleanup_submission + -o smtpd_sasl_auth_enable=yes + -o smtpd_client_restrictions=permit_sasl_authenticated,reject + -o smtpd_data_restrictions=$submission_data_restrictions + -o smtpd_recipient_restrictions=$submission_recipient_restrictions + -o smtpd_sender_restrictions=$submission_sender_restrictions + -o smtpd_client_restrictions=$submission_client_restrictions + -o smtpd_helo_restrictions=$submission_helo_restrictions + -o smtpd_helo_required=yes + -o smtpd_peername_lookup=no +pickup fifo n - n 60 1 pickup +cleanup unix n - n - 0 cleanup + -o header_checks=regexp:/etc/postfix/header_checks.inbound + -o mime_header_checks=regexp:/etc/postfix/header_checks.inbound +cleanup_submission unix n - n - 0 cleanup + -o header_checks=regexp:/etc/postfix/header_checks.submission + -o mime_header_checks=regexp:/etc/postfix/header_checks.submission +qmgr fifo n - n 300 1 qmgr +tlsmgr unix - - n 1000? 1 tlsmgr +rewrite unix - - n - - trivial-rewrite +bounce unix - - n - 0 bounce +defer unix - - n - 0 bounce +trace unix - - n - 0 bounce +verify unix - - n - 1 verify +flush unix n - n 1000? 0 flush +proxymap unix - - n - - proxymap +proxywrite unix - - n - 1 proxymap +smtp unix - - n - - smtp +relay unix - - n - - smtp +showq unix n - n - - showq +error unix - - n - - error +retry unix - - n - - error +discard unix - - n - - discard +local unix - n n - - local +virtual unix - n n - - virtual +lmtp unix - - n - - lmtp -v +anvil unix - - n - 1 anvil +scache unix - - n - 1 scache + +# Filter email through Amavisd +# smtp-amavis unix - - n - 3 smtp +# -o smtp_data_done_timeout=1800 +# -o disable_dns_lookups=yes +# -o smtp_send_xforward_command=yes +# -o max_use=20 +# -o smtp_bind_address=127.0.0.1 + +# Listener to re-inject email from Amavisd into Postfix +# 127.0.0.1:10025 inet n - n - 100 smtpd +# -o cleanup_service_name=cleanup_internal +# -o content_filter=smtp-wallace:[127.0.0.1]:10026 +# -o local_recipient_maps= +# -o relay_recipient_maps= +# -o smtpd_restriction_classes= +# -o smtpd_client_restrictions= +# -o smtpd_helo_restrictions= +# -o smtpd_sender_restrictions= +# -o smtpd_recipient_restrictions=permit_mynetworks,reject +# -o mynetworks=127.0.0.0/8 +# -o smtpd_authorized_xforward_hosts=127.0.0.0/8 + +# Filter email through Wallace +# smtp-wallace unix - - n - 3 smtp +# -o default_destination_recipient_limit=1 +# -o smtp_data_done_timeout=1800 +# -o disable_dns_lookups=yes +# -o smtp_send_xforward_command=yes +# -o max_use=20 + +# Listener to re-inject email from Wallace into Postfix +# 127.0.0.1:10027 inet n - n - 100 smtpd +# -o cleanup_service_name=cleanup_internal +# -o content_filter= +# -o local_recipient_maps= +# -o relay_recipient_maps= +# -o smtpd_restriction_classes= +# -o smtpd_client_restrictions= +# -o smtpd_helo_restrictions= +# -o smtpd_sender_restrictions= +# -o smtpd_recipient_restrictions=permit_mynetworks,reject +# -o mynetworks=127.0.0.0/8 +# -o smtpd_authorized_xforward_hosts=127.0.0.0/8 + +# Filter email through Amavisd +# amavis unix - - n - 3 smtp +# -o disable_dns_lookups=yes +# -o max_use=20 +# -o smtp_bind_address=127.0.0.1 +# -o smtp_data_done_timeout=1800 +# -o smtp_send_xforward_command=yes +# -o smtp_tls_security_level=none + +# Reinjection from amavis +# 127.0.0.1:10025 inet n - n - 100 smtpd +# -o cleanup_service_name=cleanup_outbound +# -o content_filter= +# -o local_recipient_maps= +# -o mydestination= +# -o mynetworks=127.0.0.0/8 +# -o relay_domains= +# -o relay_recipient_maps= +# -o smtpd_authorized_xforward_hosts=127.0.0.0/8 +# -o smtpd_restriction_classes= +# -o smtpd_client_restrictions= +# -o smtpd_data_restrictions= +# -o smtpd_helo_restrictions= +# -o smtpd_sender_restrictions= +# -o smtpd_recipient_restrictions=permit_mynetworks,reject +# -o syslog_name=postfix/amavis + +# Outbound +policy_ratelimit unix - n n - - spawn + user=nobody argv=/usr/libexec/postfix/kolab_policy_ratelimit + +# Inbound +policy_greylist unix - n n - - spawn + user=nobody argv=/usr/libexec/postfix/kolab_policy_greylist + +# Inbound +policy_spf unix - n n - - spawn + user=nobody argv=/usr/libexec/postfix/kolab_policy_spf + +#0.0.0.0:10587 inet n - n - - smtpd +# -o cleanup_service_name=cleanup_submission +# -o syslog_name=postfix/submission +# #-o smtpd_tls_security_level=encrypt +# -o smtpd_sasl_auth_enable=yes +# -o smtpd_sasl_authenticated_header=yes +# -o smtpd_client_restrictions=permit_sasl_authenticated,reject +# -o smtpd_data_restrictions=$submission_data_restrictions +# -o smtpd_recipient_restrictions=$submission_recipient_restrictions +# -o smtpd_sender_restrictions=$submission_sender_restrictions + +#0.0.0.0:10465 inet n - n - - smtpd +# -o cleanup_service_name=cleanup_submission +# -o rewrite_service_name=rewrite_submission +# -o syslog_name=postfix/smtps +# -o mydestination= +# -o local_recipient_maps= +# -o relay_domains= +# -o relay_recipient_maps= +# #-o smtpd_tls_wrappermode=yes +# -o smtpd_sasl_auth_enable=yes +# -o smtpd_sasl_authenticated_header=yes +# -o smtpd_client_restrictions=permit_sasl_authenticated,reject +# -o smtpd_sender_restrictions=$submission_sender_restrictions +# -o smtpd_recipient_restrictions=$submission_recipient_restrictions +# -o smtpd_data_restrictions=$submission_data_restrictions diff --git a/docker/postfix/rootfs/etc/postfix/sql/local_recipient_maps.cf b/docker/postfix/rootfs/etc/postfix/sql/local_recipient_maps.cf new file mode 100644 index 00000000..61ffeb32 --- /dev/null +++ b/docker/postfix/rootfs/etc/postfix/sql/local_recipient_maps.cf @@ -0,0 +1,5 @@ +hosts = DB_HOST +user = DB_USERNAME +password = DB_PASSWORD +dbname = DB_DATABASE +query = SELECT email FROM users WHERE email = '%u@%d' AND status & 2 AND NOT status & 4 AND NOT status & 8 diff --git a/docker/postfix/rootfs/etc/postfix/transport b/docker/postfix/rootfs/etc/postfix/transport new file mode 100644 index 00000000..3d53f03a --- /dev/null +++ b/docker/postfix/rootfs/etc/postfix/transport @@ -0,0 +1,318 @@ +# TRANSPORT(5) TRANSPORT(5) +# +# NAME +# transport - Postfix transport table format +# +# SYNOPSIS +# postmap /etc/postfix/transport +# +# postmap -q "string" /etc/postfix/transport +# +# postmap -q - /etc/postfix/transport = 3.5): +# +# example.com smtp:bar.example, foo.example +# +# This tries to deliver to bar.example before trying to +# deliver to foo.example. +# +# The error mailer can be used to bounce mail: +# +# .example.com error:mail for *.example.com is not deliverable +# +# This causes all mail for user@anything.example.com to be +# bounced. +# +# REGULAR EXPRESSION TABLES +# This section describes how the table lookups change when +# the table is given in the form of regular expressions. For +# a description of regular expression lookup table syntax, +# see regexp_table(5) or pcre_table(5). +# +# Each pattern is a regular expression that is applied to +# the entire address being looked up. Thus, +# some.domain.hierarchy is not looked up via its parent +# domains, nor is user+foo@domain looked up as user@domain. +# +# Patterns are applied in the order as specified in the ta- +# ble, until a pattern is found that matches the search +# string. +# +# The trivial-rewrite(8) server disallows regular expression +# substitution of $1 etc. in regular expression lookup +# tables, because that could open a security hole (Postfix +# version 2.3 and later). +# +# TCP-BASED TABLES +# This section describes how the table lookups change when +# lookups are directed to a TCP-based server. For a descrip- +# tion of the TCP client/server lookup protocol, see tcp_ta- +# ble(5). This feature is not available up to and including +# Postfix version 2.4. +# +# Each lookup operation uses the entire recipient address +# once. Thus, some.domain.hierarchy is not looked up via +# its parent domains, nor is user+foo@domain looked up as +# user@domain. +# +# Results are the same as with indexed file lookups. +# +# CONFIGURATION PARAMETERS +# The following main.cf parameters are especially relevant. +# The text below provides only a parameter summary. See +# postconf(5) for more details including examples. +# +# empty_address_recipient (MAILER-DAEMON) +# The recipient of mail addressed to the null +# address. +# +# parent_domain_matches_subdomains (see 'postconf -d' out- +# put) +# A list of Postfix features where the pattern "exam- +# ple.com" also matches subdomains of example.com, +# instead of requiring an explicit ".example.com" +# pattern. +# +# transport_maps (empty) +# Optional lookup tables with mappings from recipient +# address to (message delivery transport, next-hop +# destination). +# +# SEE ALSO +# trivial-rewrite(8), rewrite and resolve addresses +# master(5), master.cf file format +# postconf(5), configuration parameters +# postmap(1), Postfix lookup table manager +# +# README FILES +# Use "postconf readme_directory" or "postconf html_direc- +# tory" to locate this information. +# ADDRESS_REWRITING_README, address rewriting guide +# DATABASE_README, Postfix lookup table overview +# FILTER_README, external content filter +# +# LICENSE +# The Secure Mailer license must be distributed with this +# software. +# +# AUTHOR(S) +# Wietse Venema +# IBM T.J. Watson Research +# P.O. Box 704 +# Yorktown Heights, NY 10598, USA +# +# Wietse Venema +# Google, Inc. +# 111 8th Avenue +# New York, NY 10011, USA +# +# TRANSPORT(5) + diff --git a/docker/postfix/rootfs/etc/saslauthd.conf b/docker/postfix/rootfs/etc/saslauthd.conf new file mode 100644 index 00000000..1d1d3be0 --- /dev/null +++ b/docker/postfix/rootfs/etc/saslauthd.conf @@ -0,0 +1,4 @@ +httpform_host: services.APP_DOMAIN +httpform_port: 8000 +httpform_uri: /api/webhooks/cyrus-sasl/ +httpform_data: %u %r %p diff --git a/docker/postfix/rootfs/init.sh b/docker/postfix/rootfs/init.sh new file mode 100755 index 00000000..69f7918b --- /dev/null +++ b/docker/postfix/rootfs/init.sh @@ -0,0 +1,38 @@ +#!/bin/bash + +sed -i -r \ + -e "s|APP_DOMAIN|$APP_DOMAIN|g" \ + /etc/saslauthd.conf + +/usr/sbin/saslauthd -m /run/saslauthd -a httpform -d & + +# If host mounting /var/spool/postfix, we need to delete old pid file before +# starting services +rm -f /var/spool/postfix/pid/master.pid + +/usr/libexec/postfix/aliasesdb +/usr/libexec/postfix/chroot-update + +sed -i -r \ + -e "s|LMTP_DESTINATION|$LMTP_DESTINATION|g" \ + /etc/postfix/main.cf + +sed -i -r \ + -e "s|APP_DOMAIN|$APP_DOMAIN|g" \ + /etc/postfix/main.cf + +sed -i -r \ + -e "s|APP_DOMAIN|$APP_DOMAIN|g" \ + /usr/libexec/postfix/kolab_policy* + +sed -i -r \ + -e "s|DB_HOST|$DB_HOST|g" \ + -e "s|DB_USERNAME|$DB_USERNAME|g" \ + -e "s|DB_PASSWORD|$DB_PASSWORD|g" \ + -e "s|DB_DATABASE|$DB_DATABASE|g" \ + /etc/postfix/sql/* + +# echo "/$APP_DOMAIN/ lmtp:$LMTP_DESTINATION" >> /etc/postfix/transport +# postmap /etc/postfix/transport + +exec /usr/sbin/postfix -c /etc/postfix start-fg diff --git a/docker/postfix/rootfs/usr/libexec/postfix/kolab_policy_greylist b/docker/postfix/rootfs/usr/libexec/postfix/kolab_policy_greylist new file mode 100755 index 00000000..79e85d83 --- /dev/null +++ b/docker/postfix/rootfs/usr/libexec/postfix/kolab_policy_greylist @@ -0,0 +1,81 @@ +#!/usr/bin/python3 +""" +An example implementation of a policy service. +""" + +import json +import time +import sys + +import requests + + +def read_request_input(): + """ + Read a single policy request from sys.stdin, and return a dictionary + containing the request. + """ + start_time = time.time() + + policy_request = {} + end_of_request = False + + while not end_of_request: + if (time.time() - start_time) >= 10: + print("action=DEFER_IF_PERMIT Temporary error, try again later.\n") + sys.stdout.flush() + sys.exit(0) + + request_line = sys.stdin.readline() + + if request_line.strip() == '': + if 'request' in policy_request: + end_of_request = True + else: + request_line = request_line.strip() + request_key = request_line.split('=')[0] + request_value = '='.join(request_line.split('=')[1:]) + + policy_request[request_key] = request_value + + return policy_request + + +if __name__ == "__main__": + URL = 'https://services.APP_DOMAIN/api/webhooks/policy/greylist' + + # Start the work + while True: + REQUEST = read_request_input() + + try: + RESPONSE = requests.post( + URL, + data=REQUEST, + verify=True + ) + # pylint: disable=broad-except + except Exception: + print("action=DEFER_IF_PERMIT Temporary error, try again later.\n") + sys.stdout.flush() + sys.exit(0) + + try: + R = json.loads(RESPONSE.text) + # pylint: disable=broad-except + except Exception: + print("action=DEFER_IF_PERMIT Temporary error, try again later.\n") + sys.stdout.flush() + sys.exit(0) + + if 'prepend' in R: + for prepend in R['prepend']: + print("action=PREPEND {0}".format(prepend)) + + if RESPONSE.ok: + print("action={0}\n".format(R['response'])) + else: + print("action={0} {1}\n".format(R['response'], R['reason'])) + + sys.stdout.flush() + sys.exit(0) diff --git a/docker/postfix/rootfs/usr/libexec/postfix/kolab_policy_ratelimit b/docker/postfix/rootfs/usr/libexec/postfix/kolab_policy_ratelimit new file mode 100755 index 00000000..d95fe1a8 --- /dev/null +++ b/docker/postfix/rootfs/usr/libexec/postfix/kolab_policy_ratelimit @@ -0,0 +1,144 @@ +#!/usr/bin/python3 +""" +This policy applies rate limitations +""" + +import json +import time +import sys + +import requests + + +class PolicyRequest: + """ + A holder of policy request instances. + """ + db = None + recipients = [] + sender = None + + def __init__(self, request): + """ + Initialize a policy request, usually in RCPT protocol state. + """ + if 'sender' in request: + self.sender = request['sender'] + + if 'recipient' in request: + request['recipient'] = request['recipient'] + + self.recipients.append(request['recipient']) + + def add_request(self, request): + """ + Add an additional request from an instance to the existing instance + """ + # Normalize email addresses (they may contain recipient delimiters) + if 'recipient' in request: + request['recipient'] = request['recipient'] + + if not request['recipient'].strip() == '': + self.recipients.append(request['recipient']) + + def check_rate(self): + """ + Check the rates at which this sender is hitting our mailserver. + """ + if self.sender == "": + return {'response': 'DUNNO'} + + try: + response = requests.post( + URL, + data={ + 'sender': self.sender, + 'recipients': self.recipients + }, + verify=True + ) + + # pylint: disable=broad-except + except Exception: + print("action=DEFER_IF_PERMIT Temporary error, try again later.\n") + sys.stdout.flush() + sys.exit(0) + + return response + + +def read_request_input(): + """ + Read a single policy request from sys.stdin, and return a dictionary + containing the request. + """ + start_time = time.time() + + policy_request = {} + end_of_request = False + + while not end_of_request: + if (time.time() - start_time) >= 10: + print("action=DEFER_IF_PERMIT Temporary error, try again later.\n") + sys.stdout.flush() + sys.exit(0) + + request_line = sys.stdin.readline() + + if request_line.strip() == '': + if 'request' in policy_request: + end_of_request = True + else: + request_line = request_line.strip() + request_key = request_line.split('=')[0] + request_value = '='.join(request_line.split('=')[1:]) + + policy_request[request_key] = request_value + + return policy_request + + +if __name__ == "__main__": + URL = 'https://services.APP_DOMAIN/api/webhooks/policy/ratelimit' + + POLICY_REQUESTS = {} + + # Start the work + while True: + POLICY_REQUEST = read_request_input() + + INSTANCE = POLICY_REQUEST['instance'] + + if INSTANCE in POLICY_REQUESTS: + POLICY_REQUESTS[INSTANCE].add_request(POLICY_REQUEST) + else: + POLICY_REQUESTS[INSTANCE] = PolicyRequest(POLICY_REQUEST) + + protocol_state = POLICY_REQUEST['protocol_state'].strip().lower() + + if not protocol_state == 'data': + print("action=DUNNO\n") + sys.stdout.flush() + + else: + RESPONSE = POLICY_REQUESTS[INSTANCE].check_rate() + + try: + R = json.loads(RESPONSE.text) + # pylint: disable=broad-except + except Exception: + print("action=DEFER_IF_PERMIT Temporary error, try again later.\n") + sys.stdout.flush() + sys.exit(0) + + if 'prepend' in R: + for prepend in R['prepend']: + print("action=PREPEND {0}".format(prepend)) + + if 'reason' in R: + print("action={0} {1}\n".format(R['response'], R['reason'])) + else: + print("action={0}\n".format(R['response'])) + + sys.stdout.flush() + sys.exit(0) diff --git a/docker/postfix/rootfs/usr/libexec/postfix/kolab_policy_spf b/docker/postfix/rootfs/usr/libexec/postfix/kolab_policy_spf new file mode 100755 index 00000000..e497f6fd --- /dev/null +++ b/docker/postfix/rootfs/usr/libexec/postfix/kolab_policy_spf @@ -0,0 +1,95 @@ +#!/usr/bin/python3 +""" +This is the implementation of a (postfix) MTA policy service to enforce the +Sender Policy Framework. +""" + +import json +import time +import sys +import logging +from logging.handlers import SysLogHandler + +import requests + +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) +logger.addHandler(SysLogHandler()) + +def read_request_input(): + """ + Read a single policy request from sys.stdin, and return a dictionary + containing the request. + """ + start_time = time.time() + + policy_request = {} + end_of_request = False + + while not end_of_request: + if (time.time() - start_time) >= 10: + logger.warning("policy/spf took too long reading the request.") + print("action=DEFER_IF_PERMIT Temporary error, try again later.\n") + sys.stdout.flush() + sys.exit(0) + + request_line = sys.stdin.readline() + + if request_line.strip() == '': + if 'request' in policy_request: + end_of_request = True + else: + request_line = request_line.strip() + request_key = request_line.split('=')[0] + request_value = '='.join(request_line.split('=')[1:]) + + policy_request[request_key] = request_value + + return policy_request + + +if __name__ == "__main__": + URL = 'https://services.APP_DOMAIN/api/webhooks/policy/spf' + + # Start the work + while True: + REQUEST = read_request_input() + + try: + RESPONSE = requests.post( + URL, + data=REQUEST, + verify=True + ) + # pylint: disable=broad-except + except Exception: + logger.warning("policy/spf request failed.") + print("action=DEFER_IF_PERMIT Temporary error, try again later.\n") + sys.stdout.flush() + sys.exit(0) + + try: + R = json.loads(RESPONSE.text) + # pylint: disable=broad-except + except Exception: + logger.warning("Failed to load json from policy/spf request.") + print("action=DEFER_IF_PERMIT Temporary error, try again later.\n") + sys.stdout.flush() + sys.exit(0) + + if 'prepend' in R: + for prepend in R['prepend']: + print("action=PREPEND {0}".format(prepend)) + + if 'log' in R: + for line in R['log']: + logger.warning(line) + + if RESPONSE.ok: + print("action={0}\n".format(R['response'])) + else: + print("action={0} {1}\n".format(R['response'], R['reason'])) + logger.warning("spf failed with reason: %s" % R['reason']) + + sys.stdout.flush() + sys.exit(0)