NAME
    postfwd - postfix firewall daemon

SYNOPSIS
    postfwd [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

            Scoring:
            -s, --scores <v>=<r>      returns <r> when score exceeds <v>

            Networking:
            -d, --daemon              run postfwd as daemon
            -i, --interface <dev>     listen on interface <dev>
            -p, --port <port>         listen on port <port>
            -u, --user <name>         set uid to user <name>
            -g, --group <name>        set gid to group <name>
            -R, --chroot <path>       chroot the daemon to <path>
                --pidfile <path>      create pidfile under <path>

            optional:
            -v, --verbose             verbose logging
            -c, --cache <int>         sets the request-cache timeout to <int> seconds
                --cache-no-size       ignores size attribute for caching
                --cache-rdomain-only  ignores localpart of recipient address in cache
            -S, --summary <int>       show some usage statistics every <int> seconds
            -t, --test                testing, always returns "dunno"
            -n, --nodns               disable dns
            -I, --instantcfg          re-reads rulefiles for every new request

            informational (use only at command-line!):
            -C, --showconfig          shows config, -v for verbose
            -P, --perfmon             no syslogging, no stdout
            -V, --version             shows program version
            -h, --help                shows usage
            -m, --manual              shows program manual

DESCRIPTION
  INTRODUCTION
    postfwd is written to combine complex postfix restrictions in a ruleset
    similar to those of the most firewalls. 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 information).

    postfwd allows you to choose an action (e.g. reject, dunno) for a
    combination of several smtp parameters (like sender and recipient
    address, size or the client's TLS fingerprint). Also it offers simple
    macros/acls which should allow straightforward and easy-to-read
    configurations.

    *Features:*

    * Complex combinations of smtp parameters

    * Macros/ACLs

    * Combined RBL/RHSBL lookups with arbitrary actions depending on results

    * Scoring system

    * Date/time based rules

    * Internal caching for requests and dns lookups

    * Built in statistics with 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

    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.

  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

            score                   - when the specified score is hit (see ACTIONS section)
                                      the specified action will be returned to postfix

            rbl, rhsbl              - query the specified RBLs/RHSBLs, possible values are:
                                      <name>[/<reply>/<maxcache>, <name>/<reply>/<maxcache>]

            rblcount, rhsblcount    - minimum RBL/RHSBL hitcounts to match if not specified
                                      a single RBL/RHSBL hit will match the rbl/rhsbl items

    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-17:00                        mask = time (HH:MM:SS-HH:MM:SS)
            score=5.0                               mask = maximum floating point value
            rbl=zen.spamhaus.org                    mask = <name>/<reply>/<maxcache>[,...]
            rblcount=2                              mask = maximum integer value
            # ------------------------------
            # 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=0                       mask = maximum integer value
            # ------------------------------
            # Postfix version 2.2 and later:
            # ------------------------------
            sasl_method=plain                       mask = PCRE
            sasl_username=you                       mask = PCRE
            sasl_sender=                            mask = PCRE
            size=12345                              mask = maximum integer value
            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 = minimum integer value
            ...

    the current list can be found at
    <http://www.postfix.org/SMTPD_POLICY_README.html>. Pattern matching is
    performed case insensitive.

  ACTIONS
    *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.

    postfwd 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

    *postfwd actions*

    postfwd 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!

            score (<score>)
            the request's score will be increased by the specified <score>,
            which must be a floating point value. 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=REJECT). negative values are allowed.
            Anything else than +/-nnnn.nn will be ignored.

            wait (<delay>)
            pauses the program execution for <delay> seconds. use this for
            delaying or throtteling connections.

            quit (<code>)
            terminates the program with the given exit-code. postfix doesn`t
            like that too much, so use it with care.

            file (<file>) [STATUS unfinished]
            loads rules from <file> and continues with the rules found there.
            don't create loops here (file1 loads file1 loads file1...)!

            exec (<cmd>) [STATUS unfinished]
            executes command (output will be sent to syslog if "-v" is set)
            if the return code equals to zero postfwd returns dunno. any
            other result will create a reject. spawning external programs
            can be very time expensive and open potential security holes -
            use it with care.

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

  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.

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

    *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.

    *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.

            -d, --daemon
            postfwd will run as daemon and listen on the network for incoming
            queries (default 127.0.0.1:10040).

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

            -u, --user <name>
            Changes real and effective user to <name>.

            -g, --group <name>
            Changes real and effective group to <name>.

            -R, --chroot <path>
            Chroot the process to the specified path.
            Test this before using - you might need some libs there.

            --pidfile <path>
            The process id will be saved in the specified file.

    *Optional arguments*

    These parameters influence the way postfwd is working. Any of them can
    be combined.

            -v, --verbose
            Verbose logging displays a lot of useful information but can cause
            your logfiles to grow noticeably. So use it with caution.

            -c, --cache <int>
            Timeout for request cache, results for identical requests will be
            cached until config is reloaded or this time (in seconds) expired.
            A setting of 0 disables this feature.

            --cache-no-size
            Ignores size attribute for cache comparisons which will lead to better
            cache-hit rates. You should set this option, if you don't use the size
            item in your ruleset.

            --cache-rdomain-only 
            This will strip the localpart of the recipient's address before filling the
            cache. This may considerably increase cache-hit rates.
        
            -S, --summary <int>
            Shows some usage statistics (program uptime, request counter, matching rules)
            every <int> seconds (default: 600). This option is included by the -v switch.

            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] Contents: 44 cached requests, 239 cached dnsbl results
            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] 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
            ...

            -t, --test
            In test mode postfwd always returns "dunno", but logs according
            to it`s 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.

            -I, --instantcfg
            The config files, specified by -f will be re-read for every request
            postfwd receives. This enables on-the-fly configuration changes
            without restarting. Though files will be read only if necessary
            (which means their access times changed since last read) this might
            significantly increase system load.

    *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 of any syslogging and output. It is 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 it's ruleset after receiving a HUP
    signal. Please see the description of the '-I' switch to have 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.com 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\.com$ ; client_address=11.22.33.44

            ## TLS control
            # 1. *@authority.com only with correct TLS fingerprint
            # 2. *@secret.com only with keysizes >=64
            id=TL001; action=dunno                          ; sender=@authority\.com$ ; ccert_fingerprint=AA:BB:CC..
            id=TL002; action=REJECT wrong TLS fingerprint   ; sender=@authority\.com$
            id=TL003; action=REJECT tls keylength < 64      ; sender=@secret\.com$ ; 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 600s)
            # 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.local
            # 2. 20MB for SASL user joejob
            # 3. 10MB default
            id=SZ001; action=REJECT message too large ; size=30000000 ; client_name=\.customer1.local$
            id=SZ002; action=REJECT message too large ; size=20000000 ; sasl_username=^joejob$
            id=SZ003; action=REJECT message too large ; size=10000000

            ## Selective Greylisting
            # 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=greylisting ; rbl=dul.dnsbl.sorbs.net, zen.spamhaus.org/127.0.0.1[01]/1200
            id=GR002; action=greylisting ; client_name=^unknown$
            id=GR003; action=greylisting ; client_name=\.(t-ipconnect|alicedsl|ish)\.de$

            ## Date Time
            date=24.12.2007-26.12.2007   ; action=450 4.7.1 office closed during christmas
            time=04:00-05:00             ; action=450 4.7.1 maintenance ongoing, try again later
            time=07:00- ; sasl_user=jim  ; action=450 4.7.1 to early for you, jim
            time=-22:00 ; sasl_user=jim  ; action=450 4.7.1 to late now, jim

            ## 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 ; action=REJECT message too big (max. 10MB); size=10000000
            id=R100 ; 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=greylisting
            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(2.7)      ; client_name=^unknown$
            ...

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

  INTEGRATION
    *Integration via daemon mode*

    The common way to use postfwd is to start it as daemon, listening at a
    specified tcp port. As postfwd will run in a single instance
    (multiplexing mode), it will take most benefit of it`s internal caching
    in that case. Start postfwd with the following parameters:

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

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

            Aug  9 23:00:24 mail postfwd[5158]: postfwd n.nn successfully bound to 127.0.0.1:10040/tcp

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

            tcp  0  0  127.0.0.1:10040  0.0.0.0:*  LISTEN

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

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

    Reload your configuration with `postfix reload` and watch your logs. In
    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.org, recipient=someone@domain.local, helo=english-breakfast.cloud9.net, proto=ESMTP, state=RCPT, action=dunno

    Of course you can also specify a restriction class and use it in your
    access tables. 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: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.

    *Integration via xinetd*

    There might be several reasons for you to use postfwd via a tcp wrapper
    package like xinetd (see <http://www.xinetd.org/>). I won`t discuss that
    here. If you plan to do so, just add the following 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
    experience problems you might want to check your system's log for xinetd
    errors like "socket already in use".

    The integration with postfix is similar to the *Integration via daemon
    mode* section above. Reload postfix and watch your logs to see if
    everything works.

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

            postfwd -f /etc/postfwd.cf -C

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

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

    You should get an answer like

            action=<whateveryouconfigured>

    For network tests I use netcat:

            nc 127.0.0.1 10040 <request.small

    to send a request to postfwd. If you receive nothing, make sure that
    postfwd is running and listening on the specified network settings.

  SEE ALSO
    See <http://www.postfix.org/SMTPD_POLICY_README.html> for a description
    of how Postfix policy servers work.

LICENSE
    This program is free software; you can redistribute and/or modify it in
    any way you want.

    This program is distributed in the hope that it will be useful, but
    WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

AUTHOR
    Jan Peter Kessler <postfwd@jpkessler.de>. Let me know, if you have any
    suggestions.

