POSTFWD...L-IN-ONE(1)

πŸ¦‹ postfwd(1) β€” postfix firewall daemon πŸ¦‹

(User Contributed Perl Documentation)


✨ NAME ✨

postfwd β€” postfix firewall daemon πŸ’…


🌸 SYNOPSIS 🌸

okay bestie, here's the vibe: you run this thing like

postfwd [OPTIONS] [SOURCE1, SOURCE2, ...]

and then you've got a whole menu of options, grouped by what they do. let's get into it 🫢

πŸŽ€ Ruleset: (at least one, multiple use is allowed):

  • -f, --file <file> β€” reads rules from <file> πŸ“‚
  • -r, --rule <rule> β€” adds <rule> to config ✍️

πŸŽ€ Scoring:

  • -s, --scores <v>=<r> β€” returns <r> when score exceeds <v> πŸ“ˆ

πŸŽ€ Control:

  • -d, --daemon β€” run postfwd as daemon πŸ‘‘
  • -k, --kill β€” stops daemon πŸ›‘
  • --reload β€” reloads configuration πŸ”„
  • --dumpstats β€” displays usage statistics πŸ“Š
  • --dumpcache β€” displays cache contents πŸ—‚οΈ
  • --delcache <item> β€” removes an item from the request cache 🧹
  • --delrate <item> β€” removes an item from the rate cache 🧽

πŸŽ€ Networking:

  • -i, --interface <dev> β€” listen on interface <dev> 🌐
  • -p, --port <port> β€” listen on port <port> πŸšͺ
  • --proto <proto> β€” socket type (tcp or unix) πŸ”Œ
  • -u, --user <name> β€” set uid to user <name> πŸ‘€
  • -g, --group <name> β€” set gid to group <name> πŸ‘₯
  • --umask <mask> β€” set umask for file permissions πŸ”’
  • -R, --chroot <path> β€” chroot the daemon to <path> πŸ“
  • --pidfile <path> β€” create pidfile under <path> πŸ“
  • --facility <f> β€” syslog facility 🏷️
  • --socktype <s> β€” syslog socktype 🧦
  • -l, --logname <label> β€” label for syslog messages 🏷️
  • --loglen <int> β€” truncates syslogs after <int> chars βœ‚οΈ

πŸŽ€ Caching:

  • -c, --cache <int> β€” sets the request-cache timeout to <int> seconds ⏱️
  • --cache-no-size β€” ignores size attribute for caching πŸ“
  • --cache-no-sender β€” ignores sender address in cache πŸ“§
  • --cache-rdomain-only β€” ignores localpart of recipient address in cache πŸ“¨
  • --cache-rbl-timeout β€” default rbl timeout, if not specified in ruleset ⏳
  • --cache-rbl-default β€” default rbl response pattern to match (regexp) πŸ”
  • --cacheid <item>, .. β€” list of attributes for request cache identifier πŸ†”
  • --cleanup-requests β€” cleanup interval in seconds for request cache 🧼
  • --cleanup-rbls β€” cleanup interval in seconds for rbl cache 🧼
  • --cleanup-rates β€” cleanup interval in seconds for rate cache 🧼

πŸŽ€ Optional:

  • -t, --test β€” testing, always returns "dunno" πŸ§ͺ
  • -v, --verbose β€” verbose logging, use twice (-vv) to increase level πŸ—£οΈ
  • -S, --summary <int> β€” show some usage statistics every <int> seconds πŸ“ˆ
  • --norulelog β€” disbles rule logging 🚫
  • --norulestats β€” disables per rule statistics πŸ“‰
  • --noidlestats β€” disables statistics when idle 😴
  • -n, --nodns β€” disable dns 🚫
  • --nodnslog β€” disable dns logging 🚫
  • --dns_async_txt β€” perform dnsbl A and TXT lookups simultaneously ⚑
  • --dns_timeout β€” timeout in seconds for asynchonous dns queries ⏱️
  • --dns_timeout_max β€” maximum of dns timeouts until a dnsbl will be deactivated πŸ›‘
  • --dns_timeout_interval β€” interval in seconds for dns timeout maximum counter ⏲️
  • --dns_max_ns_lookups β€” max names to look up with sender_ns_addrs πŸ”Ž
  • --dns_max_mx_lookups β€” max names to look up with sender_mx_addrs πŸ”Ž
  • -I, --instantcfg β€” re-reads rulefiles for every new request πŸ”„
  • --config_timeout <i> β€” parser timeout in seconds ⏱️
  • --keep_rates β€” do not clear rate limit counters on reload πŸ’Ύ
  • --save_rates <file> β€” save and load rate limits on disk πŸ’Ύ
  • --fast_limit_evaluation β€” evaluate rate limits before ruleset is parsed (please note the limitations) ⚠️

πŸŽ€ Plugins:

  • --plugins <file> β€” loads postfwd plugins from file πŸ”Œ

πŸŽ€ Informational (use only at command-line!):

  • -C, --showconfig β€” shows ruleset summary, -v for verbose πŸ“‹
  • -L, --stdoutlog β€” redirect syslog messages to stdout πŸ–₯️
  • -P, --perfmon β€” no syslogging, no stdout 🀫
  • -V, --version β€” shows program version 🏷️
  • -h, --help β€” shows usage πŸ†˜
  • -m, --manual β€” shows program manual πŸ“–

πŸ’– DESCRIPTION πŸ’–

πŸ¦‹ INTRODUCTION πŸ¦‹

okay so postfwd is literally written to combine complex postfix restrictions in a ruleset, kinda like the most firewalls do. πŸ”₯ The program uses the postfix policy delegation protocol to control access to the mail system before a message has been accepted β€” please visit <http://www.postfix.org/SMTPD_POLICY_README.html> for more info, bestie. πŸ’Œ

postfwd lets you choose an action (like reject, dunno) for a combination of several smtp parameters β€” think sender and recipient address, size, or the client's TLS fingerprint. It also offers simple macros/acls that make for straightforward and easy-to-read configurations. no cap, it's giving organized. ✨

Features:

  • Complex combinations of smtp parameters
  • Combined RBL/RHSBL lookups with arbitrary actions depending on results
  • Scoring system
  • Date/time based rules
  • Macros/ACLs, Groups, Negation
  • Compare request attributes (e.g. client_name and helo_name)
  • Internal caching for requests and dns lookups
  • Built in statistics for rule efficiency analysis

πŸŽ€ CONFIGURATION πŸŽ€

A configuration line consists of optional item=value pairs, separated by semicolons (;) and the appropriate desired action:

[ <item1>=<value>; <item2>=<value>; ... ] action=<result>

Example:

client_address=192.168.1.1 ; sender==no@bad.local ; action=REJECT

This will deny all mail from 192.168.1.1 with envelope sender no@bad.local. The order of the elements is not important. So the following would lead to the same result as the previous example:

action=REJECT ; client_address=192.168.1.1 ; sender==no@bad.local

The way how request items are compared to the ruleset can be influenced in the following way:

====================================================================
 ITEM == VALUE                true if ITEM equals VALUE
 ITEM => VALUE                true if ITEM >= VALUE
 ITEM =< VALUE                true if ITEM <= VALUE
 ITEM >  VALUE                true if ITEM >  VALUE
 ITEM <  VALUE                true if ITEM <  VALUE
 ITEM =~ VALUE                true if ITEM ~= /^VALUE$/i
 ITEM != VALUE                false if ITEM equals VALUE
 ITEM !> VALUE                false if ITEM >= VALUE
 ITEM !< VALUE                false if ITEM <= VALUE
 ITEM !~ VALUE                false if ITEM ~= /^VALUE$/i
 ITEM =  VALUE                default behaviour (see ITEMS section)
====================================================================

To identify single rules in your log files, you may add an unique identifier for each of it:

id=R_001 ; action=REJECT ; client_address=192.168.1.1 ; sender==no@bad.local

You may use these identifiers as target for the jump() command (see ACTIONS section below). Leading or trailing whitespace characters will be ignored. Use # to comment your configuration. Others will appreciate. πŸ™

A ruleset consists of one or multiple rules, which can be loaded from files or passed as command line arguments. Please see the COMMAND LINE section below for more information on this topic. πŸ“š

Since postfwd version 1.30 rules spanning span multiple lines can be defined by prefixing the following lines with one or multiple whitespace characters (or } for macros):

id=RULE001
        client_address=192.168.1.0/24
        sender==no@bad.local
        action=REJECT no access

postfwd versions prior to 1.30 require trailing ; and \-characters:

id=RULE001; \
        client_address=192.168.1.0/24; \
        sender==no@bad.local; \
        action=REJECT no access

πŸ’… ITEMS πŸ’…

  • id β€” a unique rule id, which can be used for log analysis. ids also serve as targets for the "jump" command. πŸ†”
  • date, time β€” a time or date range within the specified rule shall hit
# FORMAT:
# Feb, 29th
date=29.02.2008
# Dec, 24th - 26th
date=24.12.2008-26.12.2008
# from today until Nov, 23rd
date=-23.09.2008
# from April, 1st until today
date=01.04.2008-
  • days, months β€” a range of weekdays (Sun-Sat) or months (Jan-Dec) within the specified rule shall hit πŸ“…
  • score β€” when the specified score is hit (see ACTIONS section) the specified action will be returned to postfix. scores are set global until redefined! πŸ’―
  • request_score β€” this value allows one to access a request's score. it may be used as variable ($$request_score). πŸ”’
  • rbl, rhsbl, rhsbl_client, rhsbl_sender, rhsbl_reverse_client β€” query the specified RBLs/RHSBLs, possible values are: <name>[/<reply>/<maxcache>, <name>/<reply>/<maxcache>] (defaults: reply=^127\.0\.0\.\d+$ maxcache=3600). the results of all rhsbl_* queries will be combined in rhsbl_count (see below). πŸ”
  • rblcount, rhsblcount β€” minimum RBL/RHSBL hitcounts to match. if not specified a single RBL/RHSBL hit will match the rbl/rhsbl items. you may specify 'all' to evaluate all items, and use it as variable in an action (see ACTIONS section) (default: 1). πŸ”’
  • sender_localpart, sender_domain β€” the local-/domainpart of the sender address πŸ“§
  • recipient_localpart, recipient_domain β€” the local-/domainpart of the recipient address πŸ“¨
  • helo_address β€” postfwd tries to look up the helo_name. use helo_address=!!(0.0.0.0/0) to check for unknown. Please do not use this for positive access control (whitelisting), as it might be forged.
  • sender_ns_names, sender_ns_addrs β€” postfwd tries to look up the names/ip addresses of the nameservers for the sender domain part. Please do not use this for positive access control (whitelisting), as it might be forged.
  • sender_mx_names, sender_mx_addrs β€” postfwd tries to look up the names/ip addresses of the mx records for the sender domain part. Please do not use this for positive access control (whitelisting), as it might be forged.
  • version β€” postfwd version, contains "postfwd n.nn". this enables version based checks in your rulesets (e.g. for migration). works with old versions too, because a non-existing item always returns false:
# version >= 1.10
id=R01; version~=1\.[1-9][0-9]; sender_domain==some.org \
      ; action=REJECT sorry no access
  • ratecount β€” only available for rate(), size() and rcpt() actions. contains the actual limit counter:
id=R01; action=rate(sender/200/600/REJECT limit of 200 exceeded [$$ratecount hits])
id=R02; action=rate(sender/100/600/WARN limit of 100 exceeded [$$ratecount hits])

Besides these you can specify any attribute of the postfix policy delegation protocol. Feel free to combine them the way you need it (have a look at the EXAMPLES section below).

Most values can be specified as regular expressions (PCRE). Please see the table below for details:

# ==========================================================
# ITEM=VALUE                            TYPE
# ==========================================================
id=something                            mask = string
date=01.04.2007-22.04.2007              mask = date (DD.MM.YYYY-DD.MM.YYYY)
time=08:30:00-17:00:00                  mask = time (HH:MM:SS-HH:MM:SS)
days=Mon-Wed                            mask = weekdays (Mon-Wed) or numeric (1-3)
months=Feb-Apr                          mask = months (Feb-Apr) or numeric (1-3)
score=5.0                               mask = maximum floating point value
rbl=zen.spamhaus.org                    mask = <name>/<reply>/<maxcache>[,...]
rblcount=2                              mask = numeric, will match if rbl hits >= 2
helo_address=<a.b.c.d/nn>               mask = CIDR[,CIDR,...]
sender_ns_names=some.domain.tld         mask = PCRE
sender_mx_names=some.domain.tld         mask = PCRE
sender_ns_addrs=<a.b.c.d/nn>            mask = CIDR[,CIDR,...]
sender_mx_addrs=<a.b.c.d/nn>            mask = CIDR[,CIDR,...]
# ------------------------------
# Postfix version 2.1 and later:
# ------------------------------
client_address=<a.b.c.d/nn>             mask = CIDR[,CIDR,...]
client_name=another.domain.tld          mask = PCRE
reverse_client_name=another.domain.tld  mask = PCRE
helo_name=some.domain.tld               mask = PCRE
sender=foo@bar.tld                      mask = PCRE
recipient=bar@foo.tld                   mask = PCRE
recipient_count=5                       mask = numeric, will match if recipients >= 5
# ------------------------------
# Postfix version 2.2 and later:
# ------------------------------
sasl_method=plain                       mask = PCRE
sasl_username=you                       mask = PCRE
sasl_sender=                            mask = PCRE
size=12345                              mask = numeric, will match if size >= 12345
ccert_subject=blackhole.nowhere.local   mask = PCRE (only if tls verified)
ccert_issuer=John+20Doe                 mask = PCRE (only if tls verified)
ccert_fingerprint=AA:BB:CC:DD:EE:...    mask = PCRE (do NOT use "..." here)
# ------------------------------
# Postfix version 2.3 and later:
# ------------------------------
encryption_protocol=TLSv1/SSLv3         mask = PCRE
encryption_cipher=DHE-RSA-AES256-SHA    mask = PCRE
encryption_keysize=256                  mask = numeric, will match if keysize >= 256
...

the current list can be found at <http://www.postfix.org/SMTPD_POLICY_README.html>. Please read carefully about which attribute can be used at which level of the smtp transaction (e.g. size will only work reliably at END-OF-MESSAGE level). Pattern matching is performed case insensitive.

Multiple use of the same item is allowed and will compared as logical OR, which means that this will work as expected:

id=TRUST001; action=OK; encryption_keysize=64
        ccert_fingerprint=11:22:33:44:55:66:77:88:99
        ccert_fingerprint=22:33:44:55:66:77:88:99:00
        ccert_fingerprint=33:44:55:66:77:88:99:00:11
        sender=@domain\.local$

client_address, rbl and rhsbl items may also be specified as whitespace- or-comma-separated values:

id=SKIP01; action=dunno
        client_address=192.168.1.0/24, 172.16.254.23
id=SKIP02; action=dunno
        client_address=10.10.3.32 10.216.222.0/27

The following items currently have to be unique:

id, minimum and maximum values, rblcount and rhsblcount

Any item can be negated by preceding '!!' to it, e.g.:

id=HOST001 ;  hostname == !!secure.trust.local ;  action=REJECT only secure.trust.local please

or using the right compare operator:

id=HOST001 ;  hostname != secure.trust.local ;  action=REJECT only secure.trust.local please

To avoid confusion with regexps or simply for better visibility you can use '!!(...)':

id=USER01 ;  sasl_username = !!( (bob|alice) )  ;  action=REJECT who is that?

Request attributes can be compared by preceding '$$' characters, e.g.:

id=R-003 ;  client_name = !! $$helo_name      ;  action=WARN helo does not match DNS
# or
id=R-003 ;  client_name = !!($$(helo_name))   ;  action=WARN helo does not match DNS

This is only valid for PCRE values (see list above). The comparison will be performed as case insensitive exact match. Use the -vv option to debug.

These special items will be reset for any new rule:

rblcount        - contains the number of RBL answers
rhsblcount      - contains the number of RHSBL answers
matches         - contains the number of matched items
dnsbltext       - contains the dns TXT part of all RBL and RHSBL replies in the form
                  rbltype:rblname:<txt>; rbltype:rblname:<txt>; ...

These special items will be changed for any matching rule:

request_hits    - contains ids of all matching rules

This means that it might be necessary to save them, if you plan to use these values in later rules:

# set vals
id=RBL01 ; rhsblcount=all; rblcount=all
        action=set(HIT_rhls=$$rhsblcount,HIT_rbls=$$rblcount,HIT_txt=$$dnsbltext)
        rbl=list.dsbl.org, bl.spamcop.net, dnsbl.sorbs.net, zen.spamhaus.org
        rhsbl_client=rddn.dnsbl.net.au, rhsbl.ahbl.org, rhsbl.sorbs.net
        rhsbl_sender=rddn.dnsbl.net.au, rhsbl.ahbl.org, rhsbl.sorbs.net

# compare
id=RBL02 ; HIT_rhls>=1 ; HIT_rbls>=1 ; action=554 5.7.1 blocked using $$HIT_rhls RHSBLs and $$HIT_rbls RBLs [INFO: $$HIT_txt]
id=RBL03 ; HIT_rhls>=2               ; action=554 5.7.1 blocked using $$HIT_rhls RHSBLs [INFO: $$HIT_txt]
id=RBL04 ; HIT_rbls>=2               ; action=554 5.7.1 blocked using $$HIT_rbls RBLs [INFO: $$HIT_txt]

πŸ“ FILES πŸ“

Since postfwd1 v1.15 and postfwd2 v0.18 long item lists can be stored in separate files:

id=R001 ;  ccert_fingerprint==file:/etc/postfwd/wl_ccerts ;  action=DUNNO

postfwd will read a list of items (one item per line) from /etc/postfwd/wl_ccerts. comments are allowed:

# client1
11:22:33:44:55:66:77:88:99
# client2
22:33:44:55:66:77:88:99:00
# client3
33:44:55:66:77:88:99:00:11

To use existing tables in key=value format, you can use:

id=R001 ;  ccert_fingerprint==table:/etc/postfwd/wl_ccerts ;  action=DUNNO

This will ignore the right-hand value. Items can be mixed:

id=R002 ;  action=REJECT
        client_name==unknown
        client_name==file:/etc/postfwd/blacklisted

and for non pcre (comma separated) items:

id=R003 ;  action=REJECT
        client_address==10.1.1.1, file:/etc/postfwd/blacklisted

id=R004 ;  action=REJECT
        rbl=myrbl.home.local, zen.spamhaus.org, file:/etc/postfwd/rbls_changing

You can check your configuration with the --show_config option at the command line:

# postfwd --showconfig --rule='action=DUNNO; client_address=10.1.0.0/16, file:/etc/postfwd/wl_clients, 192.168.2.1'

should give something like:

Rule   0: id->"R-0"; action->"DUNNO"; client_address->"=;10.1.0.0/16, =;194.123.86.10, =;186.4.6.12, =;192.168.2.1"

If a file can not be read, it will be ignored:

# postfwd --showconfig --rule='action=DUNNO; client_address=10.1.0.0/16, file:/etc/postfwd/wl_clients, 192.168.2.1'
[LOG warning]: error: file /etc/postfwd/wl_clients not found - file will be ignored ?
Rule   0: id->"R-0"; action->"DUNNO"; client_address->"=;10.1.0.0/16, =;192.168.2.1"

File items are evaluated at configuration stage. Therefore postfwd needs to be reloaded if a file has changed.

If you want to specify a file, that will be reloaded for each request, you can use lfile: and ltable::

id=R001; client_address=lfile:/etc/postfwd/client_whitelist; action=dunno

This will check the modification time of /etc/postfwd/client_whitelist every time the rule is evaluated and reload it as necessary. Of course this might increase the system load, so please use it with care.

The --showconfig option illustrates the difference:

okay bestie, so you know how there are two flavours of that file lookup thing? Yeah. Watch what they actually print when you run them, because it's genuinely different and you need to know which one you're getting πŸ‘€

## evaluated at configuration stage
# postfwd2 --nodaemon -L --rule='client_address=table:/etc/postfwd/clients; action=dunno' -C
Rule   0: id->"R-0"; action->"dunno"; client_address->"=;1.1.1.1, =;1.1.1.2, =;1.1.1.3"

## evaluated for any rulehit
# postfwd2 --nodaemon -L --rule='client_address=ltable:/etc/postfwd/clients; action=dunno' -C
Rule   0: id->"R-0"; action->"dunno"; client_address->"=;ltable:/etc/postfwd/clients"

see the difference?? one of them slurped the whole file in at config time, the other one is just holding the pointer and reads it live. iykyk

And plot twist: files can point at other files. This is valid, no cap:

-- FILE /etc/postfwd/rules.cf --
id=R001; client_address=file:/etc/postfwd/clients_master.cf; action=DUNNO

-- FILE /etc/postfwd/clients_master.cf --
192.168.1.0/24
file:/etc/postfwd/clients_east.cf
file:/etc/postfwd/clients_west.cf

-- FILE /etc/postfwd/clients_east.cf --
192.168.2.0/24

-- FILE /etc/postfwd/clients_west.cf --
192.168.3.0/24
⚠️ heads up bestie β€” there is currently no loop detection (/a/file calls /a/file and it will just vibe into the void). Also this whole feature is only available with postfwd1 v1.15 and postfwd2 v0.18 and higher. πŸ’€

✨ ACTIONS ✨

πŸ’– General

So actions get executed when all rule items have matched a request (or at least one of any item list, bestie, don't @ me). And the cute part: you can reference request attributes by slapping $$ in front of them, like this:

id=R-003; client_name = !!$$helo_name; action=WARN helo '$$helo_name' does not match DNS '$$client_name'
# or
id=R-003; client_name = !!$$helo_name; action=WARN helo '$$(helo_name)' does not match DNS '$$(client_name)'

πŸ’Œ postfix actions

These get replied to postfix as the result of policy delegation requests. Any action postfix understands is allowed β€” go read man 5 access or <http://www.postfix.org/access.5.html> for the full description, bestie. And if you don't specify an action at all? The postfix WARN action just logs the event and that's what your rule gets. simple as.

postfwd will return dunno if it hits the end of the ruleset and nothing matched. You can change that by dropping a last rule with only an action statement in it:

...
action=dunno ; sender=@domain.local     # sender is ok
action=reject                           # default deny

the default-deny jump-scare, iconic honestly πŸ‘‘

πŸ”₯ postfwd actions

These ones control the behaviour of the program itself. Currently you can specify the following:

  • jump (<id>) β€” jumps to the rule with id <id>, use this to skip certain rules. You can jump backwards β€” but remember there's no loop detection at the moment! Jumps to non-existing ids will be skipped. πŸ¦‹
  • score (<score>) β€” the request's score gets modified by the specified <score>, which must be a floating point value. The modificator can be either:
    • +n.nn β€” adds n.nn to current score
    • -n.nn β€” sustracts n.nn from the current score
    • *n.nn β€” multiplies the current score by n.nn
    • /n.nn β€” divides the current score through n.nn
    • =n.nn β€” sets the current score to n.nn

If the score exceeds the maximum set by the --scores option (see COMMAND LINE) or the score item (see ITEMS section), the action defined for this case will be returned (default: 5.0=>"REJECT postfwd score exceeded").

  • set (<item>=<value>,<item>=<value>,...) β€” this command lets you insert or override request attributes, which then may be compared to your further ruleset. Use this to speed up repeated comparisons to large item lists. Please see the EXAMPLES section for more info. You may separate multiple key=value pairs by , characters. ✨
  • rate (<item>/<max>/<time>/<action>) β€” this command creates a counter for the given <item>, which will be increased any time a request containing it arrives. If it exceeds <max> within <time> seconds it will return <action> to postfix. Rate counters are very fast as they are executed before the ruleset is parsed. 🏎️
⚠️ Please note that <action> was limited to postfix actions (no postfwd actions) for postfwd versions <1.33!
# no more than 3 requests per 5 minutes
# from the same "unknown" client
id=RATE01 ;  client_name==unknown
   action=rate(client_address/3/300/450 4.7.1 sorry, max 3 requests per 5 minutes)

And listen bestie, the ORDER matters, this is the part people mess up 😭 Please note also that the order of rate limits in your ruleset is important, which means that this:

# works as expected
id=R001; action=rcpt(sender/500/3600/REJECT limit of 500 recipients per hour for sender $$sender exceeded)
id=R002; action=rcpt(sender/200/3600/WARN state YELLOW for sender $$sender)

leads to different results than this:

# rule R002 never gets executed
id=R001; action=rcpt(sender/200/3600/WARN state YELLOW for sender $$sender)
id=R002; action=rcpt(sender/500/3600/REJECT limit of 500 recipients per hour for sender $$sender exceeded)
  • size (<item>/<max>/<time>/<action>) β€” works similar to the rate() command, except the rate counter is increased by the request's size attribute. To do this reliably you should call postfwd from smtpd_end_of_data_restrictions. If you want to be sure, you could check it within the ruleset: πŸ“
# size limit 1.5mb per hour per client
id=SIZE01 ;  protocol_state==END-OF-MESSAGE ;  client_address!=10.1.1.1
   action=size(client_address/1572864/3600/450 4.7.1 sorry, max 1.5mb per hour)
  • rcpt (<item>/<max>/<time>/<action>) β€” again, works similar to the rate() command, except the rate counter is increased by the request's recipient_count attribute. To do this reliably you should call postfwd from smtpd_data_restrictions or smtpd_end_of_data_restrictions. If you want to be sure, you could check it within the ruleset: πŸ’…
# recipient count limit 3 per hour per client
id=RCPT01 ;  protocol_state==END-OF-MESSAGE ;  client_address!=10.1.1.1
   action=rcpt(client_address/3/3600/450 4.7.1 sorry, max 3 recipients per hour)
  • rate5321,size5321,rcpt5321 (<item>/<max>/<time>/<action>) β€” same as the corresponding non-5321 functions, with the difference that the localpart of sender oder recipient addresses are evaluated case-sensitive according to rfc5321. That means that requests from bob@example.local and BoB@example.local will be treated differently. yes, capitalisation girlies, this one's for you πŸŽ€
  • ask (<addr>:<port>[:<ignore>]) β€” allows one to delegate the policy decision to another policy service (e.g. postgrey). The first and the second argument (address and port) are mandatory. A third optional argument may be specified to tell postfwd to ignore certain answers and go on parsing the ruleset:
# example1: query postgrey and return it's answer to postfix
id=GREY; client_address==10.1.1.1; action=ask(127.0.0.1:10031)
# example2: query postgrey but ignore the answer, if it matches 'DUNNO'
# and continue parsing postfwd's ruleset
id=GREY; client_address==10.1.1.1; action=ask(127.0.0.1:10031:^dunno$)
  • mail(server/helo/from/to/subject/body) β€” This command is deprecated. You should try to use the sendmail() action instead. Very basic mail command, that sends a message with the given arguments. LIMITATIONS: This basically performs a telnet. No authentication or TLS are available. Additionally it does not track notification state and will notify you any time the corresponding rule hits. πŸ™ˆ
  • sendmail(sendmail-path::from::to::subject::body) β€” Mail command, that uses an existing sendmail binary and sends a message with the given arguments. LIMITATIONS: The command does not track notification state and will notify you any time the corresponding rule hits (which could mean 100 mails for a mail with 100 recipients at RCPT stage). πŸ’€
  • wait (<delay>) β€” pauses the program execution for <delay> seconds. Use this for delaying or throtteling connections. 🐒
  • note (<string>) β€” just logs the given string and continues parsing the ruleset. If the string is empty, nothing will be logged (noop).
  • quit (<code>) β€” terminates the program with the given exit-code. postfix doesn't like that too much, so use it with care. fr fr, be careful ⚠️

You can reference to request attributes, like

id=R-HELO ;  helo_name=^[^\.]+$ ;  action=REJECT invalid helo '$$helo_name'

🌸 MACROS/ACLS 🌸

Multiple use of long items or combinations of them may be abbreviated by macros. Those must be prefixed by && (two & characters). First the macros have to be defined as follows:

&&RBLS { rbl=zen.spamhaus.org,list.dsbl.org,bl.spamcop.net,dnsbl.sorbs.net,ix.dnsbl.manitu.net; };

Then these may be used in your rules, like:

&&RBLS ;  client_name=^unknown$                         ; action=REJECT
&&RBLS ;  client_name=(\d+[\.-_]){4}                    ; action=REJECT
&&RBLS ;  client_name=[\.-_](adsl|dynamic|ppp|)[\.-_]   ; action=REJECT

Macros can contain actions, too:

# definition
&&GONOW { action=REJECT your request caused our spam detection policy to reject this message. More info at http://www.domain.local; };
# rules
&&GONOW ;  &&RBLS ;  client_name=^unknown$
&&GONOW ;  &&RBLS ;  client_name=(\d+[\.-_]){4}
&&GONOW ;  &&RBLS ;  client_name=[\.-_](adsl|dynamic|ppp|)[\.-_]

And macros can contain macros, too β€” macro-ception, we love to see it 🧚:

# definition
&&RBLS{
        rbl=zen.spamhaus.org
        rbl=list.dsbl.org
        rbl=bl.spamcop.net
        rbl=dnsbl.sorbs.net
        rbl=ix.dnsbl.manitu.net
};
&&DYNAMIC{
        client_name=^unknown$
        client_name=(\d+[\.-_]){4}
        client_name=[\.-_](adsl|dynamic|ppp|)[\.-_]
};
&&GOAWAY { &&RBLS; &&DYNAMIC; };
# rules
&&GOAWAY ; action=REJECT dynamic client and listed on RBL

Basically macros are simple text substitutions β€” see the "PARSER" section for more information. no magic, just find-and-replace energy ✨


πŸ¦‹ PLUGINS πŸ¦‹

Description

The plugin interface allow you to define your own checks and enhance postfwd's functionality. Feel free to share useful things! collab era 🫢

Warning

⚠️ okay bestie, real talk for a sec β€” note that the plugin interface is still at devel stage. Please test your plugins carefully, because errors may cause postfwd to break! It is also allowed to override attributes or built-in functions, but be sure that you know what you do because some of them are used internally. πŸ’€

Please keep security in mind, when you access sensible resources and never, ever run postfwd as privileged user! Also never trust your input (especially hostnames, and e-mail addresses).

Okay bestie, listen, that's not me being dramatic, that's literally the rule. πŸ”’ Sensible resources = keep your hands off unless you know what you're doing. Privileged user = nope, never, don't even think about it. And your input? Hostnames? E-mail addresses? All of it is sus until proven otherwise. Trust nothing. πŸ’…


✨ ITEMS ✨ (the plugin kind, not the vibes kind)

Item plugins are perl subroutines that integrate additional attributes to requests before they are evaluated against postfwd's ruleset β€” like any other item of the policy delegation protocol. Basically: you get to invent your own checks. Main character energy fr. πŸ‘‘

But heads up: plugin-items can not be used selective. These functions will be executed for every request postfwd receives, so keep performance in mind. No skipping, no cherry-picking. 🫠

SYNOPSIS: %result = postfwd_items_plugin{<name>}(%request)

Translation: your subroutine, called <name>, has access to a hash called %request, which contains all request attributes, like $request{client_name}, and must return a value in the following form:

save: $result{<item>} = <value>

...which creates the new item <item> containing <value>. That item then gets integrated in the policy delegation request and therefore may be used in postfwd's ruleset. Slay. ✨

# do NOT remove the next line
%postfwd_items_plugin = (

    # EXAMPLES - integrated in postfwd. no need to activate them here.

        # allows one to check postfwd version in ruleset
        "version" => sub {
            my(%request) = @_;
            my(%result) = (
                "version" => $NAME." ".$VERSION,
            );
            return %result;
        },

        # sender_domain and recipient_domain
        "address_parts" => sub {
            my(%request) = @_;
            my(%result) = ();
            $request{sender} =~ /@([^@]*)$/;
            $result{sender_domain} = ($1 || '');
            $request{recipient} =~ /@([^@]*)$/;
            $result{recipient_domain} = ($1 || '');
            return %result;
        },

# do NOT remove the next line
);

πŸ¦‹ COMPARE πŸ¦‹

Compare plugins let you define how your new items should be compared to the ruleset. These are optional. If you don't specify one, the default (== for exact match, =~ for PCRE, ...) will be used. Lowkey a choose-your-own-adventure. 🌈

SYNOPSIS:  <item> => sub { return &{$postfwd_compare{<type>}}(@_); },
# do NOT remove the next line
%postfwd_compare_plugin = (

    EXAMPLES - integrated in postfwd. no need to activate them here.

        # Simple example
        # SYNOPSIS:  <result> = <item> (return &{$postfwd_compare{<type>}}(@_))
        "client_address"  => sub { return &{$postfwd_compare{cidr}}(@_); },
        "size"            => sub { return &{$postfwd_compare{numeric}}(@_); },
        "recipient_count" => sub { return &{$postfwd_compare{numeric}}(@_); },

        # Complex example
        # SYNOPSIS:  <result> = <item>(<operator>, <ruleset value>, <request value>, <request>)
        "numeric" => sub {
            my($cmp,$val,$myitem,%request) = @_;
            my($myresult) = undef;  $myitem ||= "0"; $val ||= "0";
            if ($cmp eq '==') {
                $myresult = ($myitem == $val);
            } elsif ($cmp eq '=<') {
                $myresult = ($myitem <= $val);
            } elsif ($cmp eq '=>') {
                $myresult = ($myitem >= $val);
            } elsif ($cmp eq '<') {
                $myresult = ($myitem < $val);
            } elsif ($cmp eq '>') {
                $myresult = ($myitem > $val);
            } elsif ($cmp eq '!=') {
                $myresult = not($myitem == $val);
            } elsif ($cmp eq '!<') {
                $myresult = not($myitem <= $val);
            } elsif ($cmp eq '!>') {
                $myresult = not($myitem >= $val);
            } else {
                $myresult = ($myitem >= $val);
            };
            return $myresult;
        },

# do NOT remove the next line
);

πŸ’… ACTIONS πŸ’…

Action plugins let you define new postfwd actions. By setting the $stop-flag you can decide to continue or to stop parsing the ruleset. You hold the power, bestie. πŸ‘‘

SYNOPSIS:  (<stop rule parsing>, <next rule index>, <return action>, <logprefix>, <request>) =
        <action> (<current rule index>, <current time>, <command name>, <argument>, <logprefix>, <request>)
# do NOT remove the next line
%postfwd_actions_plugin = (

    # EXAMPLES - integrated in postfwd. no need to activate them here.

        # note(<logstring>) command
        "note"  => sub {
            my($index,$now,$mycmd,$myarg,$myline,%request) = @_;
            my($myaction) = 'dunno'; my($stop) = 0;
            log_info "[RULES] ".$myline." - note: ".$myarg if $myarg;
            return ($stop,$index,$myaction,$myline,%request);
        },

        # skips next <myarg> rules
        "skip" => sub {
            my($index,$now,$mycmd,$myarg,$myline,%request) = @_;
            my($myaction) = 'dunno'; my($stop) = 0;
            $index += $myarg if ( $myarg and not(($index + $myarg) > $#Rules) );
            return ($stop,$index,$myaction,$myline,%request);
        },

        # dumps current request contents to syslog
        "dumprequest" => sub {
            my($index,$now,$mycmd,$myarg,$myline,%request) = @_;
            my($myaction) = 'dunno'; my($stop) = 0;
            map { log_info "[DUMP] rule=$index, Attribute: $_=$request{$_}" } (keys %request);
            return ($stop,$index,$myaction,$myline,%request);
        },

# do NOT remove the next line
);

πŸŽ€ COMMAND LINE πŸŽ€

🌸 Ruleset 🌸

The following arguments are used to specify the source of the postfwd ruleset. This means that at least one of the following is required for postfwd to work. Like, at least one. Pick your fighter. ✨

  • -f, --file <file> β€” Reads rules from <file>. Please see the CONFIGURATION section below for more information. πŸ“–
  • -r, --rule <rule> β€” Adds <rule> to ruleset. Remember that you might have to quote strings that contain whitespaces or shell characters. Yes, the shell is that girl, she'll eat your spaces for breakfast. 🫠

πŸ“ Scoring πŸ“

  • -s, --scores <val>=<action> β€” Returns <action> to postfix, when the request's score exceeds <val>. πŸ“ˆ

Multiple usage is allowed. Just chain your arguments, like:

postfwd -r "<item>=<value>;action=<result>" -f <file> -f <file> ...
  or
postfwd --scores 4.5="WARN high score" --scores 5.0="REJECT postfwd score too high" ...

In case of multiple scores, the highest match will count. The order of the arguments will be reflected in the postfwd ruleset. No cap. πŸ”₯

🧚 Control 🧚

  • -d, --daemon β€” postfwd will run as daemon and listen on the network for incoming queries (default 127.0.0.1:10040). 😴✨
  • -k, --kill β€” Stops a running postfwd daemon. πŸ’€
  • --reload β€” Reloads configuration. πŸ”„
  • --dumpstats β€” Displays program usage statistics. πŸ“Š
  • --dumpcache β€” Displays cache contents. πŸ—‚οΈ
  • --delcache <item> β€” Removes an item from the request cache. Use --dumpcache to identify objects. E.g.:
# postfwd --dumpcache
...
%rate_cache -> %sender=gmato@jqvo.org -> %RATE002+2_600 -> @count    -> '1'
%rate_cache -> %sender=gmato@jqvo.org -> %RATE002+2_600 -> @maxcount -> '2'
...
# postfwd --delrate="sender=gmato@jqvo.org"
rate cache item 'sender=gmato@jqvo.org' removed
  • --delrate <item> β€” Removes an item from the rate cache. Use --dumpcache to identify objects. 🧹

🌈 Networking 🌈

postfwd can be run as daemon so that it listens on the network for incoming requests. The following arguments will control it's behaviour in this case. It's giving... network era. 🌐

  • -i, --interface <dev> β€” Bind postfwd to the specified interface (default 127.0.0.1).
  • -p, --port <port> β€” postfwd listens on the specified port (default tcp/10040).
  • --proto <type> β€” The protocol type for postfwd's socket. Currently you may use 'tcp' or 'unix' here. To use postfwd with a unix domain socket, run it as follows:
postfwd --proto=unix --port=/somewhere/postfwd.socket
  • -u, --user <name> β€” Changes real and effective user to <name>.
  • -g, --group <name> β€” Changes real and effective group to <name>.
  • --umask <mask> β€” Changes the umask for filepermissions (unix domain sockets, pidfiles). Attention: This is umask, not chmod β€” you have to specify the bits that should NOT apply. E.g.: umask 077 equals to chmod 700. ⚠️ Read that twice, bestie, it's backwards on purpose.
  • -R, --chroot <path> β€” Chroot the process to the specified path. Test this before using β€” you might need some libs there. Like, test it test it. 🫣
  • --pidfile <path> β€” The process id will be saved in the specified file.
  • --facility <f> β€” sets the syslog facility, default is 'mail'.
  • --socktype <s> β€” sets the Sys::Syslog socktype to 'native', 'inet' or 'unix'. Default is to auto-detect this depening on module version and os. (Yes, "depening". We keep it exactly as it is. 😭)
  • -l, --logname <label> β€” Labels the syslog messages. Useful when running multiple instances of postfwd. 🏷️
  • --loglen <int> β€” Truncates any syslog message after <int> characters. βœ‚οΈ

πŸ’œ Plugins πŸ’œ

  • --plugins <file> β€” Loads postfwd plugins from file. Please see http://postfwd.org/postfwd.plugins or the plugins.postfwd.sample that is available from the tarball for more info. πŸ”Œβœ¨

Optional arguments


okay bestie, these are the parameters that literally change how postfwd does its thing. any of them can be combined, mix-and-match, it's giving build-your-own-daemon ✨

  • -v, --verbose β€” verbose logging spills a lot of genuinely useful info, but your logfiles will grow noticeably, so use it with caution, okay? set the option twice (-vv) to get even more (it logs all request attributes). πŸ’…
  • -c, --cache <int> β€” (default=600) timeout for the request cache. results for identical requests get cached until the config is reloaded or this time (in seconds) expires. a setting of 0 disables this feature entirely. πŸŽ€
  • --cache-no-size β€” ignores the size attribute for cache comparisons, which leads to better cache-hit rates. you should set this one if you don't use the size item in your ruleset. ✨
  • --cache-no-sender β€” ignores the sender address for cache comparisons, which leads to better cache-hit rates. set it if you don't use the sender item in your ruleset. πŸ¦‹
  • --cache-rdomain-only β€” strips the localpart off the recipient's address before filling the cache. this may considerably increase cache-hit rates. 🌸
  • --cache-rbl-timeout <timeout> β€” (default=3600) this default value gets used as the timeout in seconds for rbl cache items, if it's not specified in the ruleset. πŸ’œ
  • --cache-rbl-default <pattern> β€” (default=^127\.0\.0\.\d+$) matches pattern to rbl/rhsbl answers (regexp) if it's not specified in the ruleset. πŸ”₯
  • --cacheid <item>, <item>, ... β€” this csv-separated list of request attributes is what gets used to construct the request cache identifier. only use this if you know exactly what you're doing. if, for example, you use postfwd only for RBL/RHSBL control, you may set it to:
postfwd --cache=3600 --cacheid=client_name,client_address

this increases the efficiency of caching and improves postfwd's performance.

⚠️ Warning: you should list all items here which are used in your ruleset! 😭
  • --cleanup-requests <interval> β€” (default=600) the request cache gets searched for timed-out items after this interval in seconds. it's a minimum value, and the cleanup process only takes place when a new request arrives. 🧚
  • --cleanup-rbls <interval> β€” (default=600) the rbl cache gets searched for timed-out items after this interval in seconds. also a minimum value, also only triggered when a new request arrives. 🧚
  • --cleanup-rates <interval> β€” (default=600) the rate cache gets searched for timed-out items after this interval in seconds. minimum value, and again, only when a new request arrives. 🧚
  • -S, --summary <int> β€” (default=600) shows some usage statistics (program uptime, request counter, matching rules) every int seconds. this option is included by the -v switch. it uses the alarm signal, so you can force postfwd to dump the stats with kill -ALRM <pid> (where <pid> is the process id of postfwd). πŸ‘‘

Example:

Aug 19 12:39:45 mail1 postfwd[666]: [STATS] Counters: 213000 seconds uptime, 39 rules
Aug 19 12:39:45 mail1 postfwd[666]: [STATS] Requests: 71643 overall, 49 last interval, 62.88% cache hits
Aug 19 12:39:45 mail1 postfwd[666]: [STATS] Averages: 20.18 overall, 4.90 last interval, 557.30 top
Aug 19 12:39:45 mail1 postfwd[666]: [STATS] Contents: 44 cached requests, 239 cached dnsbl results
Aug 19 12:39:45 mail1 postfwd[666]: [STATS] Rule ID: R-001   matched: 2704 times
Aug 19 12:39:45 mail1 postfwd[666]: [STATS] Rule ID: R-002   matched: 9351 times
Aug 19 12:39:45 mail1 postfwd[666]: [STATS] Rule ID: R-003   matched: 3116 times
...
  • --no-rulestats β€” disables per-rule statistics. keeps your log clean if you don't use them. this option has no effect without --summary or --verbose set. πŸ’…
  • -L, --stdoutlog β€” redirects all syslog messages to stdout for debugging.
🚨 Never use this with postfix! like, fr fr, never. πŸ’€
  • -t, --test β€” in test mode postfwd always returns "dunno", but logs according to its ruleset. -v` will be set automatically with this option. πŸŽ€
  • -n, --nodns β€” disables all DNS based checks like RBL checks. rules containing such elements will be ignored. πŸ™ˆ
  • -n, --nodnslog β€” disables logging of dns events. (yes bestie, -n shows up twice with a different long name β€” that's just how it is, no cap.) ✨
  • --dns_timeout β€” (default: 14) sets the timeout for asynchronous dns queries in seconds. this value applies to all dns items in a rule. ⏳
  • --dns_timeout_max β€” (default: 10) sets the maximum timeout counter for dnsbl lookups. if the timeouts exceed this value, the corresponding dnsbl gets deactivated for a while (see --dns_timeout_interval). 😀
  • --dns_timeout_interval β€” (default=1200) the dnsbl timeout counter gets cleaned after this interval in seconds. use this in conjunction with the --dns_timeout_max parameter. 🧼
  • --dns_async_txt β€” performs dnsbl A and TXT lookups simultaneously (otherwise only for listings with at least one A record). this needs more network bandwidth due to increased queries, but it might increase throughput because the lookups can be parallelized. 🌈
  • --dns_max_ns_lookups β€” (default=0) maximum ns names to look up with the sender_ns_addrs item. use 0 for no maximum. πŸ”
  • --dns_max_mx_lookups β€” (default=0) maximum mx names to look up with the sender_mx_addrs item. use 0 for no maximum. πŸ”
  • -I, --instantcfg β€” the config files specified by -f get re-read for every single request postfwd receives. this enables on-the-fly configuration changes without restarting. though files will only be read if necessary (meaning their access times changed since last read), this might significantly increase system load. 😭
  • --config_timeout β€” (default=3) timeout in seconds to parse a single configuration line. if it's exceeded, the rule gets skipped. this is used to prevent problems due to large files or loops. πŸŒ€
  • --keep_rates β€” (default=0) with this option set, postfwd does not clear the rate limit counters on reload. please note that you have to restart (not reload) postfwd with this option if you change any rate limit rules. πŸ’…
  • --save_rates β€” (default=none) with this option, postfwd saves existing rate limit counters to disk and reloads them on program start. this allows persistent rate limits across program restarts or reboots. please note that postfwd needs read and write access to the specified file. πŸ’Ύ
  • --fast_limit_evaluation β€” (default=0) once a ratelimit was set by the ruleset, future requests get evaluated against it before consulting the ruleset. this mode was the default behaviour until v1.30. with this mode rate limits are faster, but eventually set up whitelisting-rules within the ruleset might not work as expected. 😬
LIMITATIONS: this option does not allow nested postfwd commands like action=rate(sender/3/60/wait(3)) this option does not work with the strict-rfc5321 rate() functions.

πŸ’– Informational arguments πŸ’–

these arguments are for command line usage only. never ever use them with postfix spawn! πŸ™…β€β™€οΈ

  • -C, --showconfig β€” displays the current ruleset. use -v for verbose output. πŸ“œ
  • -P, --perfmon β€” this option turns off any syslogging and output. it's included for performance testing. 🏎️
  • -V, --version β€” displays the program version. 🏷️
  • -h, --help β€” shows program usage. πŸ†˜
  • -m, --manual β€” displays the program manual. πŸ“–

πŸ”„ REFRESH πŸ”„

in daemon mode, postfwd reloads its ruleset after receiving a HUP signal. and please go look at the description of the -I switch if you want your configuration refreshed for every request postfwd receives. ✨


🌟 EXAMPLES 🌟

## whitelisting
# 1. networks 192.168.1.0/24, 192.168.2.4
# 2. client_names *.gmx.net and *.gmx.de
# 3. sender *@someshop.tld from 11.22.33.44
id=WL001; action=dunno ; client_address=192.168.1.0/24, 192.168.2.4
id=WL002; action=dunno ; client_name=\.gmx\.(net|de)$
id=WL003; action=dunno ; sender=@someshop\.tld$ ; client_address=11.22.33.44

## TLS control
# 1. *@authority.tld only with correct TLS fingerprint
# 2. *@secret.tld only with keysizes >=64
id=TL001; action=dunno                          ; sender=@authority\.tld$ ; ccert_fingerprint=AA:BB:CC..
id=TL002; action=REJECT wrong TLS fingerprint   ; sender=@authority\.tld$
id=TL003; action=REJECT tls keylength < 64      ; sender=@secret\.tld$ ; encryption_keysize=64

## Combined RBL checks
# This will reject mail if
# 1. listed on ix.dnsbl.manitu.net
# 2. listed on zen.spamhaus.org (sbl and xbl, dns cache timeout 1200s instead of 3600s)
# 3. listed on min 2 of bl.spamcop.net, list.dsbl.org, dnsbl.sorbs.net
# 4. listed on bl.spamcop.net and one of rhsbl.ahbl.org, rhsbl.sorbs.net
id=RBL01 ; action=REJECT listed on ix.dnsbl.manitu.net  ; rbl=ix.dnsbl.manitu.net
id=RBL02 ; action=REJECT listed on zen.spamhaus.org     ; rbl=zen.spamhaus.org/127.0.0.[2-8]/1200
id=RBL03 ; action=REJECT listed on too many RBLs        ; rblcount=2 ; rbl=bl.spamcop.net, list.dsbl.org, dnsbl.sorbs.net
id=RBL04 ; action=REJECT combined RBL+RHSBL check       ; rbl=bl.spamcop.net ; rhsbl=rhsbl.ahbl.org, rhsbl.sorbs.net

## Message size (requires message_size_limit to be set to 30000000)
# 1. 30MB for systems in *.customer1.tld
# 2. 20MB for SASL user joejob
# 3. 10MB default
id=SZ001; protocol_state==END-OF-MESSAGE; action=DUNNO; size<=30000000 ; client_name=\.customer1.tld$
id=SZ002; protocol_state==END-OF-MESSAGE; action=DUNNO; size<=20000000 ; sasl_username==joejob
id=SZ002; protocol_state==END-OF-MESSAGE; action=DUNNO; size<=10000000
id=SZ100; protocol_state==END-OF-MESSAGE; action=REJECT message too large

okay so that's the whole vibe of these bits β€” and there's still more coming bestie, don't go anywhere πŸ’–

okay bestie, more example configs, these ones are chef's kiss πŸ’‹πŸ‘‘

## Selective Greylisting
##
## Note that postfwd does not include greylisting. This setup requires a running postgrey service
## at port 10031 and the following postfix restriction class in your main.cf:
##
##      smtpd_restriction_classes = check_postgrey, ...
##      check_postgrey = check_policy_service inet:127.0.0.1:10031
#
# 1. if listed on zen.spamhaus.org with results 127.0.0.10 or .11, dns cache timeout 1200s
# 2. Client has no rDNS
# 3. Client comes from several dialin domains
id=GR001; action=check_postgrey ; rbl=dul.dnsbl.sorbs.net, zen.spamhaus.org/127.0.0.1[01]/1200
id=GR002; action=check_postgrey ; client_name=^unknown$
id=GR003; action=check_postgrey ; client_name=\.(t-ipconnect|alicedsl|ish)\.de$

quick heads up before you @ me: postfwd itself does not do greylisting, okay? This setup needs a postgrey service already running at port 10031, plus that postfix restriction class sitting in your main.cf. Slay. ✨

## Date Time
date=24.12.2007-26.12.2007          ;  action=450 4.7.1 office closed during christmas
time=04:00:00-05:00:00              ;  action=450 4.7.1 maintenance ongoing, try again later
time=-07:00:00 ;  sasl_username=jim ;  action=450 4.7.1 to early for you, jim
time=22:00:00- ;  sasl_username=jim ;  action=450 4.7.1 to late now, jim
months=-Apr                         ;  action=450 4.7.1 see you in may
days=!!Mon-Fri                      ;  action=check_postgrey

not the time=-07:00:00 and time=22:00:00- open-ended situations being used to personally drag jim 😭 iconic.

## Usage of jump
# The following allows a message size of 30MB for different
# users/clients while others will only have 10MB.
id=R001 ; action=jump(R100) ; sasl_username=^(Alice|Bob|Jane)$
id=R002 ; action=jump(R100) ; client_address=192.168.1.0/24
id=R003 ; action=jump(R100) ; ccert_fingerprint=AA:BB:CC:DD:...
id=R004 ; action=jump(R100) ; ccert_fingerprint=AF:BE:CD:DC:...
id=R005 ; action=jump(R100) ; ccert_fingerprint=DD:CC:BB:DD:...
id=R099 ; protocol_state==END-OF-MESSAGE; action=REJECT message too big (max. 10MB); size=10000000
id=R100 ; protocol_state==END-OF-MESSAGE; action=REJECT message too big (max. 30MB); size=30000000
## Usage of score
# The following rejects a mail, if the client
# - is listed on 1 RBL and 1 RHSBL
# - is listed in 1 RBL or 1 RHSBL and has no correct rDNS
# - other clients without correct rDNS will be greylist-checked
# - some whitelists are used to lower the score
id=S01 ; score=2.6              ; action=check_postgrey
id=S02 ; score=5.0              ; action=REJECT postfwd score too high
id=R00 ; action=score(-1.0)     ; rbl=exemptions.ahbl.org,list.dnswl.org,query.bondedsender.org,spf.trusted-forwarder.org
id=R01 ; action=score(2.5)      ; rbl=bl.spamcop.net, list.dsbl.org, dnsbl.sorbs.net
id=R02 ; action=score(2.5)      ; rhsbl=rhsbl.ahbl.org, rhsbl.sorbs.net
id=N01 ; action=score(-0.2)     ; client_name==$$helo_name
id=N02 ; action=score(2.7)      ; client_name=^unknown$
...
## Usage of rate and size
# The following temporary rejects requests from "unknown" clients, if they
# 1. exceeded 30 requests per hour or
# 2. tried to send more than 1.5mb within 10 minutes
id=RATE01 ;  client_name==unknown ;  protocol_state==RCPT
        action=rate(client_address/30/3600/450 4.7.1 sorry, max 30 requests per hour)
id=SIZE01 ;  client_name==unknown ;  protocol_state==END-OF-MESSAGE
        action=size(client_address/1572864/600/450 4.7.1 sorry, max 1.5mb per 10 minutes)
## Macros
# definition
&&RBLS { rbl=zen.spamhaus.org,list.dsbl.org,bl.spamcop.net,dnsbl.sorbs.net,ix.dnsbl.manitu.net; };
&&GONOW { action=REJECT your request caused our spam detection policy to reject this message. More info at http://www.domain.local; };
# rules
&&GONOW ;  &&RBLS ;  client_name=^unknown$
&&GONOW ;  &&RBLS ;  client_name=(\d+[\.-_]){4}
&&GONOW ;  &&RBLS ;  client_name=[\.-_](adsl|dynamic|ppp|)[\.-_]
## Groups
# definition
&&RBLS{
        rbl=zen.spamhaus.org
        rbl=list.dsbl.org
        rbl=bl.spamcop.net
        rbl=dnsbl.sorbs.net
        rbl=ix.dnsbl.manitu.net
};
&&RHSBLS{
        ...
};
&&DYNAMIC{
        client_name==unknown
        client_name~=(\d+[\.-_]){4}
        client_name~=[\.-_](adsl|dynamic|ppp|)[\.-_]
        ...
};
&&BAD_HELO{
        helo_name==my.name.tld
        helo_name~=^([^\.]+)$
        helo_name~=\.(local|lan)$
        ...
};
&&MAINTENANCE{
        date=15.01.2007
        date=15.04.2007
        date=15.07.2007
        date=15.10.2007
        time=03:00:00 - 04:00:00
};
# rules
id=COMBINED    ;  &&RBLS ;  &&DYNAMIC ;  action=REJECT dynamic client and listed on RBL
id=MAINTENANCE ;  &&MAINTENANCE       ;  action=DEFER maintenance time - please try again later

# now with the set() command, note that long item
# lists don't have to be compared twice
id=RBL01    ;  &&RBLS      ;  action=set(HIT_rbls=1)
id=HELO01   ;  &&BAD_HELO  ;  action=set(HIT_helo=1)
id=DYNA01   ;  &&DYNAMIC   ;  action=set(HIT_dyna=1)
id=REJECT01 ;  HIT_rbls==1 ;  HIT_helo==1  ; action=REJECT please see http://some.org/info?reject=01 for more info
id=REJECT02 ;  HIT_rbls==1 ;  HIT_dyna==1  ; action=REJECT please see http://some.org/info?reject=02 for more info
id=REJECT03 ;  HIT_helo==1 ;  HIT_dyna==1  ; action=REJECT please see http://some.org/info?reject=03 for more info

## combined with enhanced rbl features
#
id=RBL01 ; rhsblcount=all ; rblcount=all ; &&RBLS ; &&RHSBLS
     action=set(HIT_dnsbls=$$rhsblcount,HIT_dnsbls+=$$rblcount,HIT_dnstxt=$$dnsbltext)
id=RBL02 ; HIT_dnsbls>=2  ; action=554 5.7.1 blocked using $$HIT_dnsbls DNSBLs [INFO: $$HIT_dnstxt]

🧚 PARSER 🧚

πŸ’… Configuration πŸ’…

okay so you can hand postfwd your ruleset either straight at the commandline with the -r option, or read it from files with -f. The order of your arguments will be kept, so don't come for me about ordering. πŸ™…β€β™€οΈ

Before you go applying a shiny new config, check the parser with the -C | --showconfig switch at the command line. fr fr, do it. 🫢

This call right here:

postfwd --showconfig \
        -r "id=TEST; recipient_count=100; action=WARN mail with 100+ recipients" \
        -f /etc/postfwd.cf \
        -r "id=DEFAULT; action=dunno";

will produce the following output:

Rule   0: id->"TEST" action->"WARN mail with 100+ recipients"; recipient_count->"100"
...
... <content of /etc/postfwd.cf> ...
...
Rule <n>: id->"DEFAULT" action->"dunno"

Multiple items of the same type get added to lists (peep the ITEMS section for more info, bestie):

postfwd --showconfig \
        -r "client_address=192.168.1.0/24; client_address=172.16.26.32; action=dunno"

will result in:

Rule   0: id->"R-0"; action->"dunno"; client_address->"192.168.1.0/24, 172.16.26.32"

Macros are evaluated at configuration stage, which means that:

postfwd --showconfig \
        -r "&&RBLS { rbl=bl.spamcop.net; client_name=^unknown$; };" \
        -r "id=RBL001; &&RBLS; action=REJECT listed on spamcop and bad rdns";

will result in:

Rule   0: id->"RBL001"; action->"REJECT listed on spamcop and bad rdns"; rbl->"bl.spamcop.net"; client_name->"^unknown$"

πŸ” Request processing πŸ”

When a policy delegation request rolls up, it gets compared against postfwd's ruleset. To inspect the processing in detail you should crank up the verbosity using the -v or -vv switch. And -L redirects log messages to stdout. πŸ“

Keeping the order of the ruleset in general, items will be compared in random order, which basically means that

id=R001; action=dunno; client_address=192.168.1.1; sender=bob@alice.local

equals

id=R001; sender=bob@alice.local; client_address=192.168.1.1; action=dunno

Lists will be evaluated in the specified order, which lets you place faster expressions at first:

postfwd -vv -L -r "id=RBL001; rbl=localrbl.local zen.spamhaus.org; action=REJECT" /some/where/request.sample

produces the following

[LOGS info]: compare rbl: "remotehost.remote.net[68.10.1.7]"  ->  "localrbl.local"
[LOGS info]: count1 rbl:  "2"  ->  "0"
[LOGS info]: query rbl:   localrbl.local 7.1.10.68 (7.1.10.68.localrbl.local)
[LOGS info]: count2 rbl:  "2"  ->  "0"
[LOGS info]: match rbl:   FALSE
[LOGS info]: compare rbl: "remotehost.remote.net[68.10.1.7]"  ->  "zen.spamhaus.org"
[LOGS info]: count1 rbl:  "2"  ->  "0"
[LOGS info]: query rbl:   zen.spamhaus.org 7.1.10.68 (7.1.10.68.zen.spamhaus.org)
[LOGS info]: count2 rbl:  "2"  ->  "0"
[LOGS info]: match rbl:   FALSE
[LOGS info]: Action: dunno

The negation operator !!(<value>) has the highest priority and therefore will be evaluated first. Then variable substitutions are performed:

postfwd -vv -L -r "id=TEST; action=REJECT; client_name=!!($$heloname)" /some/where/request.sample

will give

[LOGS info]: compare client_name:     "unknown"  ->  "!!($$helo_name)"
[LOGS info]: negate client_name:      "unknown"  ->  "$$helo_name"
[LOGS info]: substitute client_name:  "unknown"  ->  "english-breakfast.cloud8.net"
[LOGS info]: match client_name:  TRUE
[LOGS info]: Action: REJECT

βš–οΈ Ruleset evaluation βš–οΈ

A rule hits when all items (or at least one element of a list for each item) have matched. And the second one item (or all elements of a list) fails to compare against the request attribute, the parser will jump to the next rule in the postfwd ruleset. bye πŸ‘‹

If a rule matches, there are two options:

  • Rule returns postfix action (dunno, reject, ...) β€” the parser stops rule processing and returns the action to postfix. Other rules will not be evaluated.
  • Rule returns postfwd action (jump(), note(), ...) β€” the parser evaluates the given action and continues with the next rule (except for the jump() or quit() actions β€” please see the ACTIONS section for more information). Nothing will be sent to postfix.

If no rule has matched and the end of the ruleset is reached, postfwd will return dunno without logging anything unless in verbose mode. You may simply place a last catch-all rule to change that behaviour:

... <your rules> ...
id=DEFAULT ;  action=dunno

and that's the vibe check passed πŸ’–

…and it's gonna log every single request that slides through your ruleset without tripping any earlier rule first. like, it made it all the way to the end, no rule claimed it, so postfwd is like "okay bestie, noting this for the record" πŸ’…


πŸ› οΈ INTEGRATION πŸ› οΈ

🌐 Integration via daemon mode 🌐

okay so the normal girl way to run postfwd is as a daemon, chilling on a tcp port you pick. and because postfwd runs in a single instance (that's multiplexing mode, iykyk), it gets the absolute most out of its internal caching that way. like, that's the whole point. start it like this:

postfwd -d -f /etc/postfwd.cf -i 127.0.0.1 -p 10040 -u nobody -g nobody -S

and for caching that actually slays, go check if you can use --cache-rdomain-only, --cache-no-sender and --cache-no-size. those are the cheat codes fr fr.

now go peek at your syslogs (default facility is "mail") and look for a line like:

Aug  9 23:00:24 mail postfwd[5158]: postfwd n.nn ready for input

and run netstat -an|grep 10040 to check for something like

tcp  0  0  127.0.0.1:10040  0.0.0.0:*  LISTEN

if that's all working, open your postfix main.cf and drop this in:

127.0.0.1:10040_time_limit      = 3600                                          <--- integration
smtpd_recipient_restrictions    = permit_mynetworks                             <--- recommended
                                  reject_unauth_destination                     <--- recommended
                                  check_policy_service inet:127.0.0.1:10040     <--- integration

reload your config with postfix reload and watch your logs. if it works you should see lines like this in your mail log:

Aug  9 23:01:24 mail postfwd[5158]: rule=22, id=ML_POSTFIX, client=english-breakfast.cloud9.net[168.100.1.7], sender=owner-postfix-users@postfix.tld, recipient=someone@domain.local, helo=english-breakfast.cloud9.net, proto=ESMTP, state=RCPT, action=dunno

now β€” if you wanna check for size or rcpt_count items, you gotta integrate postfwd in smtp_data_restrictions or smtpd_end_of_data_restrictions instead. no skipping that step bestie, those items literally don't exist yet at RCPT time.

and ofc you can also define a restriction class and use it in your access tables. first make a file /etc/postfix/policy containing:

domain1.local           postfwdcheck
domain2.local           postfwdcheck
...

then postmap that file (postmap hash:/etc/postfix/policy), open your main.cf and enter

# Restriction Classes
smtpd_restriction_classes       = postfwdcheck, <some more>...                          <--- integration
postfwdcheck                    = check_policy_service inet:127.0.0.1:10040             <--- integration

127.0.0.1:10040_time_limit      = 3600                                                  <--- integration
smtpd_recipient_restrictions    = permit_mynetworks,                                    <--- recommended
                                  reject_unauth_destination,                            <--- recommended
                                  ...                                                   <--- optional
                                  check_recipient_access hash:/etc/postfix/policy,      <--- integration
                                  ...                                                   <--- optional

reload postfix and watch your logs. that's it, that's the vibe ✨

🧚 Integration via xinetd 🧚

there might be a few reasons you'd wanna run postfwd through a tcp wrapper package like xinetd (see <http://www.xinetd.org/>). not gonna get into that here β€” the author's words, not mine. if you're planning to do it anyway, just add this line to your /etc/services file:

# postfwd port
postfwd     10040/tcp

then create a file /etc/xinetd.d/postfwd:

{
        interface       = 127.0.0.1
        socket_type     = stream
        protocol        = tcp
        wait            = no
        user            = nobody
        server          = /usr/local/bin/postfwd
        server_args     = -f /etc/postfwd.cf
        disable         = no
}

and restart the xinetd daemon (usually a SIGHUP should be fine 🫢). if you hit problems, check your system's log for xinetd errors like "socket already in use".

the integration with postfix is basically the same as the Integration via daemon mode section up above. reload postfix and watch your logs to see if everything works.


πŸ§ͺ TESTING πŸ§ͺ

first you gotta make a ruleset (peep the Configuration section). check it with

postfwd -f /etc/postfwd.cf -C

there's an example policy request shipped with postfwd called 'request.sample'. just edit it to fit your needs and use

postfwd -f /etc/postfwd.cf <request.sample

you should get an answer like

action=<whateveryouconfigured>

for network tests, netcat is the move:

nc 127.0.0.1 10040 <request.sample

to send a request to postfwd. if you get nothing back, make sure postfwd is actually running and listening on the network settings you specified. like, that's usually it 😭


πŸš€ PERFORMANCE πŸš€

some of these proposals might not match your environment. please check your requirements and test new options carefully! no cap, don't just paste and pray.

- use caching options
- use the correct match operator ==, <=, >=
- use ^ and/or $ in regular expressions
- use item lists (faster than single rules)
- use set() action on repeated item lists
- use jumps and rate limits
- use a pre-lookup rule for rbl/rhsbls with empty note() action

πŸ‘€ SEE ALSO πŸ‘€

go read <http://www.postfix.org/SMTPD_POLICY_README.html> for a description of how Postfix policy servers work. it's giving essential reading, fr.


πŸ“œ LICENSE πŸ“œ

postfwd is free software and released under BSD license, which basically means you can do whatever you want as long as you keep the copyright notice:

Copyright (c) 2007, Jan Peter Kessler All rights reserved.

Redistribution 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 authors nor the names of his contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY ME ``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 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.

πŸ‘‘ AUTHOR πŸ‘‘

Jan Peter Kessler <info (AT) postfwd (DOT) org>. let me know if you have any suggestions. he's literally the main character of this whole thing πŸ’–


and that's a wrap bestie!! πŸŽ€ this page came to you courtesy of perl v5.14.2, dated 2013-04-18, and it's the POSTFWD...L-IN-ONE(1) man page. go forth and policy-serve responsibly βœ¨πŸ¦‹πŸ’…

πŸ“¦ where this page comes from