Posts tagged systemd

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

systemd: custom init script from scratch.

posted on 2015-06-29 09:35:19

This suffices to start a custom script as a system service in the background as a non-root-user:

[Unit]
Description=My service. Change This! :)
After=syslog.target network.target

[Service]
Type=simple
User=etherpad
ExecStart=<path to my application or shellscript, change me :)>

[Install]
WantedBy=multi-user.target

This is located at /etc/systemd/system/my-custom.service

Then system restart my-custom will work. Which is actually way easier than in the past. Also it happened to work better, out of the box. \ o /

systemd cheat sheet

posted on 2015-01-16 22:54:15

SYSVINIT COMMAND                    SYSTEMD COMMAND


Used to start a service (not reboot persistent)
service <daemon> start               systemctl start <daemon>


Used to stop a service (not reboot persistent)
service <daemon> stop                systemctl stop <daemon>


Used to stop and then start a service
service <daemon> restart             systemctl restart <daemon>


When supported, reloads the config file without interrupting pending operations.
service <daemon> reload              systemctl reload <daemon>


Restarts if the service is already running.
service <daemon> condrestart         systemctl condrestart <daemon>


Tells whether a service is currently running.
service <daemon> status              systemctl status <daemon>


Used to list the services that can be started or stopped
Used to list all the services and other units
ls /etc/rc.d/init.d/                systemctl 
                                    systemctl list-unit-files --type=service
                                    ls /lib/systemd/system/*.service /etc/systemd/system/*.service


Turn the service on, for start at next boot, or other trigger.
chkconfig <daemon> on                systemctl enable <daemon>


Turn the service off for the next reboot, or any other trigger.
chkconfig <daemon> off               systemctl disable <daemon>


Used to check whether a service is configured to start or not in the current environment.
chkconfig <daemon>                   systemctl is-enabled <daemon>


Print a table of services that lists which runlevels each is configured on or off
chkconfig --list                    systemctl list-unit-files --type=service 
                                    ls /etc/systemd/system/*.wants/


Used to list what levels this service is configured on or off
chkconfig <daemon> --list            ls /etc/systemd/system/*.wants/<daemon>.service


Used when you create a new service file or modify any configuration
chkconfig <daemon> --add             systemctl daemon-reload

To be fair, this is just ripped from the fedora manual and I reformatted it a bit.

Another gem might be:

systemd-analyze blame

This will tell you the times the assorted programs needed during booting

This blog covers .csv, .htaccess, .pfx, .vmx, /etc/crypttab, /etc/network/interfaces, /etc/sudoers, /proc, 10.04, 14.04, AS, ASA, ControlPanel, DS1054Z, GPT, HWR, Hyper-V, IPSEC, KVM, LSI, LVM, LXC, MBR, MTU, MegaCli, PHP, PKI, R, RAID, S.M.A.R.T., SNMP, SSD, SSL, TLS, TRIM, VEEAM, VMware, VServer, VirtualBox, Virtuozzo, XenServer, acpi, adaptec, algorithm, ansible, apache, 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, 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, fbsd, fdisk, fedora, file, filesystem, find, fio, firewall, firmware, fish, flashrom, forensics, free, freebsd, freedos, fritzbox, fsck, fstrim, ftp, ftps, g-states, gentoo, ghostscript, git, git-filter-branch, 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, 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, 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, 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