know-how:firewall
Inhaltsverzeichnis
Features
- ipsets basierend auf zB: Hostnamen d.h. iptables Freigaben oder Blocks können auf Domain bzw. Hostnamen Ebene durchgeführt werden im Unterschied zu „nativem“ iptables
- ipsets basierend auf CIDR Netznotationen
- ipsets basierend auf Einzel IPs
- Implementierung von http://iplists.firehol.org/ basierend auf ihrem bash Skript (https://github.com/firehol/blocklist-ipsets)
- Pi-Hole Minimal für Blacklists pihole-minimal.tar
Voraussetzungen
- Minimale Requirements mit update-ipsets.tar auf jeden Fall wird iprange benötigt
- Für /usr/share/netfilter-persistent/plugins.d# iptables-scripts.zip , Originalmodule löschen
- dnsmasq zum aktualisieren von den Domain/Hostname basierenden IP Sets
- zB: auf Debian Stretch:
apt-get install ipset netfilter-persistent iptables iptables-persistent dnsmasq
Anpassungen
Verzeichnisse u. Dateien
- Grundsätzlicher Aufbau
root@mrBox-x:/etc/iptables# ls -al /etc/iptables/ total 60 drwxr-x--- 5 root root 4096 Sep 29 11:42 . drwxr-xr-x 91 root root 4096 Nov 22 10:08 .. drwxr-x--- 2 root root 4096 Dec 8 2017 ipset-dns.v4 drwxr-x--- 2 root root 4096 Sep 29 11:15 ipset-ips.v4 drwxr-x--- 2 root root 4096 Sep 29 11:28 ipset-networks.v4 -rw-r----- 1 root root 9291 Sep 29 11:42 rules-new.v4 -rw-r----- 1 root root 6353 Dec 8 2017 rules-new.v6 -rw-r----- 1 root root 9291 Sep 29 11:43 rules.v4 -rw-r----- 1 root root 6353 Dec 8 2017 rules.v6 root@mrBox-x:~# ls -al /usr/share/netfilter-persistent/plugins.d/ total 16 drwxr-xr-x 2 root root 4096 Nov 22 10:19 . drwxr-xr-x 3 root root 4096 Mar 24 2016 .. -rwx------ 1 root root 3902 Sep 29 11:31 40-ip4tables -rwx------ 1 root root 2078 Mar 18 2017 60-ip6tables root@mrBox-x:~# ls -al /usr/local/sbin/update-ipsets/ total 324 drwxr-sr-x 2 root staff 4096 Sep 29 11:29 . drwxrwsr-x 3 root staff 4096 Sep 29 11:26 .. -rw-r--r-- 1 root staff 70 May 2 2018 commands.txt -rw-r--r-- 1 root staff 2095 May 2 2018 functions.common -rw-r--r-- 1 root staff 2346 May 2 2018 install.config -rwxr--r-- 1 root staff 310196 May 2 2018 update-ipsets.sh root@mrBox-x:/etc/cron.d# cat update-ipset SHELL=/bin/bash PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games */15 * * * * root /usr/local/sbin/update-ipsets/update-ipsets.sh --silent &> /dev/null
- Firewall IPv4 Beispiel
:
# Generated by iptables-save v1.4.12 on Mon Oct 14 15:11:00 2013 *raw :PREROUTING ACCEPT [60:6158] :OUTPUT ACCEPT [0:0] -A PREROUTING -i eth0 -s 10.0.0.0/8 -j RETURN -A PREROUTING -i eth0 -s 192.168.0.0/16 -j RETURN -A PREROUTING -i eth0 -s 172.16.0.0/12 -j RETURN -A PREROUTING -i eth0 -m set --match-set firehol_level1 src -m limit --limit 5/sec -j LOG --log-prefix "fw firehol_level1 DROP: " --log-level 7 -A PREROUTING -i eth0 -m set --match-set firehol_level1 src -j DROP -A PREROUTING -i eth0 -m set --match-set firehol_level2 src -m limit --limit 5/sec -j LOG --log-prefix "fw firehol_level2 DROP: " --log-level 7 -A PREROUTING -i eth0 -m set --match-set firehol_level2 src -j DROP COMMIT *nat :PREROUTING ACCEPT [1:84] :INPUT ACCEPT [1:84] :OUTPUT ACCEPT [0:0] :POSTROUTING ACCEPT [0:0] -A PREROUTING ! -d 192.168.1.1/32 -i br0 -p udp --dport 53 -m limit --limit 5/sec -j LOG --log-prefix "fw DNS REDIRECT: " --log-level 7 -A PREROUTING ! -d 192.168.1.1/32 -i br0 -p udp --dport 53 -j REDIRECT --to 53 -A PREROUTING ! -d 192.168.1.1/32 -i br0 -p tcp -m tcp --dport 53 -m limit --limit 5/sec -j LOG --log-prefix "fw DNS REDIRECT: " --log-level 7 -A PREROUTING ! -d 192.168.1.1/32 -i br0 -p tcp -m tcp --dport 53 -j REDIRECT --to 53 -A PREROUTING ! -d 192.168.1.1/32 -i br0 -p tcp -m tcp --dport 80 -m limit --limit 5/sec -j LOG --log-prefix "fw HTTP REDIRECT: " --log-level 7 -A PREROUTING ! -d 192.168.1.1/32 -i br0 -p tcp -m tcp --dport 80 -j REDIRECT --to-ports 8081 -A POSTROUTING -o eth0 -j MASQUERADE COMMIT # Completed on Mon Oct 14 15:11:00 2013 # Generated by iptables-save v1.4.12 on Mon Oct 14 15:11:00 2013 *mangle :PREROUTING ACCEPT [348:36659] :INPUT ACCEPT [348:36659] :FORWARD ACCEPT [0:0] :OUTPUT ACCEPT [252:78891] :POSTROUTING ACCEPT [252:78891] COMMIT # Completed on Mon Oct 14 15:11:00 2013 # Generated by iptables-save v1.4.12 on Mon Oct 14 15:11:00 2013 *filter :INPUT DROP [0:0] :FORWARD DROP [0:0] :OUTPUT DROP [0:0] :ALLOW - [0:0] :EXT-FW - [0:0] :EXT-INT - [0:0] :FW-EXT - [0:0] :FW-INT - [0:0] :GARBAGE - [0:0] :INT-EXT - [0:0] :INT-FW - [0:0] -A INPUT -i lo -j ACCEPT -A INPUT -i eth0 -j EXT-FW -A INPUT -i br0 -j INT-FW -A INPUT -j GARBAGE -A INPUT -m limit --limit 5/sec -j LOG --log-prefix "fw INPUT DROP: " --log-level 7 -A INPUT -j DROP -A FORWARD -i br0 -o eth0 -j INT-EXT -A FORWARD -i eth0 -o br0 -j EXT-INT -A FORWARD -j GARBAGE -A FORWARD -m limit --limit 5/sec -j LOG --log-prefix "fw FORWARD DROP: " --log-level 7 -A FORWARD -j DROP -A OUTPUT -o lo -j ACCEPT -A OUTPUT -o eth0 -j FW-EXT -A OUTPUT -o br0 -j FW-INT -A OUTPUT -j GARBAGE -A OUTPUT -m limit --limit 5/sec -j LOG --log-prefix "fw OUTPUT DROP: " --log-level 7 -A OUTPUT -j DROP -A ALLOW -m limit --limit 5/sec -j LOG --log-prefix "fw ALLOW ACCEPT: " --log-level 7 -A ALLOW -j ACCEPT -A EXT-FW -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT -A EXT-FW -p icmp -m icmp --icmp-type 8 -j ALLOW -A EXT-FW -j GARBAGE -A EXT-FW -m limit --limit 5/sec -j LOG --log-prefix "fw EXT-FW DROP: " --log-level 7 -A EXT-FW -j DROP -A EXT-INT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT -A EXT-INT -j GARBAGE -A EXT-INT -m limit --limit 5/sec -j LOG --log-prefix "fw EXT-INT DROP: " --log-level 7 -A EXT-INT -j DROP -A FW-EXT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT -A FW-EXT -p tcp -m tcp --dport 80 --tcp-flags FIN,SYN,RST,ACK SYN -j ALLOW -A FW-EXT -p tcp -m tcp --dport 443 --tcp-flags FIN,SYN,RST,ACK SYN -j ALLOW -A FW-EXT -p icmp -m icmp --icmp-type 8 -j ALLOW -A FW-EXT -p udp -m udp --dport 67 -j ALLOW -A FW-EXT -p tcp -m tcp --dport 587 --tcp-flags FIN,SYN,RST,ACK SYN -j ALLOW -A FW-EXT -p udp -m udp --dport 123 -j ALLOW -A FW-EXT -p udp -m udp --dport 53 -j ALLOW -A FW-EXT -p tcp -m tcp --dport 53 --tcp-flags FIN,SYN,RST,ACK SYN -j ALLOW -A FW-EXT -p udp -m udp --dport 65194 -j ALLOW -A FW-EXT -m owner --uid-owner proxy -j ALLOW -A FW-EXT -j GARBAGE -A FW-EXT -m limit --limit 5/sec -j LOG --log-prefix "fw FW-EXT DROP: " --log-level 7 -A FW-EXT -j DROP -A FW-INT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT -A FW-INT -p udp -m udp --dport 68 -j ALLOW -A FW-INT -p icmp -m icmp --icmp-type 8 -j ALLOW -A FW-INT -j GARBAGE -A FW-INT -m limit --limit 5/sec -j LOG --log-prefix "fw FW-INT DROP: " --log-level 7 -A FW-INT -j DROP -A GARBAGE -d 224.0.0.1/32 -j DROP -A GARBAGE -d 255.255.255.255/32 -j DROP -A GARBAGE -d 224.0.0.251/32 -j DROP -A GARBAGE -p udp -m udp --dport 137 -j DROP -A GARBAGE -p udp -m udp --dport 138 -j DROP -A INT-EXT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT -A INT-EXT -p tcp --syn --dport 465 -j ALLOW -A INT-EXT -p tcp --syn --dport 587 -j ALLOW -A INT-EXT -p tcp --syn --dport 993 -j ALLOW -A INT-EXT -p tcp --syn --dport 995 -j ALLOW -A INT-EXT -p icmp -m icmp --icmp-type 8 -j ALLOW -A INT-EXT -m limit --limit 5/sec -j LOG --log-prefix "fw INT-EXT DROP: " --log-level 7 -A INT-EXT -j DROP -A INT-FW -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT -A INT-FW -p tcp -m tcp --dport 8080 --tcp-flags FIN,SYN,RST,ACK SYN -j ALLOW -A INT-FW -p tcp -m tcp --dport 8081 --tcp-flags FIN,SYN,RST,ACK SYN -j ALLOW -A INT-FW -p tcp -m tcp --dport 53 --tcp-flags FIN,SYN,RST,ACK SYN -j ALLOW -A INT-FW -p tcp -m tcp --dport 80 --tcp-flags FIN,SYN,RST,ACK SYN -j ALLOW -A INT-FW -p tcp -m tcp --dport 22 --tcp-flags FIN,SYN,RST,ACK SYN -j ALLOW -A INT-FW -p udp -m udp --dport 53 -j ALLOW -A INT-FW -p udp -m udp --dport 67 -j ALLOW -A INT-FW -p icmp -m icmp --icmp-type 8 -j ALLOW -A INT-FW -p udp -m udp --dport 123 -j ALLOW -A INT-FW -j GARBAGE -A INT-FW -m limit --limit 5/sec -j LOG --log-prefix "fw INT-FW DROP: " --log-level 7 -A INT-FW -j DROP COMMIT # Completed on Mon Oct 14 15:11:00 2013
Backup Leitung
- Wenn der primäre Link offline geht wechsel zum Sekundären
- Wenn der primäre Link offline war und „zurück“ kommt wechsel wieder zum Primären
- Wenn der primäre Link funktioniert gibt es keine Änderungen
- /usr/local/sbin/check_wan_links.sh
#!/bin/bash
# Requirements:
# IF primary link is down switch to secondary link if not already active
# IF primary link is down and comes back switch to primary link
# IF primary link is active and working do nothing
PRIMARY_IP="82.149.97.213"
SECONDARY_IP="192.168.29.2"
PRIMARY_GATEWAY="82.149.97.1"
SECONDARY_GATEWAY="192.168.29.1"
function checkLink()
{
returnCode="1"
/bin/ping -q -c 5 -I $1 8.8.8.8 >/dev/null || /bin/ping -q -c 5 -I $1 1.1.1.1 >/dev/null || /bin/ping -q -c 5 -I $1 9.9.9.9 >/dev/null || returnCode="0"
echo $returnCode
}
function checkCurrentGateway()
{
default=$(/sbin/ip route get 8.8.8.8 | awk '{print $3}')
echo $default
}
function setCurrentGateway()
{
/sbin/ip route change default via $1
echo "Default route changed to: $1"
}
linkPrimary=$(checkLink $PRIMARY_IP);
currentGateway=$(checkCurrentGateway);
#echo "Link Primary: $linkPrimary"
#echo "Current Gateway: $currentGateway"
[[ $linkPrimary == "0" && $currentGateway == $PRIMARY_GATEWAY ]] && setCurrentGateway $SECONDARY_GATEWAY
[[ $linkPrimary == "1" && $currentGateway == $SECONDARY_GATEWAY ]] && setCurrentGateway $PRIMARY_GATEWAY
exit 0
- Routing zB: /etc/network/interfaces
#DREI Huawei Modem
auto bond0.29
iface bond0.29 inet static
up ip route add 192.168.29.0/24 dev bond0.29 table lte
up ip route add default via 192.168.29.1 table lte
up ip rule add from 192.168.92.2 lookup lte
address 192.168.29.2
netmask 255.255.255.0
#EXT - kabelsignal AG
auto eth2
iface eth2 inet static
address 82.149.97.213
netmask 255.255.255.0
gateway 82.149.97.1
up ip route add 82.149.97.0/24 dev eth2 table kabsi
up ip route add default via 82.149.97.1 table kabsi
up ip rule add from 82.149.97.213 lookup kabsi
Gäste WLAN
- Gäste WLAN , das innerhalb der vorhandenen LAN Infrastruktur durchgereicht werden kann ohne komplexe VLAN Taggings
- In Kombination mit zB: openwrt und openvpn möglich + Linux Firewall
Firewall Konfiguration
- Wir benötigen eine Bridge und OpenVPN
- Verschlüsselung ist nicht notwendig ausschließlich Authentifizierung
- DNSMASQ dient als DHCP Server
- /etc/dnsmasq.conf
.. dhcp-range=set:wlan,10.0.212.100,10.0.212.200,255.255.255.0,4h dhcp-option=tag:wlan,6,8.8.8.8,8.8.4.4 dhcp-option=tag:wlan,3,10.0.212.1 ..
- /etc/network/interfaces
...
#WLAN Guest Interface
auto br-guest
iface br-guest inet manual
pre-up brctl addbr br-guest
pre-up brctl stp br-guest off
pre-up brctl setfd br-guest 0
pre-up ip addr add 10.0.212.1/24 brd + dev br-guest
pre-up ip li set dev br-guest up
...
- /etc/openvpn/wlan-guest.conf
dev tap0 dev-type tap port 65190 proto udp mode server management 127.0.0.1 222 cd /etc/openvpn/wlan-guest cipher none server 172.24.240.0 255.255.255.0 dh dh2048.pem ca ca.crt cert firewall.crt key firewall.key status status.log client-config-dir ccd topology subnet tls-server keepalive 5 15 verb 3 multihome script-security 2 up /etc/openvpn/wlan-guest/add_tap.sh multihome
- /etc/openvpn/wlan-guest/add_tap.sh
#!/bin/bash brctl addif br-guest tap0
Access Point Konfiguration
- /etc/config/network
- Achtung in diesem Fall 2 VLANs die das interne und Gästenetz aufteilen auf entsprechende Ports ( in diesem Fall 841n TP-Link)
config interface 'loopback'
option ifname 'lo'
option proto 'static'
option ipaddr '127.0.0.1'
option netmask '255.0.0.0'
config interface 'guest'
option ifname 'eth1.2'
option type 'bridge'
config interface 'intern'
option ifname 'eth0 eth1.3'
option proto 'dhcp'
option type 'bridge'
config switch
option name 'switch0'
option reset '1'
option enable_vlan '1'
config switch_vlan
option device 'switch0'
option vlan '3'
option ports '0t 2 3'
config switch_vlan
option device 'switch0'
option vlan '2'
option ports '0t 1 4'
- /etc/config/wireless
config wifi-device radio0
option type mac80211
option channel auto
option hwmode 11g
option path 'platform/ar934x_wmac'
option htmode HT20
list ht_capab LDPC
list ht_capab SHORT-GI-20
list ht_capab SHORT-GI-40
list ht_capab TX-STBC
list ht_capab RX-STBC1
list ht_capab DSSS_CCK-40
# REMOVE THIS LINE TO ENABLE WIFI:
option disabled 0
config wifi-iface
option device radio0
option network guest
option mode ap
option ssid SSID_GASTNETZWERK
option encryption psk2
option key PSK_GASTNETZWERK
- /etc/openvpn/client.conf
client
dev tap-guest
dev-type tap
cipher none
proto udp
remote firewall 65190
keepalive 5 10
resolv-retry infinite
script-security 2
up /etc/openvpn/client/add_tap.sh
nobind
ca /etc/openvpn/client/ca.crt
cert /etc/openvpn/client/wlanx.crt
key /etc/openvpn/client/wlanx.key
ns-cert-type server
verb 3
- /etc/openvpn/client/add_tap.sh
#!/bin/sh brctl addif br-guest tap-guest
all stations detection
- Richtig oldschool , aber dennoch gut zu wissen , bei Arpspoofing gibt es Flip Flop Meldungen :)
- Getestet mit Debian 12 - apt-get install arpwatch
- Konfiguration unter - /etc/arpwatch
- Folgendes interface möchte ich überwachen: br-buero d.h. File anlegen → br-buero.iface / per Default schickt er die Nachrichten ohnehin an root d.h. es ist in dem Fall überbestimmt - postfix sorgt daann dafür dass ich die Mails die an root gehen bekomme / DB wird unter /var/lib/arpwatch abgelegt
root@mrGatekeeper:/etc/arpwatch# ls
README
br-buero.iface
root@mrGatekeeper:/etc/arpwatch# cat br-buero.iface
IFACE_ARGS="-m root"
root@mrGatekeeper:/etc/arpwatch# systemctl start arpwatch@br-buero
root@mrGatekeeper:/etc/arpwatch# systemctl enable arpwatch@br-buero
root@mrGatekeeper:/etc/arpwatch# systemctl status arpwatch@br-buero
● arpwatch@br-buero.service - arpwatch service on interface br/buero
Loaded: loaded (/lib/systemd/system/arpwatch@.service; enabled; preset: enabled)
Active: active (running) since Mon 2025-09-08 14:22:42 CEST; 2 days ago
Docs: man:arpwatch(8)
Process: 2429251 ExecStartPre=/usr/bin/touch -a br-buero.dat (code=exited, status=0/SUCCESS)
Process: 2429259 ExecStartPre=/bin/chown $RUNAS br-buero.dat (code=exited, status=0/SUCCESS)
Process: 2429265 ExecStart=/usr/sbin/arpwatch -u $RUNAS -i br-buero -f br-buero.dat $ARGS $IFACE_ARGS -F ${PCAP_FILTER} (code=exited, status=0/SUCCESS)
Main PID: 2429272 (arpwatch)
Tasks: 1 (limit: 38242)
Memory: 480.0K
CPU: 1.373s
CGroup: /system.slice/system-arpwatch.slice/arpwatch@br-buero.service
└─2429272 /usr/sbin/arpwatch -u arpwatch -i br-buero -f br-buero.dat -N -p -m root -F
Notice: journal has been rotated since unit was started, output may be incomplete.
root@mrGatekeeper:/var/lib/arpwatch# ls br-buero.dat
br-buero.dat
rogue client workstation detection
- Getestet mit Debian 9 - apt-get install arpalert
- Es soll eine Mail an root geschickt werden wenn ein unbekannter Client dem System hinzugefügt wird und zusätzlich noch wenn möglich ein Port Scan auf den Client durchgeführt werden
- grep -v ^# /etc/arpalert/arpalert.conf
maclist file = "/etc/arpalert/maclist.allow" maclist alert file = "/etc/arpalert/maclist.deny" maclist leases file = "/var/lib/arpalert/arpalert.leases" lock file = "/var/run/arpalert.pid" use syslog = true log level = 7 user = arpalert umask = 177 dump packet = false daemon = false dump inter = 5 catch only arp = true interface = "eth1" action on detect = "/usr/local/sbin/notifyArpalert.sh" mod on detect = "" mod config = "" execution timeout = 10 max alert = 20 dump black list = false dump white list = false dump new address = true mac timeout = 1555200 expire authorized mac addresses = false max entry = 1000000 anti flood interval = 5 anti flood global = 50 mac vendor file = "/etc/arpalert/oui.txt" log mac vendor = true alert mac vendor = true mod mac vendor = true log referenced address = false alert on referenced address = false mod on referenced address = false log deny address = true alert on deny address = true mod on deny address = true log new address = true alert on new address = true mod on new address = true log new mac address = true alert on new mac address = true mod on new mac address = true log ip change = true alert on ip change = false mod on ip change = true log mac change = true alert on mac change = false mod on mac change = true log unauth request = true alert on unauth request = true mod on unauth request = true ignore unknown sender = false ignore me = true ignore self test = true unauth ignore time method = 2 log request abus = true alert on request abus = true mod on request abus = true max request = 1000000 log mac error = true alert on mac error = true mod on mac error = true log flood = true alert on flood = true mod on flood = true log expire mac address = false alert on expire mac address = false mod on expire mac address = false
- /usr/local/sbin/notifyArpalert.sh
#!/bin/bash tmp_file=$(mktemp) ip_address="$2" mac_address="$1" params="$3" ethernet_device="$4" alert_type="$5" echo "Possible Intrusion Attempt" > $tmp_file echo "IP Address: $ip_address" >> $tmp_file echo "MAC Address: $mac_address" >> $tmp_file echo "Parameters: $params" >> $tmp_file echo "Alert Type: $alert_type" >> $tmp_file alert_explained=$(cat << EOF Alert Types: \n 0: ip change \n 1: mac address only detected but not in whithe list \n 2: mac address in black list \n 3: new mac address \n 4: unauthorized arp request \n 5: abusive number of arp request detected \n 6: ethernet mac address different from arp mac address \n 7: global flood detection \n 8: new mac adress without ip \n 9: mac change \n 10: mac expire \n EOF) echo -e $alert_explained >> $tmp_file echo "Nmap Scan: " >> $tmp_file ip route get $ip_address | grep -q eth1 ( [[ $? == 0 ]] && nmap -Pn $ip_address >> $tmp_file ) || echo "I'm not performing nmap on $ip_address" >> $tmp_file cat $tmp_file | mail -s "Possible Break in Attempt " root rm $tmp_file
- /etc/arpalert/maclist.allow
#KOMMENTAR GERÄT1 11:22:33:44:55:66 IP_GERÄT1 INTERFACE_NETZWERK
rogue dhcp server detection
dhcp-probe
- BUG beim Socket WAIT ?? - im Debugging „wartet“ er für immer nach erster Runde
- Es sollen DHCP Server gefunden werden , die sich in der aktuellen Broadcast Domain befinden, die nicht autorisiert sind
- getestet auf Debian 9 mit apt-get install dhcp-probe
- löschen von dhcp-probe init Skript rm /etc/init.d/dhcp-probe
- Die Ausgabe wird nun geloggt über syslog mit Systemd
- Systemd Unit /lib/systemd/system/dhcp_probe\@.service
[Unit] Description=DHCP-Probe Instance %i After=network.target [Service] Type=simple ExecStart=/usr/sbin/dhcp_probe -f -d 11 -T %i #2020-08-12 cc: ExecStop not defined on purpose KillSignal=9 [Install] WantedBy=multi-user.target
- Für interface eth1:
- ln -s /lib/systemd/system/dhcp_probe\@.service /etc/systemd/system/multi-user.target.wants/dhcp_probe\@eth1.service
- /etc/dhcp_probe.cf
legal_server IP_DHCP_SERVER1 legal_server IP_DHCP_SERVER2 alert_program_name2 /usr/local/sbin/notifyDHCP.sh response_wait_time 10000
- /usr/local/sbin/notifyDHCP.sh
#!/bin/bash
tmp_file=$(mktemp)
# -I the name of the interface on which the unexpected response packet was received
# -i the IP source address of the packet
# -m Ethernet source address of the packet
ip_address="NONE"
mac_address="NONE"
ethernet_device="NONE"
program_id="NONE"
while getopts ":I:i:m:p:" arg; do
case "$arg" in
I)
ethernet_device=$OPTARG
;;
i)
ip_address=$OPTARG
;;
m)
mac_address=$OPTARG
;;
p)
program_id=$OPTARG
;;
*)
;;
esac
done
echo "Possible Rogue DHCP Server" > $tmp_file
echo "IP Address: $ip_address" >> $tmp_file
echo "MAC Address: $mac_address" >> $tmp_file
echo "Ethernet Device: $ethernet_device" >> $tmp_file
echo "Nmap Scan: " >> $tmp_file
ip route get $ip_address | grep -q eth1
( [[ $? == 0 ]] && nmap -Pn $ip_address >> $tmp_file ) || echo "I'm not performing nmap on $ip_address" >> $tmp_file
cat $tmp_file | mail -s "POSSIBLE rogue DHCP SERVER " root
rm $tmp_file
dhclient Skript
- Getestet unter Debian 9
- Wir lassen den offiziellen DHCP Client dhclient eine Lease über das Interface %i zb. eth1 holen und triggern sobald er die IP setzen sollte /usr/local/sbin/triggerDHCPLease.sh Das Renewal setzen wir auf 300 Sekunden /usr/local/sbin/triggerDHCPLease.sh - Wenn die lease von einem DHCP Server kommt , den wir nicht whitelisted haben rufe notfiyDHCP.sh auf scanne ggf. die IP mit nmap und sende ein Mail an root
- apt-get install isc-dhcp-client
- Systemd Service cat /lib/systemd/system/dhcp-monitoring\@.service
[Unit] Description=DHCP-Monitoring Instance %i After=network.target [Service] Type=simple ExecStart=/sbin/dhclient -v -d -sf /usr/local/sbin/triggerDHCPLease.sh -cf /usr/local/etc/dhcp-monitoring/dhclient.conf -lf /dev/zero %i #2020-08-12 cc: ExecStop not defined on purpose KillSignal=9 [Install] WantedBy=multi-user.target
- Für Netzwerinterface eth1 starten
- ln -s /lib/systemd/system/dhcp-monitoring\@.service /etc/systemd/system/multi-user.target.wants/dhcp-monitoring\@eth1.service
ls -al /etc/systemd/system/multi-user.target.wants/dhcp-monitoring\@eth1.service lrwxrwxrwx 1 root root 44 Aug 12 13:35 /etc/systemd/system/multi-user.target.wants/dhcp-monitoring@eth1.service -> /lib/systemd/system/dhcp-monitoring@.service
- /usr/local/sbin/triggerDHCPLease.sh
#!/bin/bash
WHITELISTED_DHCP_SERVERS="^(IP_DHCP_SERVER_1|IP_DHCP_SERVER2)$"
#2020-08-12 cc: will be triggered from dhclient therefore certain variables have to exist
#Variable new_dhcp_server_identifier must be present
function bailout
{
echo -e "$1"
exit 2
}
[[ -v new_dhcp_server_identifier ]] || bailout "new_dhcp_server_identifier is not set - called by dhclient ? "
echo $new_dhcp_server_identifier | grep -q -P "$WHITELISTED_DHCP_SERVERS"
grepReturn=$?
if [ $grepReturn != "0" ]
then
/usr/local/sbin/notifyDHCP.sh -i $new_dhcp_server_identifier
fi
exit 0
- /usr/local/etc/dhcp-monitoring/dhclient.conf
# man page for more information about the syntax of this file
# and a more comprehensive list of the parameters understood by
# dhclient.
#
# Normally, if the DHCP server provides reasonable information and does
# not leave anything out (like the domain name, for example), then
# few changes must be made to this file, if any.
#
option rfc3442-classless-static-routes code 121 = array of unsigned integer 8;
send host-name = gethostname();
request subnet-mask, broadcast-address, time-offset, routers,
domain-name, domain-name-servers, domain-search, host-name,
dhcp6.name-servers, dhcp6.domain-search, dhcp6.fqdn, dhcp6.sntp-servers,
netbios-name-servers, netbios-scope, interface-mtu,
rfc3442-classless-static-routes, ntp-servers;
supersede dhcp-rebinding-time 300;
supersede dhcp-lease-time 300;
supersede dhcp-renewal-time 300;
VPN
roadworker mfa - multiple factor auth
- Bei OpenVPN mit entsprechender Konfiguration wäre sie implizit gegeben wenn zB: ein Zertifikat zur Authentifizierung benutzt wird + Username + Password
- OpenVPN Server - roadworker-auth.conf:
... auth-user-pass-verify /etc/openvpn/roadworker-auth/hybrid_auth.sh via-env script-security 3 ...
- /etc/openvpn/roadworker-auth/hybrid_auth.sh
#!/bin/bash
function bailout ()
{
echo $1
exit 1
}
export username
export password
#env > /tmp/debug
#echo "u: -$AUTH_USERNAME-" >> /tmp/debug
#echo "p: -$AUTH_PASSWORD-" >> /tmp/debug
ORIGINAL_PASSWORD="$password"
AUTH_TOTP_SECRET="/etc/openvpn/roadworker-auth/totp/$username"
echo $username | grep -P -q "^[A-Za-z0-9\.]+$"
#2021-09-21 cc: Somehow malformed
[[ $? != 0 ]] && bailout "Username malformed"
[[ -f $AUTH_TOTP_SECRET && ${#password} -lt 7 ]] && bailout "TOTP is used but password is too small"
#2021-09-21 cc: The last 6 digits contain the TOTP string / the rest is the password
[[ -f $AUTH_TOTP_SECRET ]] && password=$(echo ${ORIGINAL_PASSWORD::-6})
/etc/openvpn/roadworker-auth/smb_auth.sh
RET_SMB_AUTH=$?
[[ ! -f $AUTH_TOTP_SECRET ]] && exit $?
#echo "smb auth: $RET_SMB_AUTH" > /tmp/smb_auth
[[ $RET_SMB_AUTH != 0 ]] && bailout "SMB Auth invalid"
password=$(echo ${ORIGINAL_PASSWORD: -6})
/etc/openvpn/roadworker-auth/totp_auth.sh
exit $?
- /etc/openvpn/roadworker-auth/smb_auth.sh
- Gültiger Account check via smb
check username
AUTH_USERNAME="$username" AUTH_PASSWORD="$password" AUTH_SERVER="SERVER_AUTH" [[ $AUTH_USERNAME == "" || $AUTH_USERNAME == " " ]] && AUTH_USERNAME="---" [[ $AUTH_PASSWORD == "" || $AUTH_USERNAME == " " ]] && AUTH_PASSWORD="---" #env > /tmp/debug #echo "u: -$AUTH_USERNAME-" >> /tmp/debug_smb #echo "p: -$AUTH_PASSWORD-" >> /tmp/debug_smb echo $AUTH_PASSWORD | /usr/bin/smbclient -mSMB3 --ip-address=$AUTH_SERVER --list=$AUTH_SERVER --user=$AUTH_USERNAME --timeout=5 &> /dev/null exit $?
- /etc/openvpn/roadworker-auth/totp_auth.sh
- TOTP Check mit oathtool
#!/bin/bash
function bailout ()
{
echo $1
exit 1
}
AUTH_USERNAME="$username"
AUTH_PASSWORD="$password"
AUTH_TOTP_SECRET="/etc/openvpn/roadworker-auth/totp/$AUTH_USERNAME"
[[ $AUTH_USERNAME == "" || $AUTH_USERNAME == " " ]] && AUTH_USERNAME="---"
[[ $AUTH_PASSWORD == "" || $AUTH_USERNAME == " " ]] && AUTH_PASSWORD="---"
echo $AUTH_USERNAME | grep -P -q "^[A-Za-z0-9\.]+$"
#2021-09-21 cc: Somehow malformed
[[ $? != 0 ]] && bailout "Username malformed"
#2021-09-21 cc: Somehow not 6 digits
echo $AUTH_PASSWORD | grep -P -q "^[0-9]{6}$"
[[ $? != 0 ]] && bailout "Digits malformed"
#2021-09-21 cc: This is tricky , if there's no secret file - it hasn't been created yet so auth succeeds
[[ ! -f $AUTH_TOTP_SECRET ]] && exit 0
TOTP_SEED=$(cat $AUTH_TOTP_SECRET)
DIGIT_CODE=$(oathtool -b --totp $TOTP_SEED)
#env > /tmp/debug
#echo "u: -$AUTH_USERNAME-" >> /tmp/debug
#echo "p: -$AUTH_PASSWORD-" >> /tmp/debug
#echo "c: -$DIGIT_CODE" >> /tmp/debug
[[ $DIGIT_CODE == $AUTH_PASSWORD ]] && exit 0
exit 1
- Um für bestimmten User TOTP zu aktivieren
pwgen -0 -s -1 16 > /etc/openvpn/roadworker-auth/totp/username
- Dieser TOTP Seed , der nun unter /etc/openvpn/roadworker-auth/totp/username zB: ABCABCBABCBCDFFG muss dem entsprechenden User sicher übermittelt werden zB: über Signal/Whatsapp - er kann ihn zB: im Google Authenticator als eigenen Eintrag hinzufügen
- Variante um bei bestehender zertifikatsbasierender Authentifizierung OTP zu aktivieren:
- für bestimmtes Gerät d.h. Zertifikat wird es obligatorisch und User können zum Zertifikat spezifiziert werden
- /etc/openvpn/roadworker-cert/roadworker-cert.conf
... auth-user-pass-verify /etc/openvpn/roadworker-cert/totp_auth.sh via-env auth-user-pass-optional script-security 3 ....
- /etc/openvpn/roadworker-cert/totp_auth.sh
#!/bin/bash
function bailout ()
{
echo $1
echo $1 | logger -t totp
exit 1
}
AUTH_USERNAME="$username"
AUTH_PASSWORD="$password"
AUTH_COMMON_NAME="$common_name"
AUTH_TOTP_ROOT_SECRET="/etc/openvpn/roadworker-cert/totp/"
AUTH_TOTP_SECRET="$AUTH_TOTP_ROOT_SECRET/$AUTH_COMMON_NAME/$AUTH_USERNAME"
#2021-10-14 cc: Certificate required
echo $common_name | grep -P -q "^[A-Za-z0-9\.\-]+$"
[[ $? != 0 ]] && bailout "Common certificate Name malformed"
#2021-10-14 cc: IF directory with common name does not exist OTP is not activated
[[ ! -d "$AUTH_TOTP_ROOT_SECRET/$AUTH_COMMON_NAME" ]] && exit 0
echo $AUTH_USERNAME | grep -P -q "^[A-Za-z0-9\.]+$"
#2021-09-21 cc: Somehow malformed
[[ $? != 0 ]] && bailout "Username malformed"
#2021-09-21 cc: Somehow not 6 digits
echo $AUTH_PASSWORD | grep -P -q "^[0-9]{6}$"
[[ $? != 0 ]] && bailout "Digits malformed"
#2021-09-21 cc: This is tricky , if there's no secret file - it has been created yet so auth succeeds
#2021-10-14 cc: If common_name root path exists there must be a file for the user
[[ ! -f $AUTH_TOTP_SECRET ]] && bailout "TOTP Secret not found - is needed"
TOTP_SEED=$(cat $AUTH_TOTP_SECRET)
DIGIT_CODE=$(oathtool -b --totp $TOTP_SEED)
#env > /tmp/debug
#echo "u: -$AUTH_USERNAME-" >> /tmp/debug
#echo "p: -$AUTH_PASSWORD-" >> /tmp/debug
#echo "c: -$DIGIT_CODE" >> /tmp/debug
[[ $DIGIT_CODE == $AUTH_PASSWORD ]] && exit 0
exit 1
roadworker openvpn wake on lan (wol) trigger
- zB: bei Roadworkern die per Remote Desktop auf ihre Bürorechner zugreifen möchten / Die Bürorechner können ruhig heruntergefahren werden / Sobald eine erfolgreiche authentifizierte Verbindung aufgebaut wurde wird wol für den Rechner getriggered
- /etc/openvpn/roadworker.conf (getestet auf Debian stretch)
... script-security 2 client-connect /usr/local/sbin/wake-on-vpn.sh ...
- /usr/local/sbin/wake-on-vpn.sh
#!/bin/bash case "$common_name" in COMMON_NAME_ROADWORKER) echo "Wake up Client associated with: $common_name" /usr/bin/wakeonlan -i IP_BROADCAST TARGET_MAC_ADDRESS | /usr/bin/logger -t roadworker ;; *) echo "No Client to wake up found: $common_name" | logger -t roadworker ;; esac exit 0
roadworker strongswan ipsec
Auth über radius server / Trigger bei strongswan für wake on lan
- Getestet auf: Ubuntu 18.04
- /etc/ipsec.conf
- Verbindungsparameter wurden speziell auf Windows Rechner ausgerichtet , damit IPSEC VPN im Windows automatisch funktioniert - Achtung bei Windows wird die Default Route ersetzt , muss sich um ein „Feature“ handeln egal ob bei leftsubnet nur das Zielnetz spezifiziert wird
- CA Zertifikat muss für den Computer Zertifikatsstore importiert worden sein und FQDN muss matchen bei Verbindungsaufbau mit zB: vpn.firewall.at
# ipsec.conf - strongSwan IPsec configuration file
config setup
#plutostart=no
conn %default
keyexchange=ikev2
ike=aes256-sha1-modp1024!
esp=aes256-sha1!
dpdaction=clear
dpddelay=300s
rekey=no
conn roadworker
left=%any
leftsubnet=0.0.0.0/0
leftauth=pubkey
leftcert=vpn.firewall.at.crt
leftid=@vpn.firweall.at
right=%any
rightsourceip=172.16.3.0/24
rightauth=eap-radius
eap_identity=%identity
rightsendcert=never
auto=add
leftupdown=/usr/local/sbin/wakeup.sh
- wake on lan (wol) bei erfolgreichem Login: /usr/local/sbin/wakeup.sh
#!/bin/bash #Debugging: env > /tmp/env_wakeup #PLUTO_XAUTH_ID=ACCOUNTNAME@DOMAIN /usr/sbin/etherwake -i eth1 -b -D MAC_ADDRESS exit 0
roadworker workstation/client
- Konfiguration mit Endung .ovpn
- OpenVPN Community Edition ist installiert
- Getestet wird immer mit unabhängiger Internetverbindung → Smartphone Hotspot
- Im Windows erscheint auch ein Fenster unten rechts wenn die Verbindung erfolgreich ist
- Schritte zum Importieren der Konfiguration und aufrufen der Verbindung:
unbound
- Rekursiver DNS Resolver der DNSSEC validiert und auch dns over tls unterstützt
troubleshoot
- Wenns immer wieder dnssec troubles gibt / und keiner aktiv DNS spoofing betreibt :)
1. Permissive mode
Does not actually turn off dnssec, but stops the resolver from withholding bogus answers from clients. Resolution may be slow due to validation failures but can still proceed. Add to the unbound.conf file:
server:
val-permissive-mode: yes
2. Remove trust anchors
If you remove the trust-anchor definitions from the unbound.conf file, DNSSEC is not used for those domains. Related options:
server:
# trust-anchor-file:
# auto-trust-anchor-file:
# trust-anchor:
# trusted-keys-file:
3. Disable the validator module
This also disables validation for other domains. In the unbound.conf file:
server:
module-config: "iterator"
4. Stop a broken chain of trust
To work around a broken chain of trust use a temporary item until the proper DS or DNSKEY records are published, put in the unbound.conf file:
server:
domain-insecure: "example"
internal dns zone
- zB: wenn intern ein AD Server benutzt wird für interne Domäne
server:
..
..
#2024-02-11 cc: if pannoniait.intern was used by a e.g. windows ad server
private-domain: pannoniait.intern
domain-insecure: pannoniait.intern
..
..
#2024-02-11 cc: If pannoniait.intern was used e.g. by windows ad server
forward-zone:
name: pannoniait.intern
forward-addr: IP_DNS_SERVER
dns over tls
- führt zu massiven DNS Performanceeinbruch
performance + prefetch usw.
server:
..
..
#2024-02-11 cc: The debian place where the bundle can be found
tls-cert-bundle: "/etc/ssl/certs/ca-certificates.crt"
..
..
forward-zone:
name: "."
forward-addr: 9.9.9.9@853#dns.quad9.net
forward-addr: 149.112.112.112@853#dns.quad9.net
forward-tls-upstream: yes
..
..
Traffic Shaping - tc
- PLAYGROUND - für bestimmten Traffic Bandbreite insgesamt einschränken , damit zB: ein Pool von Adressen eingeschränkt werden kann wie zB: Windows Updates :) entweder über iptables Markierungen oder über ipset Matches
#!/bin/sh -x
# Maximum allowed downlink. Set to 90% of the achievable downlink in mbit
DOWNLINK=60
# Interface facing the Internet
EXTDEV=wlp2s0
# Load IFB, all other modules all loaded automatically
modprobe ifb
ip link set dev ifb0 down
# Clear old queuing disciplines (qdisc) on the interfaces and the MANGLE table
tc qdisc del dev $EXTDEV root 2> /dev/null > /dev/null
tc qdisc del dev $EXTDEV ingress 2> /dev/null > /dev/null
tc qdisc del dev ifb0 root 2> /dev/null > /dev/null
tc qdisc del dev ifb0 ingress 2> /dev/null > /dev/null
iptables -t mangle -F
# appending "stop" (without quotes) after the name of the script stops here.
if [ "$1" = "stop" ]
then
echo "Shaping removed on $EXTDEV."
exit
fi
ip link set dev ifb0 up
# HTB classes on IFB with rate limiting - default class 3:30
tc qdisc add dev ifb0 root handle 3: htb default 30
tc class add dev ifb0 parent 3:3 classid 3:30 htb rate 60mbit ceil 60mbit
tc class add dev ifb0 parent 3:3 classid 3:33 htb rate 10mbit ceil 10mbit
# Packets marked with "2" on IFB flow through class 3:33
tc filter add dev ifb0 parent 3:0 protocol ip handle 2 fw flowid 3:33
# Martin Devera, author of HTB, then recommends SFQ for beneath these classes:
tc qdisc add dev ifb0 parent 3:30 handle 30: sfq perturb 10
tc qdisc add dev ifb0 parent 3:33 handle 33: sfq perturb 10
#https://speed.hetzner.de/1GB.bin
iptables -t mangle -A PREROUTING -s 88.198.248.254 -j MARK --set-mark 2
iptables -t mangle -A PREROUTING -j CONNMARK --save-mark
# Forward all ingress traffic on internet interface to the IFB device
tc qdisc add dev $EXTDEV ingress handle ffff:
tc filter add dev $EXTDEV parent ffff: protocol ip \
u32 match u32 0 0 \
action connmark \
action mirred egress redirect dev ifb0 \
flowid ffff:1
# Kein markieren mehr der Pakete / iptables fällt weg über ipset
# root@mrWhiteGhost:/home/urnilxfgbez/Desktop# ipset create slowdown hash:ip
#root@mrWhiteGhost:/home/urnilxfgbez/Desktop# tc filter add dev ifb0 parent 3:0 protocol ip basic match 'ipset(slowdown src,dst)' flowid 3:33
#
#
#
#
#root@mrWhiteGhost:/tmp# tc -s class show dev ifb0
#class htb 3:33 root prio 0 rate 10Mbit ceil 10Mbit burst 1600b cburst 1600b
# Sent 28375626 bytes 20582 pkt (dropped 0, overlimits 20488 requeues 0)
# backlog 0b 0p requeues 0
# lended: 20582 borrowed: 0 giants: 0
# tokens: -16889 ctokens: -16889
#
#class htb 3:30 root prio 0 rate 60Mbit ceil 60Mbit burst 1590b cburst 1590b
# Sent 1760229 bytes 3364 pkt (dropped 0, overlimits 884 requeues 0)
# backlog 0b 0p requeues 0
# lended: 3364 borrowed: 0 giants: 0
# tokens: 3125 ctokens: 3125
exit 0
GeoIP - iptables matches
- Getestet mit Debian Buster - Achtung hier gibt es keine xtables-addons* Pakete mehr / Sukzessive Wechsel zu nftables wird spürbar(er)
- Dafür gibt es die Pakete in Debian Bullseye wieder / Die Pakete für bullseye scheinen auch unter Debian Buster zu laufen (xtables-addons-common_3.13-1_amd64.deb/xtables-addons-dkms_3.13-1_all.deb )
testen,testen,testen
- Grundsätzliches: iptables -m geoip –help
iptables -m geoip --help
iptables v1.8.2
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:
Either long or short options are allowed.
--append -A chain Append to chain
--check -C chain Check for the existence of a rule
--delete -D chain Delete matching rule from chain
--delete -D chain rulenum
Delete rule rulenum (1 = first) from chain
--insert -I chain [rulenum]
Insert in chain as rulenum (default 1=first)
--replace -R chain rulenum
Replace rule rulenum (1 = first) in chain
--list -L [chain [rulenum]]
List the rules in a chain or all chains
--list-rules -S [chain [rulenum]]
Print the rules in a chain or all chains
--flush -F [chain] Delete all rules in chain or all chains
--zero -Z [chain [rulenum]]
Zero counters in chain or all chains
--new -N chain Create a new user-defined chain
--delete-chain
-X [chain] Delete a user-defined chain
--policy -P chain target
Change policy on chain to target
--rename-chain
-E old-chain new-chain
Change chain name, (moving any references)
Options:
--ipv4 -4 Nothing (line is ignored by ip6tables-restore)
--ipv6 -6 Error (line is ignored by iptables-restore)
[!] --proto -p proto protocol: by number or name, eg. `tcp'
[!] --source -s address[/mask][...]
source specification
[!] --destination -d address[/mask][...]
destination specification
[!] --in-interface -i input name[+]
network interface name ([+] for wildcard)
--jump -j target
target for rule (may load target extension)
--goto -g chain
jump to chain with no return
--match -m match
extended match (may load extension)
--numeric -n numeric output of addresses and ports
[!] --out-interface -o output name[+]
network interface name ([+] for wildcard)
--table -t table table to manipulate (default: `filter')
--verbose -v verbose mode
--wait -w [seconds] maximum wait to acquire xtables lock before give up
--wait-interval -W [usecs] wait time to try to acquire xtables lock
default is 1 second
--line-numbers print line numbers when listing
--exact -x expand numbers (display exact values)
[!] --fragment -f match second or further fragments only
--modprobe=<command> try to insert modules using this command
--set-counters PKTS BYTES set the counter during insert/append
[!] --version -V print package version.
geoip match options:
[!] --src-cc, --source-country country[,country...]
Match packet coming from (one of) the specified country(ies)
[!] --dst-cc, --destination-country country[,country...]
Match packet going to (one of) the specified country(ies)
NOTE: The country is inputed by its ISO3166 code
- Datenbank aktualisieren 1x im Monat update-geoip.sh
#!/bin/bash
DST_TEMP_DB="/tmp/dbip-country-lite.csv.gz"
SRC_URL="https://download.db-ip.com/free/dbip-country-lite-$(date +%Y)-$(date +%m).csv.gz"
#Required on Ubuntu 18.04: libtext-csv-xs-perl, libnet-cidr-lite-perl / took xt_geoip_build from ubuntu 20.04
XTABLES_BUILD_SCRIPT="/usr/lib/xtables-addons/xt_geoip_build"
XTABLES_GEOIP_DIRECTORY="/usr/share/xt_geoip"
function bailout
{
>&2 echo -e "$1"
exit 2
}
[[ -f $DST_TEMP_DB ]] && bailout "FAIL: $DST_TEMP_DB already found aborting"
wget -q "$SRC_URL" -O $DST_TEMP_DB || bailout "FAIL: $DST_TEMP_DB cannot be downloaded from $SRC_URL"
gunzip -t $DST_TEMP_DB || bailout "FAIL: Gzip Format failure from $SRC_URL"
[[ -d "$XTABLES_GEOIP_DIRECTORY" ]] || echo "FAIL: could not find Destination: $XTABLES_GEOIP_DIRECTORY"
gunzip -f $DST_TEMP_DB --to-stdout > $XTABLES_GEOIP_DIRECTORY/dbip-country-lite.csv || bailout "FAIL: cannot gunzip file from $SRC_URL"
[[ -x $XTABLES_BUILD_SCRIPT ]] || echo "FAIL: could not find $XTABLES_BUILD_SCRIPT"
$XTABLES_BUILD_SCRIPT -D "$XTABLES_GEOIP_DIRECTORY" -S "$XTABLES_GEOIP_DIRECTORY"
rm $DST_TEMP_DB
exit 0
- Achtung /usr/lib/xtables-addons/xt_geoip_build stammt aus dem Ubuntu 20.04 Paket von xtables-addons-common_3.8-2_amd64.deb
- Nach 20 Minuten Tests mit iptables matches gabs noch keine panic :)
19 976 LOG all -- * * 0.0.0.0/0 0.0.0.0/0 -m geoip --source-country CN,RS LOG flags 0 level 4
GeoIP - map-geoip.sh
- GeoIP Lookup aus vorhandenen Logfiles / kann auch gepiped werden um vorher relevante Auszüge rauszugreppen
- map-geoip.sh
#!/bin/bash
# cmd: foo=$(mmdblookup -f /usr/local/share/ip-db/dbip-country-lite.mmdb -i 192.168.0.1 country iso_code 2>/dev/null)
# https://download.db-ip.com/free/dbip-country-lite-2022-03.mmdb.gz
PATH_LOGS="/var/log/fw.log.1"
PATH_GEODB="/usr/local/share/ip-db/dbip-country-lite.mmdb"
function bailout
{
echo -e "$1" >&2
echo -e "\nUsage: $0 [LOGFILE_FIREWALLS]"
exit 2
}
function lookup_geo
{
mmdblookup -f $PATH_GEODB -i $1 country iso_code 2>/dev/null | grep -o -P "\"[a-zA-Z]{2}\"" | tr -d "\""
}
function lookup_ip
{
echo $1 | grep -o -P "$2(([0-9]{1,3}\.)){3}[0-9]{1,3}"
}
[[ -r $PATH_GEODB ]] || bailout "Cannot read geodb database: $PATH_GEODB"
[[ -r "$1" ]] && PATH_LOGS="$1"
[[ $1 == "-" ]] && PATH_LOGS="-"
[[ -r $PATH_LOGS || $PATH_LOGS == "-" ]] || bailout "Cannot read path logs: $PATH_LOGS"
which mmdblookup >/dev/null || bailout "Cannot find mmdblookup please install\n"
IFS=$'\n'
while read foo ;
do
LOG_SUFFIX=""
SRC_IP=""
DST_IP=""
SRC_IP=$(lookup_ip $foo "SRC=" |tr -d "SRC=")
DST_IP=$(lookup_ip $foo "DST=" | tr -d "DST=" )
#echo "SRC: $SRC_IP"
#echo "DST: $DST_IP"
if [ ${#SRC_IP} -gt 0 ] && [ ${#DST_IP} -gt 0 ]
then
SRC_GEO=$(lookup_geo $SRC_IP)
DST_GEO=$(lookup_geo $DST_IP)
[[ -z $SRC_GEO ]] && SRC_GEO="00"
[[ -z $DST_GEO ]] && DST_GEO="00"
LOG_SUFFIX="SRC_GEO=$SRC_GEO DST_GEO=$DST_GEO"
echo "$foo$LOG_SUFFIX"
fi
done < <(zcat -f $PATH_LOGS )
WEB Module
Blocks - Multi - IPSET
- In Kombination mit dnsmasq und seiner Funktionalität ipsets aktualisieren zu können
- www-data muss dnsmasq neu starten können zB: visudo → www-data ALL=(ALL)NOPASSWD:/usr/sbin/service dnsmasq restart / und die entsprechenden Berechtigungen für das Set File besitzen unter /etc/dnsmasq.d/ipset-foo.conf
- Achtung: Wenn es eine Vielzahl an Sets gibt die mit dnsmasq befüllt werden sollen muss auf die dnsmasq Syntax geachtet werden ipset=/hostname/set1/set2/set3 und nicht jeweils eine extra Datei für set1, set2, set3
- merge-ipsets.sh
#!/bin/bash
function bailout
{
echo -e "$1" >&2
exit 2
}
which dnsmasq >/dev/null || bailout "Cannot find dnsmasq binary"
LOCATION_DNSMASQS="/etc/dnsmasq.conf /etc/dnsmasq.d/*"
TMP_LOCATION=$(mktemp)
FINAL_LOCATION="/etc/dnsmasq.d/ipset-master.conf"
if [ ! -w $FINAL_LOCATION ]
then
rm $TMP_LOCATION
bailout "FAIL: Final config file: $FINAL_LOCATION cannot be written to "
fi
grep -h "^ipset=" $LOCATION_DNSMASQS | cut -d"/" -f"2" | sort | uniq -c | while read hosts ;
do
nr_matches=$(echo $hosts | awk '{print $1}')
host_entry=$(echo $hosts | awk '{print $2}')
if (($nr_matches > 1 )) && [ -n $host_entry ] ;
then
build_entry="ipset=/$host_entry"
while read found_sets
do
build_entry+="/$found_sets"
done <<< $(grep -h "^ipset=/$host_entry/" $LOCATION_DNSMASQS | cut -d"/" -f 3- | tr "/" "\n" | sort | uniq )
echo $build_entry >> $TMP_LOCATION
echo $build_entry
fi
done
filesize_tmp=$(stat -c %s $TMP_LOCATION)
if [ $filesize_tmp == "0" ]
then
rm $TMP_LOCATION
echo "No double ipsets found in $LOCATION_DNSMASQS"
exit 0
fi
cmp -s $TMP_LOCATION $FINAL_LOCATION
compare_ret="$?"
if [ $compare_ret == "0" ]
then
rm $TMP_LOCATION
echo "Current ipsets have already been merged"
exit 0
fi
dnsmasq --test --conf-file=$TMP_LOCATION
ipset_tests="$?"
if [ $ipset_tests != "0" ]
then
rm $TMP_LOCATION
bailout "FAIL: Malformed config file: $TMP_LOCATION"
fi
#2022-02-21 cc: Keep Ownership intact
cat $TMP_LOCATION > $FINAL_LOCATION
rm $TMP_LOCATION
systemctl reload dnsmasq || bailout "FAIL: Cannot reload dnsmasq"
exit 0
Blocks - IPSET
- In Kombination mit dnsmasq und seiner Funktionalität ipsets aktualisieren zu können
- www-data muss dnsmasq neu starten können zB: visudo → www-data ALL=(ALL)NOPASSWD:/usr/sbin/service dnsmasq restart / und die entsprechenden Berechtigungen für das Set File besitzen unter /etc/dnsmasq.d/ipset-foo.conf
Blocks - Hostnamen
- In Kombination mit dnsmasq / um quasi „dns Spoofing“ zu betreiben d.h. das Resolving zu überschreiben für bestimmte Hostnamen
- www-data muss dnsmasq neu starten können zB: visudo → www-data ALL=(ALL)NOPASSWD:/usr/sbin/service dnsmasq restart
Proxy
- Um squid proxy ACLs zu bearbeiten
- Achtung www-data braucht sudo Rechte für parse / reload
- zB: visudo → www-data ALL=(ALL)NOPASSWD:/usr/sbin/squid3 -k reconfigure, /usr/sbin/squid3 -k parse
Authorizer
- Um nach erfolgter Authentifizierung IP/MACs in ipset einzutragen
know-how/firewall.txt · Zuletzt geändert: 2025/10/02 10:00 von cc




