Posts tagged firewall

firewall with systemd file

posted on 2016-09-14 00:38

Some while ago I created a firewall script here, but this was prior to systemd. Now here's an update on how to fix this. First the unit-file, then the firewallscript in fullquote again.

prerequisites

apt install -y libnetfilter-conntrack3 libnfnetlink0
echo "net.netfilter.nf_conntrack_acct=1" >> /etc/sysctl.d/iptables.conntrack.accounting.conf

systemd unit file

/lib/systemd/system/firewall.service:

[Unit]
Description=Do some Firewalling.
Requires=local-fs.target
After=local-fs.target
Before=network.target

[Install]
WantedBy=multi-user.target

[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/usr/sbin/firewall start
ExecStop=/usr/sbin/firewall stop

firewallscript

/usr/sbin/firewall:

#!/bin/bash

# aliasing
IPTABLES=$(which iptables)
# set IF to work on
O=eth0
I=eth0


# load kernel modules
modprobe ip_conntrack
modprobe ip_conntrack_ftp

case "$1" in

    start)
        echo 60 > /proc/sys/net/ipv4/tcp_fin_timeout
        echo 0 > /proc/sys/net/ipv4/tcp_ecn

        echo -n "Starting stateful paket inspection firewall... "

        # delete/flush old/existing chains
        $IPTABLES -F
        # delete undefined chains
        $IPTABLES -X

        # create default chains
        $IPTABLES -N INPUT
        $IPTABLES -N OUTPUT

        # create log-drop chain
        $IPTABLES -N LOGDROP

        # set default chain-actions, accept all outgoing traffic per default
        $IPTABLES -P INPUT LOGDROP
        $IPTABLES -P OUTPUT ACCEPT
        $IPTABLES -P FORWARD ACCEPT

        # make NAT Pinning impossible
        $IPTABLES -A INPUT -p udp --dport 6667 -j LOGDROP
        $IPTABLES -A INPUT -p tcp --dport 6667 -j LOGDROP
        $IPTABLES -A INPUT -p tcp --sport 6667 -j LOGDROP
        $IPTABLES -A INPUT -p udp --sport 6667 -j LOGDROP
        $IPTABLES -A OUTPUT -p tcp --dport 6667 -j LOGDROP
        $IPTABLES -A OUTPUT -p udp --dport 6667 -j LOGDROP
        $IPTABLES -A OUTPUT -p tcp --sport 6667 -j LOGDROP
        $IPTABLES -A OUTPUT -p udp --sport 6667 -j LOGDROP

        # drop invalids
        $IPTABLES -A INPUT -m conntrack --ctstate INVALID -j LOGDROP

        # allow NTP and established connections
        $IPTABLES -A INPUT -p udp --dport 123 -j ACCEPT
        $IPTABLES -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
        $IPTABLES -A INPUT -i lo -j ACCEPT

        # pings are allowed
        $IPTABLES -A INPUT -p icmp --icmp-type 8 -m conntrack --state NEW -j ACCEPT

        # drop not routable networks
        $IPTABLES -A INPUT -i $I -s 169.254.0.0/16 -j LOGDROP
        $IPTABLES -A INPUT -i $I -s 172.16.0.0/12 -j LOGDROP
        $IPTABLES -A INPUT -i $I -s 192.0.2.0/24 -j LOGDROP
        #$IPTABLES -A INPUT -i $I -s 192.168.0.0/16 -j LOGDROP
        #$IPTABLES -A INPUT -i $I -s 10.0.0.0/8 -j LOGDROP
        $IPTABLES -A INPUT -s 127.0.0.0/8  ! -i lo -j LOGDROP




        # OPEN PORTS FOR USED SERVICES

        ## SSH
        $IPTABLES -A INPUT -i $I -p tcp -m conntrack --ctstate NEW --dport 22 -j ACCEPT

        ## HTTPD
        #$IPTABLES -A INPUT -i $I -p tcp -m conntrack --ctstate NEW --dport 80 -j ACCEPT
        #$IPTABLES -A INPUT -i $I -p tcp -m conntrack --ctstate NEW --dport 443 -j ACCEPT

        ## OVPN
        #$IPTABLES -A INPUT -i $I -p udp -m conntrack --ctstate NEW --dport 1194 -j ACCEPT

        ## MySQL
        #$IPTABLES -A INPUT -i $I -p tcp -m conntrack --ctstate NEW --dport 3306 -j ACCEPT






        # Portscanner will be blocked for 15 minutes
        $IPTABLES -A INPUT  -m recent --name psc --update --seconds 900 -j LOGDROP

        # only use when ports not available from the internet
        $IPTABLES -A INPUT ! -i lo -m tcp -p tcp --dport 1433  -m recent --name psc --set -j LOGDROP
        $IPTABLES -A INPUT ! -i lo -m tcp -p tcp --dport 3306  -m recent --name psc --set -j LOGDROP
        $IPTABLES -A INPUT ! -i lo -m tcp -p tcp --dport 8086  -m recent --name psc --set -j LOGDROP
        $IPTABLES -A INPUT ! -i lo -m tcp -p tcp --dport 10000 -m recent --name psc --set -j LOGDROP

        ### drop ms specific WITHOUT LOGGING - because: else too much logging
        $IPTABLES -A INPUT -p UDP -m conntrack --ctstate NEW --dport 137:139 -j DROP
        $IPTABLES -A INPUT -p UDP -m conntrack --ctstate NEW --dport 67:68 -j DROP

        # log packets to be dropped and drop them afterwards
        $IPTABLES -A INPUT -j LOGDROP
        $IPTABLES -A LOGDROP -j LOG --log-level 4 --log-prefix "dropped:"
        $IPTABLES -A LOGDROP -j DROP

        echo "Done."
    ;;

    stop)
        echo -n "Stopping stateful paket inspection firewall... "
        /etc/init.d/fail2ban stop
        # flush
        $IPTABLES -F
        # delete
        $IPTABLES -X
        # set default to accept all incoming and outgoing traffic
        $IPTABLES -P INPUT ACCEPT
        $IPTABLES -P OUTPUT ACCEPT
        echo "Done."
    ;;

    restart)
        echo -n "Restarting stateful paket inspection firewall... "
        echo -n
        /etc/init.d/firewall stop
        /etc/init.d/firewall start
        /etc/init.d/fail2ban start
    ;;

    status)
        $IPTABLES -L -vnx --line-numbers | \
        sed ''/Chain[[:space:]][[:graph:]]*/s//$(printf "\033[31;1m&\033[0m")/'' | \
        sed ''/^num.*/s//$(printf "\033[31m&\033[0m")/'' | \
        sed ''/[[:space:]]DROP/s//$(printf "\033[31m&\033[0m")/'' | \
        sed ''/REJECT/s//$(printf "\033[31m&\033[0m")/'' | \
        sed ''/ACCEPT/s//$(printf "\033[32m&\033[0m")/'' | \
        sed -r ''/\([ds]pt[s]\?:\)\([[:digit:]]\+\(:[[:digit:]]\+\)\?\)/s//$(printf "\\\1\033[35;1m\\\2\033[0m")/''| \
        sed -r ''/\([0-9]\{1,3\}\\.\)\{3\}[0-9]\{1,3\}\(\\/\([0-9]\)\{1,3\}\)\{0,1\}/s//$(printf "\033[37;1m&\033[0m")/g'' | \
        sed -r ''/\([^n][[:space:]]\)\(LOGDROP\)/s//$(printf "\\\1\033[1;31m\\\2\033[0m")/'' | \
        sed -r ''/[[:space:]]LOG[[:space:]]/s//$(printf "\033[36;1m&\033[0m")/''
    ;;

    monitor)
        if [ -n "$2" ]
            then $(which watch) -n1 -d $IPTABLES -vnxL "$2" --line-numbers
            else $(which watch) -n1 -d $IPTABLES -vnxL --line-numbers; fi
    ;;

    *)
        echo "Usage: $0 {start|stop|status|monitor [<chain>]|restart}"
        exit 1
    ;;

esac

exit 0

The coloring at the status part when using firewall status is borked. It works, but its completely shit from what I know now. The '' were a single double-apostrophe, but I was not good enough with bash when I copy pasted it and tried to color the shell output. Some day I may fix it. Hopefully.

finishing

chmod u+x /usr/sbin/firewall
systemctl enable firewall
firewall start

usage

This should suffice, just try it:

firewall
firewall start
firewall stop
firewall restart
firewall status
firewall monitor

firewall: block DHCP traffic

posted on 2016-02-20 23:29:26

To block DHCP reqests as well as responses, block:

src port range 67 to 68
dst port range 67 to 68

Why?

[ jl@jl ~ ] 23:31:06 $ \grep -e '\s67/' -e '\s68/' /etc/services 
bootps          67/tcp                          # BOOTP server
bootps          67/udp
bootpc          68/tcp          dhcpc           # BOOTP client
bootpc          68/udp          dhcpc

Which means port 67->68 are DHCP responses, whereas 68->67 are DHCP requests.

Battling a sophos cluster and on appliances in general

posted on 2015-08-09 11:56:27

An anectdote on appliances...

Recently a sophos UTM cluster of a client died, consisting of two of these. Simply the web interface stopped working, and nothing was reachable anymore. Of course he only had clustered systems, to prevent exactly this scenario. The cause?

A NIC on one of the boxes died. Sadly the one for clustering both devices, the direct connection. The symptoms?

  • Downtime.
  • No accessible web interface.
  • Looks like both appliances play ping-pong and have a split-brain situation where they cannot settle who gets to be the master.

Getting a single application to boot and run, an all works in order again. But in the post-mortem analysis of the device nothing could be found in the web interface. All NIC's were present.

In the shell (accessed with SSH) an interface, eth3 to be exact, can be seen missing... What could that just mean?

So the vendor told 'to flash the device with current firmware release'. This did work. Rebuilding the cluster did work, too. When trying to set up link aggregation (bonding 2 NIC's, so one port can die) for future prevention, the cluster did not work reliably again.

Removed the second box again. Flashing it did not work.

RMA again, exchange it with a new box from the vendor, it works.

Usually this hardware system ist set up for the most convenient use, configuring these is a breeze (setup the first box, connect clusterconnection on eth3, wait until sync is finished, plug the other ethernet cables on), but link aggregation has to be configured by hand from scratch, which is where you will need your own solid knowledge again.

This has nothing to do with especially sophos appliances, the problems are the same for everything else, in different grades. Standards work, rest often doesn't.

And as sophisticated these things are, as inexperienced is sometimes the support technician you have on the other end of the phone. Be it from the vendor directly or from a so-called 'gold partner'. All this does not help you anything at all.

The problems come with core firewalls (F5), vpn appliances (I am looking at you, Cisco ASA cluster!!!), switches (Hi, Juniper!).

Often you have no real symptoms besides the to hardest issues to ever debug:

  • it does not work reliably
  • it is slow

The problems and the root causes for them are all understandable and fine, easily so.

But as I said, it does not help you at all with your day to day work.

And it makes you question the use and return of investment of some of these purchases, especially when you are told to wait for the next hotfix, as 'we are working on your problem' and your network goes down sporadically until then.

Whitebox hardware is the latest craze, why not build the smaller stuff yourself?

NAS boxes or firewalls are often just linux based, junipers run on a FreeBSD variant. Ponder a little on these facts, and stop pulling your hair out when things break.

iptables: sole config

posted on 2015-08-03 17:21:27

DISCLAIMER: This is almost a complete ripoff of this answer here.

Usually when ending a iptables rule with something like -j LOG --log-prefix "dropped:", this information will go straight to the general syslog file. This creates quite some clutter, depending on the rules your firewall has in place.

/etc/rsyslog.d/10-iptables:

if ( $msg contains 'IN=' and $msg contains 'OUT=' ) 
then { 
    /var/log/10-iptables.log
    stop
}

& ~ is deprecated in the new rsyslog, you should use stop instead.

/etc/logrotate.d/iptables:

/var/log/iptables.log
{
        rotate 30
        daily
        missingok
        notifempty
        delaycompress

        postrotate
                service rsyslog rotate > /dev/null
        endscript
}

Note: The prefix is set to 10- to catch it before it reach the default rules (i.e. named 50-defaults).

iptables: definitive basics

posted on 2015-03-07 16:12:02

introduction

Most of this is from the manpage anyway (man iptables), this write-up is simply aimed at getting the topic better into my head.

iptables and alternatives

iptables is the basic firewall solution on all linux-systems. (To be exact, it is the frontend for the netfilter part in the kernel, but you do not need to know that.) ipchains does also exist, but you can only choose one of both, so do yourself a favour and use the former. ipchains can also only do stateless firewalling, where each packet is looked at independently. Opposed to this is stateful firewalling which iptables can do. Stateful packet inspection, or dynamic packet inspection can also do work based on connection states, see next part on some more explanations.

Discussing anything besides iptables currently is more or less moot:

  • 2.4.x kernels and above run iptables
  • 2.2.x kernels run ipchains
  • 2.0.x kernels run ipfwadm.

This will change with nftables, which should arrive with kernel 3.13 AFAIK. By then another posting like this one will become necessary, I fear. :)

connection states

iptables can switch packets by ip data, as well as connection (stream) states. 'connection', 'connection stream' and 'stream' are synonyms in the following. Easiest these are explained with parts of TCP's three-way handshake, but keep in mind there is also UDP and ICMP. See here.

NEW
    the first packet of a connection stream, i.e. a SYN packet
    stream is classified as NEW
ESTABLISHED
    a connection was initiated through a SYN packet
    SYN/ACK'd through a second packet in reverse
    then all following packets of this stream are of this state
RELATED
    if an already ESTABLISHED connection stream spawns a new connection
    the new connection will be RELATED
    example is FTP's data channel set up by an ESTABLISHED control channel
INVALID
    packets having no state and being unidentifiable
UNTRACKED
    packets marked with the raw's table NOTRACK target show up as UNTRACKED
    i.e. for traffic on port 80 of a highly frequented webserver, to save resources.
    Sidenote: 'related' streams cannot be tracked either!

fwbuilder

If you have absolutely no idea on how to build an iptables FW by yourself, try fwbuilder, which is a GUI where you enter your rules. The result can be compiled afterwards into an iptables script. Do not forget to install the fwbuilder-ipt package, too, which you need to compile the iptables rules. There does also a backend exist, to create a pf FW script, along with others.

iptables system structure

There exist three building blocks:

  1. tables
  2. chains
  3. rules

Each table contains a set of chains, where each chain is an assortment of rules. The chains are parsed rule after rule, if no rule matches the default policy will be applied. If all rules are parsed or not, depends on rule design.

The basic tables are filter, nat and mangle. There also exist raw and secure. Usually you can forget everything besides filter (which is the default table, if you choose none it will be used) and maybe nat sometimes.

The mangle tables is interesting for marking packets and rule-based routing, to implement traffic engineering for QoS. If you have no idea what this is about, leave that stuff alone. :)

default tables and chains, ordering

Here's a list of all tables with all default chains along with an explanation which chain will be active on which packets.

filter = default table
    INPUT - packets destined locally
    FORWARD - routed packets
    OUTPUT - packets with external destination

nat = looked up when packets initiate a new connection
    PREROUTING - alters packets ASAP at arrival
    OUTPUT - alter locally generated packets before routing
    POSTROUTING - alter packets just before they go out

mangle = packet alteration 
    INPUT - alter incoming packets
    PREROUTING - alter incoming packets before routing
    OUTPUT- alter locally generated packets before routing
    FORWARD - packets being routed through the box
    POSTROUTING - alter packet after routing applied

raw = add exemptions from connection tracking, table looked up prior to anything else
    PREROUTING - all packets arriving on all interfaces
    OUTPUT - packets generated by local addresses

security = MAC networking rules, selinux stuff, called after filter table
    INPUT - incoming packetsj
    OUTPUT - alter locally generated packets before routing
    FORWARD - alter packets routed through the box

If this is rocket science, you can try the wikipedia graph here.

default commands / flags

These are to be used as presented in order here.

select your table

# omitting means implicit '-t filter'
-t <table>
    specify table

day-to-day commands

-L [<chain>]
    LIST chains + rules for current table

-S [<chain>]
    SHOW rules' code being active for current table

-I <chain> [<rulenumber>] <rule>
    INSERT rule at rulenum, prepend if no rulenum given

-A <chain> <rule>
    APPEND rule to given table
    (most often -I is needed, as append rules often don't even get hit)

-D <chain> <rule>|<rulenumber>
    DELETE rule for current table and given chain
    (--line-numbers for lookup helps a lot here)

-Z [<chain> [<rulenumber>]]
    ZERO packet counts

Lesser used:

-R <chain> <rulenumber> <rule>
    REPLACE command at line <rulenumber> (remember --line-numbers?)

cleanup commands

These are needed, in this order, to create a new, clean layout:

-F
    FLUSH all rules
-X
    delete all chains (flush previously!)
-P
    set default POLICY (DROP? REJECT? ACCEPT?)
-N
    create a NEW user-defined chain

After FLUSHING, deleting and setting INPUT and OUTPUT to default POLICY -j ACCEPT, you have effectively deactivated iptables.

parameters for rule creation

Here a lot could be written, but that is better left for googling. Be it on the -p, -s, -d flags, all you need is the internet.

However there is not a lot to be found on the -m documentation or which modules are present at a system at all.

To get some sort of overview what can be done with the netfilter modules being present on your linux system:

for i in /lib/modules/$(uname -r)/kernel/net/netfilter/*; do echo "\e[33;1m$(basename "$i")\e[0m"; strings "$i" | \grep -e description -e depends| sed -e 's/Xtables: //g' -e 's/=/: /g' -e 's/depends=/depends on: /g'; echo; done

That is ugly, but worth a look.

Further, if you wonder if a specific module / match / -m flag is possible on your system, try this:

iptables -m <modulename> --help

I.e. limit is present, as can be seen at the end of the help output:

[sjas@nb ~]$ iptables -m limit --help
iptables v1.4.21

Usage: iptables -[ACD] chain rule-specification [options]
       iptables -I chain [rulenum] rule-specification [options]
       iptables -R chain rulenum rule-specification [options]
       iptables -D chain rulenum [options]
       iptables -[LS] [chain [rulenum]] [options]
       iptables -[FZ] [chain] [options]
       iptables -[NX] chain
       iptables -E old-chain-name new-chain-name
       iptables -P chain target [options]
       iptables -h (print this help information)

Commands:


...


[!] --version   -V              print package version.

limit match options:
--limit avg                     max average match rate: default 3/hour
                                [Packets per second unless followed by 
                                /sec /minute /hour /day postfixes]
--limit-burst number            number to match in a burst, default 5
[sjas@nb ~]$ 

Whereas iplimit is not:

[sjas@nb ~]$ iptables -m iplimit --help
iptables v1.4.21: Couldn't load match `iplimit':No such file or directory

Try `iptables -h' or 'iptables --help' for more information.
[sjas@nb ~]$ 

That way you also get an easy overview on how to use a module in question, since info on the -m flags is basically non-existant on the iptables man page.

actions on packets

What happens to a packet is chosen through these:

-j <target>
    move packet to chain which is specified as JUMP target
    or use ACCEPT, DROP or REJECT targets
    RETURN used in a built-in chain tells that the chain policy decides the packet fate
    RETURN used in a user-defined chain tells to proceed in the superior chain with the next rule
    (after the one which let us jump into this user-defined chain in the first place)

-g <chain>
    if a packet is RETURNed from the GOTO chain accessed via -g, it will jump to the last chain before accessed with -j
    if you end up in a built-in chain, and no rule can be found, the default policy will hit

<nothing>
    if no action is specified, the rule is still nice to have for debugging: (and 'watch'-ing iptables output)
    although nothing happens, the packet counter is active, showing you if it matches or not

additional parameters

--line-numbers
    show rulenumbers in first column, helps when using -D
-v
    verbose mode
-n
    numeric mode: ip's/ports are shown without DNS or service resolution
-x
    exact numbers, means no kilo or mega sizes

These can also be specified i.e. -L -vnx.

Or -vnxL.

a working example

A sample configuration with some sane defaults can be found here now. I have also included colored/noncolored output and a watch shortcut for checking chains for activity easily.

Place the following into /etc/init.d/firewall, if you do not use systemd.

#!/bin/bash
#### BEGIN INIT INFO
## Provides:          firewall
## Required-Start:    mountall
## Required-Stop:
## Default-Start:     2 3 4 5
## Default-Stop:      0 1 6
## Short-Description: start firewall
#### END INIT INFO
#
#### required packages: libnetfilter-conntrack3 libnfnetlink0
## /etc/sysctl.d/iptables.conntrack.accounting.conf
## -> net.netfilter.nf_conntrack_acct=1

# aliasing
IPTABLES=$(which iptables)
# set IF to work on
O=eth0
I=eth0


# load kernel modules
modprobe ip_conntrack
modprobe ip_conntrack_ftp

case "$1" in

    start)
        echo 60 > /proc/sys/net/ipv4/tcp_fin_timeout
        echo 0 > /proc/sys/net/ipv4/tcp_ecn

        echo -n "Starting stateful paket inspection firewall... "

        # delete/flush old/existing chains
        $IPTABLES -F
        # delete undefined chains
        $IPTABLES -X

        # create default chains
        $IPTABLES -N INPUT
        $IPTABLES -N OUTPUT

        # create log-drop chain
        $IPTABLES -N LOGDROP

        # set default chain-actions, accept all outgoing traffic per default
        $IPTABLES -P INPUT LOGDROP
        $IPTABLES -P OUTPUT ACCEPT
        $IPTABLES -P FORWARD ACCEPT

        # make NAT Pinning impossible
        $IPTABLES -A INPUT -p udp --dport 6667 -j LOGDROP
        $IPTABLES -A INPUT -p tcp --dport 6667 -j LOGDROP
        $IPTABLES -A INPUT -p tcp --sport 6667 -j LOGDROP
        $IPTABLES -A INPUT -p udp --sport 6667 -j LOGDROP
        $IPTABLES -A OUTPUT -p tcp --dport 6667 -j LOGDROP
        $IPTABLES -A OUTPUT -p udp --dport 6667 -j LOGDROP
        $IPTABLES -A OUTPUT -p tcp --sport 6667 -j LOGDROP
        $IPTABLES -A OUTPUT -p udp --sport 6667 -j LOGDROP

        # drop invalids
        $IPTABLES -A INPUT -m conntrack --ctstate INVALID -j LOGDROP

        # allow NTP and established connections
        $IPTABLES -A INPUT -p udp --dport 123 -j ACCEPT
        $IPTABLES -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
        $IPTABLES -A INPUT -i lo -j ACCEPT

        # pings are allowed
        $IPTABLES -A INPUT -p icmp --icmp-type 8 -m conntrack --state NEW -j ACCEPT

        # drop not routable networks
        $IPTABLES -A INPUT -i $I -s 169.254.0.0/16 -j LOGDROP
        $IPTABLES -A INPUT -i $I -s 172.16.0.0/12 -j LOGDROP
        $IPTABLES -A INPUT -i $I -s 192.0.2.0/24 -j LOGDROP
        #$IPTABLES -A INPUT -i $I -s 192.168.0.0/16 -j LOGDROP
        #$IPTABLES -A INPUT -i $I -s 10.0.0.0/8 -j LOGDROP
        $IPTABLES -A INPUT -s 127.0.0.0/8  ! -i lo -j LOGDROP




        # OPEN PORTS FOR USED SERVICES

        ## SSH
        $IPTABLES -A INPUT -i $I -p tcp -m conntrack --ctstate NEW --dport 22 -j ACCEPT

        ## HTTPD
        #$IPTABLES -A INPUT -i $I -p tcp -m conntrack --ctstate NEW --dport 80 -j ACCEPT
        #$IPTABLES -A INPUT -i $I -p tcp -m conntrack --ctstate NEW --dport 443 -j ACCEPT

        ## OVPN
        #$IPTABLES -A INPUT -i $I -p udp -m conntrack --ctstate NEW --dport 1194 -j ACCEPT

        ## MySQL
        #$IPTABLES -A INPUT -i $I -p tcp -m conntrack --ctstate NEW --dport 3306 -j ACCEPT






        # Portscanner will be blocked for 15 minutes
        $IPTABLES -A INPUT  -m recent --name psc --update --seconds 900 -j LOGDROP

        # only use when ports not available from the internet
        $IPTABLES -A INPUT ! -i lo -m tcp -p tcp --dport 1433  -m recent --name psc --set -j LOGDROP
        $IPTABLES -A INPUT ! -i lo -m tcp -p tcp --dport 3306  -m recent --name psc --set -j LOGDROP
        $IPTABLES -A INPUT ! -i lo -m tcp -p tcp --dport 8086  -m recent --name psc --set -j LOGDROP
        $IPTABLES -A INPUT ! -i lo -m tcp -p tcp --dport 10000 -m recent --name psc --set -j LOGDROP

        ### drop ms specific WITHOUT LOGGING - because: else too much logging
        $IPTABLES -A INPUT -p UDP -m conntrack --ctstate NEW --dport 137:139 -j DROP
        $IPTABLES -A INPUT -p UDP -m conntrack --ctstate NEW --dport 67:68 -j DROP

        # log packets to be dropped and drop them afterwards
        $IPTABLES -A INPUT -j LOGDROP
        $IPTABLES -A LOGDROP -j LOG --log-level 4 --log-prefix "dropped:"
        $IPTABLES -A LOGDROP -j DROP

        echo "Done."
    ;;

    stop)
        echo -n "Stopping stateful paket inspection firewall... "
        /etc/init.d/fail2ban stop
        # flush
        $IPTABLES -F
        # delete
        $IPTABLES -X
        # set default to accept all incoming and outgoing traffic
        $IPTABLES -P INPUT ACCEPT
        $IPTABLES -P OUTPUT ACCEPT
        echo "Done."
    ;;

    restart)
        echo -n "Restarting stateful paket inspection firewall... "
        echo -n
        /etc/init.d/firewall stop
        /etc/init.d/firewall start
        /etc/init.d/fail2ban start
    ;;

    status)
        $IPTABLES -L -vnx --line-numbers | \
        sed ''/Chain[[:space:]][[:graph:]]*/s//$(printf "\033[33;1m&\033[0m")/'' | \
        sed ''/^num.*/s//$(printf "\033[33m&\033[0m")/'' | \
        sed ''/[[:space:]]DROP/s//$(printf "\033[31m&\033[0m")/'' | \
        sed ''/REJECT/s//$(printf "\033[31m&\033[0m")/'' | \
        sed ''/ACCEPT/s//$(printf "\033[32m&\033[0m")/'' | \
        sed -r ''/\([ds]pt[s]\?:\)\([[:digit:]]\+\(:[[:digit:]]\+\)\?\)/s//$(printf "\\\1\033[33;1m\\\2\033[0m")/''| \
        sed -r ''/\([0-9]\{1,3\}\\.\)\{3\}[0-9]\{1,3\}\(\\/\([0-9]\)\{1,3\}\)\{0,1\}/s//$(printf "\033[37;1m&\033[0m")/g'' | \
        sed -r ''/\([^n][[:space:]]\)\(LOGDROP\)/s//$(printf "\\\1\033[1;33m\\\2\033[0m")/'' | \
        sed -r ''/[[:space:]]LOG[[:space:]]/s//$(printf "\033[36;1m&\033[0m")/''
    ;;

    monitor)
        if [ -n "$2" ]
            then $(which watch) -n1 -d $IPTABLES -vnxL "$2" --line-numbers
            else $(which watch) -n1 -d $IPTABLES -vnxL --line-numbers; fi
    ;;

    *)
        echo "Usage: $0 {start|stop|status|monitor [<chain>]|restart}"
        exit 1
    ;;

esac

exit 0

See the services section on how to enable things like enabling HTTP traffic, just uncomment the lines in question.

The colors only work for IPv4 currently.

This blog covers .csv, .htaccess, .pfx, .vmx, /etc/crypttab, /etc/network/interfaces, /etc/sudoers, /proc, 10.04, 14.04, 16.04, AS, ASA, ControlPanel, DS1054Z, GPT, HWR, Hyper-V, IPSEC, KVM, LSI, LVM, LXC, MBR, MTU, MegaCli, PHP, PKI, PS1, R, RAID, S.M.A.R.T., SNMP, SSD, SSL, TLS, TRIM, VEEAM, VMware, VServer, VirtualBox, Virtuozzo, XenServer, acpi, adaptec, algorithm, ansible, apache, apache2.4, apachebench, apple, applet, arcconf, arch, architecture, areca, arping, asa, asdm, autoconf, awk, backup, bandit, bar, bash, benchmarking, binding, bitrate, blackarmor, blockdev, blowfish, bochs, bond, bonding, booknotes, bootable, bsd, btrfs, buffer, c-states, cache, caching, ccl, centos, certificate, certtool, cgdisk, cheatsheet, chrome, chroot, cisco, clamav, cli, clp, clush, cluster, cmd, coleslaw, colorscheme, common lisp, configuration management, console, container, containers, controller, cron, cryptsetup, csync2, cu, cups, cygwin, d-states, database, date, db2, dcfldd, dcim, dd, debian, debug, debugger, debugging, decimal, desktop, df, dhclient, dhcp, diff, dig, display manager, dm-crypt, dmesg, dmidecode, dns, docker, dos, drivers, dtrace, dtrace4linux, du, dynamictracing, e2fsck, eBPF, ebook, efi, egrep, emacs, encoding, env, error, ess, esx, esxcli, esxi, ethtool, evil, expect, exportfs, factory reset, factory_reset, factoryreset, fail2ban, fakeroot, fbsd, fdisk, fedora, file, files, filesystem, find, fio, firewall, firmware, fish, flashrom, forensics, free, freebsd, freedos, fritzbox, fsck, fstrim, ftp, ftps, g-states, gentoo, ghostscript, git, git-filter-branch, gitbucket, github, gitolite, global, gnutls, gradle, grep, grml, grub, grub2, guacamole, hardware, haskell, hdd, hdparm, hellowor, hex, hexdump, history, howto, htop, htpasswd, http, httpd, https, i3, icmp, ifenslave, iftop, iis, imagemagick, imap, imaps, init, innoDB, innodb, inodes, intel, ioncube, ios, iostat, ip, iperf, iphone, ipmi, ipmitool, iproute2, ipsec, iptables, ipv6, irc, irssi, iw, iwconfig, iwlist, iwlwifi, jailbreak, jails, java, javascript, javaws, js, juniper, junit, kali, kde, kemp, kernel, keyremap, kill, kpartx, krypton, lacp, lamp, languages, ldap, ldapsearch, less, leviathan, liero, lightning, links, linux, linuxin3months, lisp, list, livedisk, lmctfy, loadbalancing, locale, log, logrotate, looback, loopback, losetup, lsblk, lsi, lsof, lsusb, lsyncd, luks, lvextend, lvm, lvm2, lvreduce, lxc, lxde, macbook, macro, magento, mailclient, mailing, mailq, make-jpkg, manpages, markdown, mbr, mdadm, megacli, micro sd, microsoft, minicom, mkfs, mktemp, mod_pagespeed, mod_proxy, modbus, modprobe, mount, mouse, movement, mpstat, multitasking, myISAM, mysql, mysql 5.7, mysql workbench, mysqlcheck, mysqldump, nagios, nas, nat, nc, netfilter, networking, nfs, nginx, nmap, nocaps, nodejs, numberingsystem, numbers, od, onyx, opcode-cache, openVZ, openlierox, openssl, openvpn, openvswitch, openwrt, oracle linux, org-mode, os, oscilloscope, overview, parallel, parameter expansion, parted, partitioning, passwd, patch, pct, pdf, performance, pfsense, php, php7, phpmyadmin, pi, pidgin, pidstat, pins, pkill, plasma, plesk, plugin, posix, postfix, postfixadmin, postgres, postgresql, poudriere, powershell, preview, profiling, prompt, proxmox, ps, puppet, pv, pveam, pvecm, pvesm, pvresize, python, python3, qemu, qemu-img, qm, qmrestore, quicklisp, quickshare, r, racktables, raid, raspberry pi, raspberrypi, raspbian, rbpi, rdp, redhat, redirect, registry, requirements, resize2fs, rewrite, rewrites, rhel, rigol, roccat, routing, rs0485, rs232, rsync, s-states, s_client, samba, sar, sata, sbcl, scite, scp, screen, scripting, seafile, seagate, security, sed, serial, serial port, setup, sftp, sg300, shell, shopware, shortcuts, showmount, signals, slattach, slip, slow-query-log, smbclient, snmpget, snmpwalk, software RAID, software raid, softwareraid, sophos, spacemacs, spam, specification, speedport, spi, sqlite, squid, ssd, ssh, ssh-add, sshd, ssl, stats, storage, strace, stronswan, su, submodules, subzone, sudo, sudoers, sup, swaks, swap, switch, switching, synaptics, synergy, sysfs, systemd, systemtap, tar, tcpdump, tcsh, tee, telnet, terminal, terminator, testdisk, testing, throughput, tmux, todo, tomcat, top, tput, trafficshaping, ttl, tuning, tunnel, tunneling, typo3, uboot, ubuntu, ubuntu 16.04, ubuntu16.04, udev, uefi, ulimit, uname, unetbootin, unit testing, upstart, uptime, usb, usbstick, utf8, utm, utm 220, ux305, vcs, vgchange, vim, vimdiff, virtualbox, virtualization, visual studio code, vlan, vmstat, vmware, vnc, vncviewer, voltage, vpn, vsphere, vzdump, w, w701, wakeonlan, wargames, web, webdav, weechat, wget, whois, wicd, wifi, windowmanager, windows, wine, wireshark, wpa, wpa_passphrase, wpa_supplicant, x11vnc, x2x, xfce, xfreerdp, xmodem, xterm, xxd, yum, zones, zsh


Unless otherwise credited all material Creative Commons License by sjas