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

πŸ‘‘ postfwd2 β€” the manual, but make it a group chat πŸ‘‘

okay bestie, this is the manual page for postfwd2, straight out of the User Contributed Perl Documentation section. it's long, it's gorgeous, and we're doing it together. grab a strawberry πŸ“ and let's go.


✨ NAME ✨

postfwd2 β€” the postfix firewall daemon. that's it. that's the name. iconic. πŸ’…


πŸ¦‹ SYNOPSIS πŸ¦‹

postfwd2 [OPTIONS] [SOURCE1, SOURCE2, ...]

        Ruleset: (at least one, multiple use is allowed):
        -f, --file <file>               reads rules from <file>
        -r, --rule <rule>               adds <rule> to config
        -s, --scores <v>=<r>            returns <r> when score exceeds <v>

        Server:
        -i, --interface <dev>           listen on interface <dev>
        -p, --port <port>               listen on port <port>
            --proto <proto>             socket type (tcp or unix)
            --server_socket <sock>      e.g. tcp:127.0.0.1:10045
        -u, --user <name>               set uid to user <name>
        -g, --group <name>              set gid to group <name>
            --umask <mask>              umask for master filepermissions
            --server_umask <mask>       umask for server filepermissions
            --pidfile <path>            create pidfile under <path>
            --min_servers <i>           spawn at least <i> children
            --max_servers <i>           do not spawn more than <i> children
            --min_spare_servers <i>     minimum idle children
            --max_spare_servers <i>     maximum idle children

        Cache:
        -c, --cache <int>               sets the request-cache timeout to <int> seconds
            --cleanup-requests <int>    cleanup interval in seconds for request cache
            --cache_interface <dev>     listen on interface <dev>
            --cache_port <port>         listen on port <port>
            --cache_proto <proto>       socket type (tcp or unix)
            --cache_socket <sock>       e.g. tcp:127.0.0.1:10043
            --cache_umask <mask>        umask for cache filepermissions
            --cacheid <list>            list of request items for cache-id
            --cache-rdomain-only        skip recipient localpart for cache-id
            --cache-no-sender           skip sender address for cache-id
            --cache-no-size             skip size for cache-id
            --no_parent_request_cache   disable parent request cache
            --no_parent_rate_cache      disable parent rate cache
            --no_parent_dns_cache       disable parent dns cache (default)
            --no_parent_cache           disable all parent caches

        Rates:
            --cleanup-rates <int>       cleanup interval in seconds for rate cache

        Control:
        -k, --kill, --stop              terminate postfwd2
            --reload, --hup             reload postfwd2
            --watchdog <w>              watchdog timer in seconds
            --respawn <r>               respawn delay in seconds
            --failures <f>              max respawn failure counter
            --daemons <list>            list of daemons to start
            --dumpcache                 show cache contents
            --dumpstats                 show statistics
        -R, --chroot <path>             chroot to <path> before start
            --delcache <item>           removes an item from the request cache
            --delrate <item>            removes an item from the rate cache

        DNS:
        -n, --nodns                     skip any dns based test
            --dns_timeout <i>           dns query timeout in seconds
            --dns_timeout_max <i>       disable dnsbl after <i> timeouts
            --dns_timeout_interval <i>  re-enable dnsbl after <i> seconds
            --cache-rbl-timeout <i>     default dns ttl if not specified in ruleset
            --cache-rbl-default <s>     default dns pattern if not specified in ruleset
            --cleanup-rbls <i>          cleanup old dns cache items every <i> seconds
            --dns_async_txt             perform dnsbl A and TXT lookups simultaneously
            --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

        Optional:
        -t, --test                      testing, always returns "dunno"
        -S, --summary <i>               show stats every <i> seconds
            --noidlestats               disables statistics when idle
            --norulestats               disables per rule statistics
        -I, --instantcfg                reloads ruleset on 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

        Logging:
        -l, --logname <label>           label for syslog messages
            --facility <s>              use syslog facility <s>
            --socktype <s>              use syslog socktype <s>
            --nodnslog                  do not log dns results
            --anydnslog                 log any dns (even cached) results
            --norulelog                 do not log rule actions
            --nolog|--perfmon           no logging at all
        -v, --verbose                   verbose logging, use twice to increase
            --debug <s>                 list of debugging classes

        Information (use only at command-line!):
        -h, --help                      display this help and exit
        -m, --manual                    shows program manual
        -V, --version                   output version information and exit
        -D, --defaults                  show postfwd2 settings and exit
        -C, --showconfig                show postfwd2 ruleset and exit (-v allowed)
        -L, --stdout                    redirect syslog messages to stdout
        -q, --quiet                     no syslogging, no stdout (-P works for compatibility)

        Obsolete (only for compatibility with postfwd v1):
        -d|--daemon, --shortlog, --dns_queuesize, --dns_retries

πŸ’– DESCRIPTION πŸ’–

🌸 INTRODUCTION 🌸

so postfwd2 exists to smoosh all your complicated postfix restrictions into one ruleset, the way actual firewalls do it. it talks the postfix policy delegation protocol so it can gatekeep access to your mail system before a message even gets accepted. (if you wanna read the lore, it's at http://www.postfix.org/SMTPD_POLICY_README.html.)

basically you pick an action (like reject or dunno) for a combination of several smtp parameters β€” sender and recipient address, size, the client's TLS fingerprint, all of it. and it also hands you macros/acls so your config can be straightforward and easy to read. periodt.

the features, bestie:

  • complex combinations of smtp parameters
  • combined RBL/RHSBL lookups with arbitrary actions depending on results
  • a scoring system
  • date/time based rules
  • macros/ACLs, Groups, Negation
  • compare request attributes (like client_name and helo_name)
  • internal caching for requests and dns lookups
  • built in statistics for rule efficiency analysis

πŸŽ€ CONFIGURATION πŸŽ€

a config line is just optional item=value pairs, glued together with semicolons (;), plus the action you actually want:

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

example, because examples are everything:

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

that one denies all mail from 192.168.1.1 with envelope sender no@bad.local. and the order? literally does not matter. so this next one gives you the exact same result as the one above:

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

now, the way request items get compared to the ruleset can be tweaked like this:

====================================================================
 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)
====================================================================

and if you wanna be able to find a specific rule in your logs later (you do, trust), give it a unique identifier:

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

you can also use these identifiers as targets for the jump() command (peep the ACTIONS section below, it's coming). leading or trailing whitespace characters get ignored, so no stress. oh and use '#' to comment your configuration β€” others will appreciate it. 🫢

a ruleset is just one or multiple rules, which can come from files or from command line arguments. more on that in the COMMAND LINE section below.

multi-line rules, since postfwd version 1.30: you can define rules that span multiple lines 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

but postfwd versions before 1.30 need trailing ';' and '\' characters, so it looks like this instead:

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

...and we're not done yet, bestie. more coming. πŸ’œ

  • score β€” bestie, the moment that specific score gets hit (peep the ACTIONS section πŸ‘€) the action you specified gets handed back to postfix. ⚠️ heads up: scores are set global until you redefine them!
  • request_score β€” lets you peek at a request's score. use it as a variable like $$request_score.
  • rbl, rhsbl, rhsbl_client, rhsbl_sender, rhsbl_reverse_client β€” query the RBLs/RHSBLs you name. possible values are: <name>[/<reply>/<maxcache>, <name>/<reply>/<maxcache>] (defaults: reply=^127\.0\.0\.\d+$ and maxcache=3600) ✨ and the results of all the rhsbl_* queries get combined into rhsbl_count (see below).
  • rblcount, rhsblcount β€” the minimum RBL/RHSBL hitcounts needed to match. if you don't specify one, a single RBL/RHSBL hit will match the rbl/rhsbl items. you can also drop all in there to evaluate every single item, and use it as a variable inside an action (see the 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 β€” postfwd2 tries to look up the helo_name. use helo_address=!!(0.0.0.0/0) to check for unknown. > please don't use this for positive access control (whitelisting), bestie β€” it might be forged. 😭
  • sender_ns_names, sender_ns_addrs β€” postfwd2 tries to look up the names/ip addresses of the nameservers for the sender domain part. > same warning, no positive access control (whitelisting), it might be forged. πŸ™ˆ
  • sender_mx_names, sender_mx_addrs β€” postfwd2 tries to look up the names/ip addresses of the mx records for the sender domain part. > and again, do NOT use this for positive access control (whitelisting), because it might be forged. πŸ’€
  • version β€” the postfwd2 version, contains "postfwd2 n.nn". this is what lets you do version-based checks in your rulesets (say, for a migration ✨). it plays nice 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. it 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 all these you can specify any attribute of the postfix policy delegation protocol. go off, combine them however you need (there's a whole EXAMPLES section below, go look 🫢).

Most values can be specified as regular expressions (PCRE). peep the table below for the 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 lives at <http://www.postfix.org/SMTPD_POLICY_README.html> πŸ’– please read it carefully so you know which attribute can be used at which level of the smtp transaction (like, size will only work reliably at END-OF-MESSAGE level, no cap). also: pattern matching is performed case insensitive.

Using the same item multiple times is allowed, and it gets compared as a logical OR β€” which means this does exactly what you'd expect ✨:

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 can also be written 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 MUST be unique:

id, minimum and maximum values, rblcount and rhsblcount

Any item can be negated by putting !! in front of it, like:

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

or by using the right compare operator:

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

and to avoid any confusion with regexps (or just for better visibility, slay) you can use '!!(...)':

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

Request attributes can be compared by putting $$ in front of them, like:

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 the list above ⬆️). the comparison will be performed as a case insensitive exact match. use the -vv option to debug it πŸ”.

These special items get 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 get changed for any matching rule:

request_hits    - contains ids of all matching rules

which means you might need to save them if you're planning to use those 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 πŸ“

ever since postfwd1 v1.15 and postfwd2 v0.18, long item lists can live in their own separate files πŸ—‚οΈ:

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

postfwd2 will read a list of items (one item per line, bestie) from /etc/postfwd/wl_ccerts. and yes, 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 do:

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

this will ignore the right-hand value. and you can totally mix items ✨:

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

✨ vibe check your config ✨

Bestie you can literally check your whole configuration with the --show_config option at the command line, no cap:

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

and it should give you 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 (rude, but ok):

# postfwd2 --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. Which means postfwd2 needs to be reloaded if a file has changed. That's just how it is, bestie 🫢

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 single 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, look:

## 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"

Files can refer to other files, yes really, nesting is giving main character energy. The following is valid:

-- FILE /etc/postfwd/rules.cf --
id=R01; 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
⚠️ Note that there is currently no loop detection (/a/file calls /a/file) and that this feature is only available with postfwd1 v1.15 and postfwd2 v0.18 and higher. Be careful out there πŸ’€

🎬 ACTIONS 🎬

✨ General ✨

Actions will be executed when all rule items have matched a request (or at least one of any item list). You can refer to request attributes by preceding $$ characters, like:

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 πŸ’Œ

Actions will be replied to postfix as result to policy delegation requests. Any action that postfix understands is allowed β€” see man 5 access or <http://www.postfix.org/access.5.html> for a description. If no action is specified, the postfix WARN action which simply logs the event will be used for the corresponding rule.

postfwd2 will return dunno if it has reached the end of the ruleset and no rule has matched. This can be changed by placing a last rule containing only an action statement:

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

🌈 postfwd2 actions 🌈

postfwd2 actions control the behaviour of the program. Currently you can specify the following:

  • jump (<id>) β€” jumps to rule with id <id>, use this to skip certain rules. you can jump backwards β€” but remember that there is no loop detection at the moment! jumps to non-existing ids will be skipped.
  • score (<score>) β€” the request's score will be 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 --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 postfwd2 score exceeded").

  • set (<item>=<value>,<item>=<value>,...) β€” this command allows you to 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 information. 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)
  • size (<item>/<max>/<time>/<action>) β€” this command works similar to the rate() command with the difference that the rate counter is increased by the request's size attribute. to do this reliably you should call postfwd2 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>) β€” this command works similar to the rate() command with the difference that 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.
  • 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 postfwd2 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 it's 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.

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|)[\.-_]

Macros can contain macros, too:

# 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 bestie, macros are just simple text substitutions β€” no cap. If you wanna know the deets, the "PARSER" section has you covered. πŸ’…

🧩 PLUGINS 🧩

Description

The plugin interface is literally your backstage pass to define your own checks and level up postfwd's whole functionality. And like… if you build something cute, share it with the class?? We're all besties here. 🫢

Warning

Okay so ngl, the plugin interface is still in 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. It's giving "with great power" energy fr fr.

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) β€” not even a little bit. πŸ™ˆ


ITEMS

Item plugins are perl subroutines that integrate additional attributes into requests before they get evaluated against postfwd's ruleset, just like any other item of the policy delegation protocol. Translation: you can build your own checks. Iconic behavior honestly. ✨

⚠️ plugin-items can not be used selectively. These functions will be executed for every request postfwd receives, so keep performance in mind bestie. πŸ‘‘
SYNOPSIS: %result = postfwd_items_plugin{<name>}(%request)

That means your subroutine, called <name>, has access to a hash called %request, which contains all request attributes β€” like $request{client_name} β€” and it must return a value in this form:

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

This creates the new item <item> containing <value>, which gets integrated into 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. The way that it just handles it for you if you don't care… πŸ’…

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. Your call bestie, main character energy either way. πŸŽ€

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

These arguments specify the source of the postfwd2 ruleset. Which means at least one of the following is required for postfwd2 to work at all. No ruleset, no vibes. πŸ’€

  • -f, --file <file> β€” Reads rules from <file>. Please see the CONFIGURATION section below for more info, bestie.
  • -r, --rule <rule> β€” Adds <rule> to the ruleset. Remember you might have to quote strings that contain whitespaces or shell characters. Yes, the shell is dramatic like that. 🐚

Scoring

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

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

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

In case of multiple scores, the highest match will count. The order of the arguments will be reflected in the postfwd2 ruleset. So order matters, lowkey. πŸ”₯

Networking

postfwd2 can be run as a daemon so it listens on the network for incoming requests. The following arguments control its behaviour in this case. πŸ‘‘

  • -d, --daemon β€” postfwd2 will run as a daemon and listen on the network for incoming queries (default 127.0.0.1:10045).
  • -i, --interface <dev> β€” Bind postfwd2 to the specified interface (default 127.0.0.1).
  • -p, --port <port> β€” postfwd2 listens on the specified port (default tcp/10045).
  • --proto <type> β€” The protocol type for postfwd's socket. Currently you may use 'tcp' or 'unix' here. To use postfwd2 with a unix domain socket, run it as follows:
postfwd2 --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 of the master process (pidfile).
⚠️ Attention: This is umask, not chmod β€” you have to specify the bits that should NOT apply. E.g.: umask 077 equals to chmod 700. Don't get it twisted bestie. 😭
  • --cache_umask <mask> β€” Changes the umask for filepermissions of the cache process (unix domain socket).
  • --server_umask <mask> β€” Changes the umask for filepermissions of the server process (unix domain socket).
  • -R, --chroot <path> β€” Chroot the process to the specified path.
🚨 Please look at http://postfwd.org/postfwd2-chroot.html before use! Fr fr, read first.
  • --pidfile <path> β€” The process id will be saved in the specified file.
  • --facility <f> β€” sets the syslog facility, default is 'mail'.
  • --socktype <s> β€” tells Sys::Syslog which socktype to use, and your options are 'native', 'inet' or 'unix'. The default is to auto-detect it based on your module version and your os 🧚
  • -l, --logname <label> β€” slaps a label on your syslog messages πŸ’– super handy when you're running multiple instances of postfwd and need to tell them apart.
  • --loglen <int> β€” chops any syslog message down once it hits <int> characters. Snip snip βœ‚οΈ

✨ Plugins ✨

  • --plugins <file> β€” loads postfwd plugins from <file>. Wanna know more? Peep http://postfwd.org/postfwd.plugins, or the plugins.postfwd.sample that ships in the tarball 🫢

🌸 Optional arguments 🌸

These parameters change the way postfwd2 does its thing. You can combine literally any of them, no cap πŸ’…

  • -v, --verbose β€” verbose logging spills a ton of genuinely useful info, but bestie, it will make your logfiles grow like crazy 😭 so use it with caution. Set it twice (-vv) to get even more β€” that logs all request attributes.
  • -c, --cache <int> β€” timeout for the request cache, default is 600. Results for identical requests get cached until the config reloads or this time (in seconds) runs out. Setting it to 0 turns the whole feature off.
  • --cache-no-size β€” ignores the size attribute when comparing cache entries, which means way better cache-hit rates πŸ“ˆ You should set this if you don't use the size item in your ruleset.
  • --cache-no-sender β€” ignores the sender address when comparing cache entries, which again means better cache-hit rates. Set it if you don't use the sender item in your ruleset.
  • --cache-rdomain-only β€” this strips the localpart off the recipient's address before filling the cache. Can considerably bump up those cache-hit rates πŸ‘‘
  • --cache-rbl-timeout <timeout> β€” default 3600. This default value is used as the timeout in seconds for rbl cache items whenever the ruleset doesn't specify one.
  • --cache-rbl-default <pattern> β€” default ^127.0.0.\d+$. Matches <pattern> against rbl/rhsbl answers (regexp) whenever the ruleset doesn't specify one.
  • --cacheid <item>, <item>, ... β€” this csv-separated list of request attributes gets used to build the request cache identifier. Only use this if you know exactly what you're doing, fr fr. Like, if you use postfwd2 purely for RBL/RHSBL control, you could set it to
postfwd2 --cache=3600 --cacheid=client_name,client_address

That makes caching more efficient and boosts postfwd's performance πŸš€

⚠️ Warning: you have to list all the items here that get used in your ruleset!
  • --cleanup-requests <interval> β€” default 600. The request cache gets scanned for timed-out items after this <interval> in seconds. It's a minimum value, and the cleanup only actually happens when a new request shows up.
  • --cleanup-rbls <interval> β€” default 600. The rbl cache gets scanned for timed-out items after this <interval> in seconds. Also a minimum value, and also only happens when a new request arrives.
  • --cleanup-rates <interval> β€” default 600. The rate cache gets scanned for timed-out items after this <interval> in seconds. Minimum value again, and again only when a new request arrives.
  • -S, --summary <int> β€” default 600. Shows some usage statistics every <int> seconds (program uptime, request counter, matching rules). This option is included by the -v switch. It uses the alarm signal, so you can force postfwd2 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 squeaky clean if you don't use them 🧼 Heads up: this option does nothing at all without --summary or --verbose set.
  • -L, --stdout β€” redirects all syslog messages to stdout for debugging. Never use this with postfix! πŸ’€
  • -t, --test β€” in test mode postfwd2 always returns "dunno", but logs according to its ruleset. -v gets set automatically with this option.
  • -n, --nodns β€” disables all DNS based checks like RBL checks. Rules containing such elements get ignored.
  • -n, --nodnslog β€” disables logging of dns events.
  • --dns_timeout β€” default: 14. Sets the timeout for asynchonous 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 together 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 because of the extra queries, but it might increase throughput since 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 postfwd2 receives. This gives you on-the-fly configuration changes without a restart ✨ Though files are only read when necessary (meaning their access times changed since the last read), this might significantly increase system load. Just so you know πŸ’…
  • --config_timeout β€” default 3. Timeout in seconds to parse a single configuration line. If it's exceeded, the rule gets skipped. This exists to prevent problems from large files or loops.
  • --keep_rates β€” default 0. With this option set, postfwd2 does not clear the rate limit counters on reload. πŸ“Œ Please note 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 gives you persistent rate limits across program restarts or reboots, iconic πŸ‘‘ Please note 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 any 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! πŸ™ˆ

  • -C, --showconfig β€” displays the current ruleset. Use -v for verbose output.
  • -V, --version β€” displays the program version.
  • -h, --help β€” shows program usage.
  • -m, --manual β€” displays the program manual.
  • -D, --defaults β€” displays complete postfwd2 settings.
  • -P, --perfmon β€” this option turns off any syslogging and output. It's included for performance testing.
  • --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.

πŸ”„ REFRESH πŸ”„

In daemon mode, postfwd2 reloads its ruleset after receiving a HUP signal. Wanna have your configuration refreshed for every single request postfwd2 receives instead? Go read the description of the '-I' switch πŸ¦‹


🌈 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

So yeah bestie, that's whitelisting and TLS control served fresh πŸ’…πŸ“


Combined RBL checks, but make it a whole personality πŸ’…

okay so this first block is your greatest hits of RBL combos β€” four separate ways to get a REJECT out of DNS blocklists, and the comments spell out exactly which condition each one fires on. read the comments, they're the receipts:

## 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

not the 1200 on RBL02 bestie β€” that's the dns cache timeout, shorter than the usual 3600. and RBL03 is literally "two strikes and you're out" with rblcount=2. πŸŽ€


Message size β€” yes she has limits, and they're tiered ✨

heads up: this one requires message_size_limit to be set to 30000000, that's not optional. also the comments tell you who gets what:

## 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

yes, id=SZ002 shows up twice, that's how it's written, don't come for me πŸ™ˆ everything else is one rule per tier, then SZ100 catches whatever falls through and hits it with a REJECT. the protocol_state==END-OF-MESSAGE on every single line is doing a LOT of heavy lifting here.


Selective Greylisting πŸ¦‹

πŸ“’ IMPORTANT: postfwd does not include greylisting. this setup needs a running postgrey service on port 10031 and a postfix restriction class in your main.cf. the original gives you the exact snippet:
## 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$

three vibes get sent to the greylist chair: zen.spamhaus.org results 127.0.0.10 or .11 (cache timeout 1200s), clients with literally no rDNS, and clients from those dialin domains. 🌸


Date Time β€” she has a schedule and she's sticking to it ⏰

this whole block is just time-based drama and honestly? iconic:

## 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

the jim rules are so personal and i respect it so much πŸ’€ time=-07:00:00 means everything up to 7am, time=22:00:00- means everything from 10pm onwards. months=-Apr = up through April. days=!!Mon-Fri = the !! negation, so NOT Monday–Friday, i.e. weekend mail gets greylist-checked. no cap.


Usage of jump β€” go directly to R100, do not pass go πŸƒβ€β™€οΈπŸ’¨

the comment lays out the goal: 30MB for the special ones, 10MB for everyone else.

## 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

so Alice, Bob, Jane, the 192.168.1.0/24 crew, and three specific cert fingerprints all jump(R100) and get the 30MB ceiling. everyone else lands on R099 and gets 10MB. the three ccert_fingerprint values are AA:BB:CC:DD:..., AF:BE:CD:DC:... and DD:CC:BB:DD:... β€” yes the last two look cursed, that's literally what's written πŸ’…


Usage of score β€” points-based chaos, and i'm obsessed 🎯

comment first, then the rules:

## 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$
...

score 2.6 β†’ greylist check, score 5.0 β†’ rejected, whitelists push the score down by 1.0, RBL/RHSBL hits push it up by 2.5, matching rDNS gives you a lil -0.2 treat, and ^unknown$ clients eat a 2.7. the trailing ... is in the original, so it stays. πŸ”₯


Usage of rate and size β€” the "slow down bestie" combo 🐒

## 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)

two rules, both aimed at unknown clients. RATE01 watches client_address, 30 requests, 3600 seconds, then hits them with 450 4.7.1 sorry, max 30 requests per hour. SIZE01 watches client_address, 1572864 bytes (that's your 1.5mb, they just wrote it in bytes, respect), 600 seconds, then 450 4.7.1 sorry, max 1.5mb per 10 minutes. 🌈


Macros β€” write once, use everywhere 🧚

definitions first, then the rules that call them:

## 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|)[\.-_]

macro time!!! &&RBLS bundles five RBLs into one reusable chunk, &&GONOW bundles a whole REJECT message with a http://www.domain.local link in it. then three rules chain both macros together and just vary the client_name pattern. so clean, so slay. ✨


Groups β€” macros but make it a whole mood board πŸ‘‘

this is the big one, so buckle up. definitions:

## 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
};

note the ... inside &&RHSBLS, &&DYNAMIC and &&BAD_HELO β€” those are literally in the original, they're placeholders, don't @ me. πŸ’– and yes, &&MAINTENANCE has four date= lines (the 15th of January, April, July and October) plus a time=03:00:00 - 04:00:00 window β€” spaces around that dash, exactly like that.

then the rules using them:

# rules
id=COMBINED    ;  &&RBLS ;  &&DYNAMIC ;  action=REJECT dynamic client and listed on RBL
id=MAINTENANCE ;  &&MAINTENANCE       ;  action=DEFER maintenance time - please try again later

and then the glow-up version using set(), with a comment explaining why it's better:

# 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

the whole point: set your flags once with set(HIT_*=1), then compare the cheap flags instead of re-running the expensive group checks over and over. each REJECT even points at its own little URL with a different reject=01/02/03 param. πŸ’€


combined with enhanced rbl features 🌟

last block, and it's the fancy one β€” rhsblcount=all, rblcount=all, macros, and a set() that stacks values together:

## 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]

HIT_dnsbls starts at $$rhsblcount, then += adds $$rblcount on top, and HIT_dnstxt grabs $$dnsbltext. then RBL02 fires when HIT_dnsbls>=2 and rejects with 554 5.7.1, echoing both counters back in the message. chef's kiss, truly 🫢


✨ PARSER ✨

πŸŽ€ Configuration πŸŽ€

okay so you can hand the postfwd2 ruleset straight to it on the command line with -r, or read it out of files with -f. the order of your arguments gets kept, so it does what you meant. and pleaaaase check your parser with the -C | --showconfig switch before you deploy a fresh config, that's the whole point.

this call:

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

will produce this 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"

see how it kept your order? TEST first, then the file contents, then DEFAULT. ✨


multiple items of the same type get added to lists (peep the ITEMS section for more on that):

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

and that will result in:

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

two client_address entries went in, one comma-separated list came out. also notice it auto-assigned id->"R-0" since you didn't give one. πŸ’…


macros get evaluated at the configuration stage, which means that:

postfwd2 --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$"

so --showconfig already hands you the fully-expanded version. no guessing what &&RBLS actually contained. πŸ‘‘


🌈 Request processing 🌈

when a policy delegation request shows up, it gets compared against postfwd's ruleset. to watch that happen in excruciating detail, crank the verbosity with -v or -vv. and -L redirects log messages to stdout, which is exactly what you want when you're staring at a terminal. πŸ“


keeping the order of the ruleset in general, items get compared in random order, which basically means this:

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

equals this:

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

same rule, different word order, zero difference. but lists are a different story β€” those get evaluated in the order you specified them, which lets you put the fast expressions first:

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

and that produces:

[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

look at that β€” localrbl.local gets tried first because it's first in the list, then zen.spamhaus.org. and the query format is reversed-octet, so 68.10.1.7 becomes 7.1.10.68. iykyk. 🌸


the negation operator !!(<value>) has the highest priority, so it gets evaluated first. then variable substitutions happen:

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

will give

✨ Ruleset evaluation ✨

Okay so here's the tea on how a rule actually hits: it needs every item to match β€” or, if an item is a list, at least one element of that list. The literal second that one item (or all elements of a list) fails to compare against the request attribute, the parser just yeets itself to the next rule in the postfwd2 ruleset. πŸ’…

When a rule does match, you get two options, bestie:

  • Rule returns postfix action (dunno, reject, ...) β€” the parser stops rule processing and hands the action back to postfix. No other rules get evaluated. That's it, that's the vibe.
  • Rule returns postfwd2 action (jump(), note(), ...) β€” the parser evaluates the given action and keeps going with the next rule (except for the jump() or quit() actions β€” go peek at the "ACTIONS" section for more info, iykyk). Nothing gets sent to postfix.

And if no rule has matched and you've reached the end of the ruleset? postfwd2 returns dunno without logging anything unless you're in verbose mode. Want to change that behaviour? Drop a last catch-all rule like this:

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

That will log any request that passes the ruleset without having hit a prior rule. Cute, right? πŸŽ€


πŸ’€ DEBUGGING πŸ’€

To debug special steps of the parser, the --debug switch takes a list of debug classes. Currently the following classes are defined:

all cache config debugdns devel dns getcache getdns
getdnspacket rates request setcache setdns
parent_cache parent_dns_cache parent_rate_cache parent_request_cache
child_cache  child_dns_cache  child_rate_cache  child_request_cache

Pick your fighters, bestie. ✨


πŸ”Œ INTEGRATION πŸ”Œ

🌈 Integration via daemon mode 🌈

The common way to use postfwd2 is to start it as a daemon, listening at a specified tcp port. postfwd2 will spawn multiple child processes which communicate with a parent cache. This is the preferred way to use postfwd2 in high volume environments β€” main character energy fr fr. Start postfwd2 with the following parameters:

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

For efficient caching you should check if you can use the options --cacheid, --cache-rdomain-only, --cache-no-sender and --cache-no-size. Go look, they're right there.

Now check your syslogs (default facility "mail") for a line like:

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

and use netstat -an|grep 10045 to check for something like

tcp  0  0  127.0.0.1:10045  0.0.0.0:*  LISTEN

If everything works, open your postfix main.cf and insert the following:

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

Reload your configuration with postfix reload and watch your logs. If it works you should see lines like the following 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

If you want to check for size or rcpt_count items you must integrate postfwd2 in smtp_data_restrictions or smtpd_end_of_data_restrictions. And of course you can also specify a restriction class and use it in your access tables, because why not. First create 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:10045             <--- integration

127.0.0.1:10045_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. Slay. πŸ‘‘


πŸ§ͺ TESTING πŸ§ͺ

First you have to create a ruleset (see Configuration section). Check it with

postfwd2 -f /etc/postfwd.cf -C

There is an example policy request distributed with postfwd, called 'request.sample'. Simply change it to meet your requirements and use

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

You should get an answer like

action=<whateveryouconfigured>

For network tests I use netcat:

nc 127.0.0.1 10045 <request.sample

to send a request to postfwd. If you receive nothing, make sure that postfwd2 is running and listening on the specified network settings. No notes, bestie. πŸ¦‹


πŸš€ PERFORMANCE πŸš€

Some of these proposals might not match your environment. Please check your requirements and test new options carefully! πŸ™ˆ

  • 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 πŸ‘€

See http://www.postfix.org/SMTPD_POLICY_README.html for a description of how Postfix policy servers work. It's giving required reading. πŸ“š


πŸ“œ LICENSE πŸ“œ

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

Copyright (c) 2009, 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 literally said it himself, so slide into those inboxes. 🫢


And that's a wrap on the whole page, bestie β€” no cap. This little masterpiece came to you courtesy of perl v5.14.2 and it's dated 2013-04-18, so yes it's vintage and yes it still ate. πŸ’…βœ¨πŸŒΈ

πŸ“¦ where this page comes from