1 # banIP shared function library/include - ban incoming and outgoing IPs via named nftables Sets
2 # Copyright (c) 2018-2024 Dirk Brenken (dev@brenken.org)
3 # This is free software, licensed under the GNU General Public License v3.
5 # (s)hellcheck exceptions
6 # shellcheck disable=all
11 export PATH
="/usr/sbin:/usr/bin:/sbin:/bin"
16 ban_backupdir
="/tmp/banIP-backup"
17 ban_reportdir
="/tmp/banIP-report"
18 ban_feedfile
="/etc/banip/banip.feeds"
19 ban_customfeedfile
="/etc/banip/banip.custom.feeds"
20 ban_allowlist
="/etc/banip/banip.allowlist"
21 ban_blocklist
="/etc/banip/banip.blocklist"
22 ban_mailtemplate
="/etc/banip/banip.tpl"
23 ban_pidfile
="/var/run/banip.pid"
24 ban_rtfile
="/var/run/banip_runtime.json"
25 ban_rdapfile
="/var/run/banip_rdap.json"
26 ban_rdapurl
="https://rdap.db.ripe.net/ip/"
27 ban_lock
="/var/run/banip.lock"
28 ban_logreadfile
="/var/log/messages"
30 ban_mailsender
="no-reply@banIP"
32 ban_mailtopic
="banIP notification"
33 ban_mailprofile
="ban_notify"
34 ban_mailnotification
="0"
35 ban_reportelements
="1"
38 ban_nftloglevel
="warn"
39 ban_nftpriority
="-200"
40 ban_nftpolicy
="memory"
53 ban_autoallowuplink
="subnet"
55 ban_autoblocksubnet
="0"
63 ban_blockforwardwan
=""
64 ban_blockforwardlan
=""
87 # gather system information
92 if [ -z "${ban_dev}" ]; then
93 ban_debug
="$(uci_get banip global ban_debug)"
94 ban_cores
="$(uci_get banip global ban_cores)"
96 ban_packages
="$("${ban_ubuscmd}" -S call rpc-sys packagelist '{ "all
": true }' 2>/dev/null)"
97 ban_memory
="$("${ban_awkcmd}" '/^MemAvailable/{printf "%s
",int($2/1000)}' "/proc
/meminfo
" 2>/dev/null)"
98 ban_ver
="$(printf "%s
" "${ban_packages}" | "${ban_jsoncmd}" -ql1 -e '@.packages.banip')"
99 ban_sysver
="$("${ban_ubuscmd}" -S call system board 2>/dev/null | "${ban_jsoncmd}" -ql1 -e '@.model' -e '@.release.description' |
100 "${ban_awkcmd}" 'BEGIN{RS="";FS="\n"}{printf "%s
, %s
",$1,$2}')"
101 if [ -z "${ban_cores}" ]; then
102 cpu
="$("${ban_grepcmd}" -c '^processor' /proc/cpuinfo 2>/dev/null)"
103 core
="$("${ban_grepcmd}" -cm1 '^core id' /proc/cpuinfo 2>/dev/null)"
104 [ "${cpu}" = "0" ] && cpu
="1"
105 [ "${core}" = "0" ] && core
="1"
106 ban_cores
="$((cpu * core))"
113 local cmd pri_cmd
="${1}" sec_cmd
="${2}"
115 cmd
="$(command -v "${pri_cmd}" 2>/dev/null)"
116 if [ ! -x "${cmd}" ]; then
117 if [ -n "${sec_cmd}" ]; then
118 [ "${sec_cmd}" = "true" ] && return
119 cmd
="$(command -v "${sec_cmd}" 2>/dev/null)"
121 if [ -x "${cmd}" ]; then
124 f_log
"emerg" "command '${pri_cmd:-"-"}'/'${sec_cmd:-"-"}' not found"
136 if [ ! -d "${dir}" ]; then
139 f_log
"debug" "f_mkdir ::: directory: ${dir}"
148 if [ ! -f "${file}" ]; then
150 f_log
"debug" "f_mkfile ::: file: ${file}"
154 # create temporary files and directories
157 f_mkdir
"${ban_basedir}"
158 ban_tmpdir
="$(mktemp -p "${ban_basedir}" -d)"
159 ban_tmpfile
="$(mktemp -p "${ban_tmpdir}" -tu)"
161 f_log
"debug" "f_tmp ::: base_dir: ${ban_basedir:-"-"}, tmp_dir: ${ban_tmpdir:-"-"}"
169 if [ -d "${dir}" ]; then
171 f_log
"debug" "f_rmdir ::: directory: ${dir}"
180 if [ "${char}" = "1" ]; then
182 elif [ "${char}" = "0" ] ||
[ -z "${char}" ]; then
185 printf "%s" "${char}"
194 string
="${string#"${string%%[![:space:]]*}"}"
195 string
="${string%"${string##*[![:space:]]}"}"
196 printf "%s" "${string}"
204 ppid
="$("${ban_catcmd}" "${ban_pidfile}" 2>/dev/null)"
205 if [ -n "${ppid}" ]; then
206 pids
="$("${ban_pgrepcmd}" -P "${ppid}" 2>/dev/null)"
207 for pid
in ${pids}; do
208 pids
="${pids} $("${ban_pgrepcmd}" -P "${pid}" 2>/dev
/null
)"
210 for pid in ${pids}; do
211 kill -INT "${pid}" >/dev/null 2>&1
221 local class="${1}" log_msg="${2}"
223 if [ -n "${log_msg}" ] && { [ "${class}" != "debug" ] || [ "${ban_debug}" = "1" ]; }; then
224 if [ -x "${ban_logcmd}" ]; then
225 "${ban_logcmd}" -p "${class}" -t "banIP-${ban_ver}[${$}]" "${log_msg}"
227 printf "%s %s %s\n" "${class}" "banIP-${ban_ver}[${$}]" "${log_msg}"
230 if [ "${class}" = "err" ] ||
[ "${class}" = "emerg" ]; then
231 if [ "${class}" = "err" ]; then
232 "${ban_nftcmd}" delete table inet banIP
>/dev
/null
2>&1
233 if [ "$(uci_get banip global ban_enabled)" = "1" ]; then
235 [ "${ban_mailnotification}" = "1" ] && [ -n "${ban_mailreceiver}" ] && [ -x "${ban_mailcmd}" ] && f_mail
237 f_genstatus
"disabled"
240 f_rmdir
"${ban_tmpdir}"
250 unset ban_dev ban_vlanallow ban_vlanblock ban_ifv4 ban_ifv6 ban_feed ban_allowurl ban_blockinput ban_blockforwardwan ban_blockforwardlan ban_logterm ban_country ban_asn
255 eval "${option}=\"${value}\""
262 eval "${option}=\"$(printf "%s" "${ban_ifv4}")${value} \""
265 eval "${option}=\"$(printf "%s" "${ban_ifv6}")${value} \""
268 eval "${option}=\"$(printf "%s" "${ban_dev}")${value} \""
271 eval "${option}=\"$(printf "%s" "${ban_vlanallow}")${value} \""
274 eval "${option}=\"$(printf "%s" "${ban_vlanblock}")${value} \""
277 eval "${option}=\"$(printf "%s" "${ban_trigger}")${value} \""
280 eval "${option}=\"$(printf "%s" "${ban_feed}")${value} \""
283 eval "${option}=\"$(printf "%s" "${ban_allowurl}")${value} \""
286 eval "${option}=\"$(printf "%s" "${ban_blockinput}")${value} \""
288 "ban_blockforwardwan")
289 eval "${option}=\"$(printf "%s" "${ban_blockforwardwan}")${value} \""
291 "ban_blockforwardlan")
292 eval "${option}=\"$(printf "%s" "${ban_blockforwardlan}")${value} \""
295 eval "${option}=\"$(printf "%s" "${ban_logterm}")${value}\\|\""
298 eval "${option}=\"$(printf "%s" "${ban_country}")${value} \""
301 eval "${option}=\"$(printf "%s" "${ban_asn}")${value} \""
307 [ -f "${ban_logreadfile}" ] && ban_logreadcmd
="$(command -v tail)" || ban_logreadcmd
="$(command -v logread)"
310 # get nft/monitor actuals
313 local nft monitor ppid pids pid
315 if "${ban_nftcmd}" -t list
set inet banIP allowlistv4MAC
>/dev
/null
2>&1; then
321 ppid
="$("${ban_catcmd}" "${ban_pidfile}" 2>/dev/null)"
322 if [ -n "${ppid}" ]; then
323 pids
="$("${ban_pgrepcmd}" -P "${ppid}" 2>/dev/null)"
324 for pid
in ${pids}; do
325 if "${ban_pgrepcmd}" -f "${ban_logreadcmd##*/}" -P "${pid}" >/dev
/null
2>&1; then
326 monitor
="$(f_char "1")"
329 monitor
="$(f_char "0")"
333 monitor
="$(f_char "0")"
335 printf "%s" "nft: ${nft}, monitor: ${monitor}"
341 local item utils insecure update
="0"
343 if { [ "${ban_fetchcmd}" = "uclient-fetch" ] && printf "%s" "${ban_packages}" | "${ban_grepcmd}" -q '"libustream-'; } ||
344 { [ "${ban_fetchcmd}" = "wget" ] && printf "%s" "${ban_packages}" | "${ban_grepcmd}" -q '"wget-ssl'; } ||
345 [ "${ban_fetchcmd}" = "curl" ] ||
[ "${ban_fetchcmd}" = "aria2c" ]; then
346 ban_fetchcmd
="$(f_cmd "${ban_fetchcmd}" "true
")"
349 if [ "${ban_autodetect}" = "1" ] && [ ! -x "${ban_fetchcmd}" ]; then
350 utils
="aria2c curl wget uclient-fetch"
351 for item
in ${utils}; do
352 if { [ "${item}" = "uclient-fetch" ] && printf "%s" "${ban_packages}" | "${ban_grepcmd}" -q '"libustream-'; } ||
353 { [ "${item}" = "wget" ] && printf "%s" "${ban_packages}" | "${ban_grepcmd}" -q '"wget-ssl'; } ||
354 [ "${item}" = "curl" ] ||
[ "${item}" = "aria2c" ]; then
355 ban_fetchcmd
="$(command -v "${item}")"
356 if [ -x "${ban_fetchcmd}" ]; then
358 uci_set banip global ban_fetchcmd
"${item}"
366 [ ! -x "${ban_fetchcmd}" ] && f_log
"err" "no download utility with SSL support"
367 case "${ban_fetchcmd##*/}" in
369 [ "${ban_fetchinsecure}" = "1" ] && insecure
="--check-certificate=false"
370 ban_fetchparm
="${ban_fetchparm:-"${insecure} --timeout=20 --retry-wait=10 --max-tries=${ban_fetchretry} --max-file-not-found=${ban_fetchretry} --allow-overwrite=true --auto-file-renaming=false --log-level=warn --dir=/ -o"}"
371 ban_rdapparm
="--timeout=5 --allow-overwrite=true --auto-file-renaming=false --dir=/ -o"
372 ban_etagparm
="--timeout=5 --allow-overwrite=true --auto-file-renaming=false --dir=/ --dry-run --log -"
375 [ "${ban_fetchinsecure}" = "1" ] && insecure
="--insecure"
376 ban_fetchparm
="${ban_fetchparm:-"${insecure} --connect-timeout 20 --retry-delay 10 --retry ${ban_fetchretry} --retry-max-time $((ban_fetchretry * 20)) --retry-all-errors --fail --silent --show-error --location -o"}"
377 ban_rdapparm
="--connect-timeout 5 --silent --location -o"
378 ban_etagparm
="--connect-timeout 5 --silent --location --head"
381 [ "${ban_fetchinsecure}" = "1" ] && insecure
="--no-check-certificate"
382 ban_fetchparm
="${ban_fetchparm:-"${insecure} --no-cache --no-cookies --timeout=20 --waitretry=10 --tries=${ban_fetchretry} --retry-connrefused -O"}"
383 ban_rdapparm
="--timeout=5 -O"
384 ban_etagparm
="--timeout=5 --spider --server-response"
387 [ "${ban_fetchinsecure}" = "1" ] && insecure
="--no-check-certificate"
388 ban_fetchparm
="${ban_fetchparm:-"${insecure} --timeout=20 -O"}"
389 ban_rdapparm
="--timeout=5 -O"
393 f_log
"debug" "f_getfetch ::: auto/update: ${ban_autodetect}/${update}, cmd: ${ban_fetchcmd:-"-"}, fetch_parm: ${ban_fetchparm:-"-"}, rdap_parm: ${ban_rdapparm:-"-"}, etag_parm: ${ban_etagparm:-"-"}"
399 local iface iface_del update
="0"
401 if [ "${ban_autodetect}" = "1" ]; then
403 network_find_wan iface
404 if [ -n "${iface}" ] && [ "${iface}" != "$(f_trim "${ban_ifv4}")" ] && "${ban_ubuscmd}" -t 10 wait_for network.interface."${iface}" >/dev
/null
2>&1; then
405 for iface_del
in ${ban_ifv4}; do
406 uci_remove_list banip global ban_ifv4
"${iface_del}"
407 f_log
"info" "remove IPv4 interface '${iface_del}' from config"
411 uci_set banip global ban_protov4
"1"
412 uci_add_list banip global ban_ifv4
"${iface}"
413 f_log
"info" "add IPv4 interface '${iface}' to config"
415 network_find_wan6 iface
416 if [ -n "${iface}" ] && [ "${iface}" != "$(f_trim "${ban_ifv6}")" ] && "${ban_ubuscmd}" -t 10 wait_for network.interface."${iface}" >/dev
/null
2>&1; then
417 for iface_del
in ${ban_ifv6}; do
418 uci_remove_list banip global ban_ifv6
"${iface_del}"
419 f_log
"info" "remove IPv6 interface '${iface_del}' from config"
423 uci_set banip global ban_protov6
"1"
424 uci_add_list banip global ban_ifv6
"${iface}"
425 f_log
"info" "add IPv6 interface '${iface}' to config"
428 if [ -n "$(uci -q changes "banip
")" ]; then
432 for iface
in ${ban_ifv4} ${ban_ifv6}; do
433 if ! "${ban_ubuscmd}" -t 10 wait_for network.interface.
"${iface}" >/dev
/null
2>&1; then
434 f_log
"err" "no wan interface '${iface}'"
438 ban_ifv4
="$(f_trim "${ban_ifv4}")"
439 ban_ifv6
="$(f_trim "${ban_ifv6}")"
440 [ -z "${ban_ifv4}" ] && [ -z "${ban_ifv6}" ] && f_log
"err" "no wan interfaces"
442 f_log
"debug" "f_getif ::: auto/update: ${ban_autodetect}/${update}, interfaces (4/6): ${ban_ifv4}/${ban_ifv6}, protocols (4/6): ${ban_protov4}/${ban_protov6}"
448 local dev dev_del iface update
="0"
450 if [ "${ban_autodetect}" = "1" ]; then
453 for iface
in ${ban_ifv4} ${ban_ifv6}; do
454 network_get_device dev
"${iface}"
455 if [ -n "${dev}" ]; then
456 dev_del
="${dev_del/${dev} / }"
457 if ! printf " %s " "${ban_dev}" | "${ban_grepcmd}" -q " ${dev} "; then
458 ban_dev
="${ban_dev}${dev} "
459 uci_add_list banip global ban_dev
"${dev}"
460 f_log
"info" "add device '${dev}' to config"
464 for dev
in ${dev_del}; do
465 ban_dev
="${ban_dev/${dev} / }"
466 uci_remove_list banip global ban_dev
"${dev}"
467 f_log
"info" "remove device '${dev}' from config"
470 if [ -n "$(uci -q changes "banip
")" ]; then
474 ban_dev
="$(f_trim "${ban_dev}")"
475 [ -z "${ban_dev}" ] && f_log
"err" "no wan devices"
477 f_log
"debug" "f_getdev ::: auto/update: ${ban_autodetect}/${update}, wan_devices: ${ban_dev}"
483 local uplink iface ip update
="0"
485 if [ "${ban_autoallowlist}" = "1" ] && [ "${ban_autoallowuplink}" != "disable" ]; then
486 for iface
in ${ban_ifv4} ${ban_ifv6}; do
488 if [ "${ban_autoallowuplink}" = "subnet" ]; then
489 network_get_subnet uplink
"${iface}"
490 elif [ "${ban_autoallowuplink}" = "ip" ]; then
491 network_get_ipaddr uplink
"${iface}"
493 if [ -n "${uplink}" ] && ! printf " %s " "${ban_uplink}" | "${ban_grepcmd}" -q " ${uplink} "; then
494 ban_uplink
="${ban_uplink}${uplink} "
496 if [ "${ban_autoallowuplink}" = "subnet" ]; then
497 network_get_subnet6 uplink
"${iface}"
498 elif [ "${ban_autoallowuplink}" = "ip" ]; then
499 network_get_ipaddr6 uplink
"${iface}"
501 if [ -n "${uplink}" ] && ! printf " %s " "${ban_uplink}" | "${ban_grepcmd}" -q " ${uplink} "; then
502 ban_uplink
="${ban_uplink}${uplink} "
505 for ip
in ${ban_uplink}; do
506 if ! "${ban_grepcmd}" -q "${ip} " "${ban_allowlist}"; then
507 if [ "${update}" = "0" ]; then
508 "${ban_sedcmd}" -i "/# uplink added on /d" "${ban_allowlist}"
510 printf "%-42s%s\n" "${ip}" "# uplink added on $(date "+%Y-
%m-
%d
%H
:%M
:%S
")" >>"${ban_allowlist}"
511 f_log
"info" "add uplink '${ip}' to local allowlist"
515 ban_uplink
="$(f_trim "${ban_uplink}")"
516 elif [ "${ban_autoallowlist}" = "1" ] && [ "${ban_autoallowuplink}" = "disable" ]; then
517 "${ban_sedcmd}" -i "/# uplink added on /d" "${ban_allowlist}"
521 f_log
"debug" "f_getuplink ::: auto/update: ${ban_autoallowlist}/${update}, uplink: ${ban_uplink:-"-"}"
524 # get feed information
528 if [ -s "${ban_customfeedfile}" ]; then
529 if json_load_file
"${ban_customfeedfile}" >/dev
/null
2>&1; then
532 f_log
"info" "can't load banIP custom feed file"
535 if [ -s "${ban_feedfile}" ] && json_load_file
"${ban_feedfile}" >/dev
/null
2>&1; then
538 f_log
"err" "can't load banIP feed file"
547 [ -s "${file}" ] && printf "%s" "elements={ $("${ban_catcmd}" "${file}" 2>/dev/null) };"
550 # handle etag http header
553 local http_head http_code etag_id etag_rc out_rc
="4" feed
="${1}" feed_url="${2}" feed_suffix="${3}"
555 if [ -n "${ban_etagparm}" ]; then
556 [ ! -f "${ban_backupdir}/banIP.etag" ] && : >"${ban_backupdir}/banIP.etag"
557 http_head
="$("${ban_fetchcmd}" ${ban_etagparm} "${feed_url}" 2>&1)"
558 http_code
="$(printf "%s
" "${http_head}" | "${ban_awkcmd}" 'tolower($0)~/^http\/[0123\.]+ /{printf "%s",$2}')"
559 etag_id="$(printf "%s" "${http_head}" | "${ban_awkcmd}" 'tolower($0)~/^[[:space:]]*etag: /{gsub("\"","");printf "%s",$2}')"
562 if [ "${http_code}" = "404" ] || { [ "${etag_rc}" = "0" ] && [ -n "${etag_id}" ] && "${ban_grepcmd}" -q "^${feed}${feed_suffix}[[:space:]]\+${etag_id}\$" "${ban_backupdir}/banIP.etag"; }; then
564 elif [ "${etag_rc}" = "0" ] && [ -n "${etag_id}" ] && ! "${ban_grepcmd}" -q "^${feed}${feed_suffix}[[:space:]]\+${etag_id}\$" "${ban_backupdir}/banIP.etag"; then
565 "${ban_sedcmd}" -i "/^${feed}${feed_suffix}/d" "${ban_backupdir}/banIP.etag"
566 printf "%-20s%s\n" "${feed}${feed_suffix}" "${etag_id}" >>"${ban_backupdir}/banIP.etag"
571 f_log
"debug" "f_etag ::: feed: ${feed}, suffix: ${feed_suffix:-"-"}, http_code: ${http_code:-"-"}, etag_id: ${etag_id:-"-"} , etag_rc: ${etag_rc:-"-"}, rc: ${out_rc}"
575 # build initial nft file with base table, chains and rules
578 local wan_dev vlan_allow vlan_block feed_log feed_rc
file="${1}"
580 wan_dev
="$(printf "%s
" "${ban_dev}" | "${ban_sedcmd}" 's/^/\"/;s/$/\"/;s/ /\", \"/g')"
581 [ -n "${ban_vlanallow}" ] && vlan_allow="$(printf "%s" "${ban_vlanallow%%?}" | "${ban_sedcmd}" 's/^/\"/;s/$/\"/;s/ /\", \"/g')"
582 [ -n "${ban_vlanblock}" ] && vlan_block="$(printf "%s" "${ban_vlanblock%%?}" | "${ban_sedcmd}" 's/^/\"/;s/$/\"/;s/ /\", \"/g')"
585 # nft header (tables and chains)
587 printf "%s\n\n" "#!/usr/sbin/nft -f"
588 if "${ban_nftcmd}" -t list
set inet banIP allowlistv4MAC
>/dev
/null
2>&1; then
589 printf "%s\n" "delete table inet banIP"
591 printf "%s\n" "add table inet banIP"
592 printf "%s\n" "add chain inet banIP wan-input { type filter hook input priority ${ban_nftpriority}; policy accept; }"
593 printf "%s\n" "add chain inet banIP wan-forward { type filter hook forward priority ${ban_nftpriority}; policy accept; }"
594 printf "%s\n" "add chain inet banIP lan-forward { type filter hook forward priority ${ban_nftpriority}; policy accept; }"
595 printf "%s\n" "add chain inet banIP reject-chain"
597 # default reject rules
599 printf "%s\n" "add rule inet banIP reject-chain meta l4proto tcp reject with tcp reset"
600 printf "%s\n" "add rule inet banIP reject-chain reject"
602 # default wan-input rules
604 printf "%s\n" "add rule inet banIP wan-input ct state established,related counter accept"
605 printf "%s\n" "add rule inet banIP wan-input iifname != { ${wan_dev} } counter accept"
606 printf "%s\n" "add rule inet banIP wan-input meta nfproto ipv4 udp sport 67-68 udp dport 67-68 counter accept"
607 printf "%s\n" "add rule inet banIP wan-input meta nfproto ipv6 udp sport 547 udp dport 546 counter accept"
608 printf "%s\n" "add rule inet banIP wan-input meta nfproto ipv4 icmp type { echo-request } limit rate 1000/second counter accept"
609 printf "%s\n" "add rule inet banIP wan-input meta nfproto ipv6 icmpv6 type { echo-request } limit rate 1000/second counter accept"
610 printf "%s\n" "add rule inet banIP wan-input meta nfproto ipv6 icmpv6 type { nd-neighbor-advert, nd-neighbor-solicit, nd-router-advert} limit rate 1000/second ip6 hoplimit 1 counter accept"
611 printf "%s\n" "add rule inet banIP wan-input meta nfproto ipv6 icmpv6 type { nd-neighbor-advert, nd-neighbor-solicit, nd-router-advert} limit rate 1000/second ip6 hoplimit 255 counter accept"
613 # default wan-forward rules
615 printf "%s\n" "add rule inet banIP wan-forward ct state established,related counter accept"
616 printf "%s\n" "add rule inet banIP wan-forward iifname != { ${wan_dev} } counter accept"
618 # default lan-forward rules
620 printf "%s\n" "add rule inet banIP lan-forward ct state established,related counter accept"
621 printf "%s\n" "add rule inet banIP lan-forward oifname != { ${wan_dev} } counter accept"
622 [ -n "${vlan_allow}" ] && printf "%s\n" "add rule inet banIP lan-forward iifname { ${vlan_allow} } counter accept"
623 [ -n "${vlan_block}" ] && printf "%s\n" "add rule inet banIP lan-forward iifname { ${vlan_block} } counter goto reject-chain"
626 # load initial banIP table within nft (atomic load)
628 feed_log
="$("${ban_nftcmd}" -f "${file}" 2>&1)"
631 f_log
"debug" "f_nftinit ::: wan_dev: ${wan_dev}, vlan_allow: ${vlan_allow:-"-"}, vlan_block: ${vlan_block:-"-"}, priority: ${ban_nftpriority}, policy: ${ban_nftpolicy}, loglevel: ${ban_nftloglevel}, rc: ${feed_rc:-"-"}, log: ${feed_log:-"-"}"
638 local log_input log_forwardwan log_forwardlan start_ts end_ts tmp_raw tmp_load tmp_file split_file ruleset_raw handle rc etag_rc
639 local expr cnt_set cnt_dl restore_rc feed_direction feed_rc feed_log feed_comp feed_proto feed_dport flag
640 local feed
="${1}" proto="${2}" feed_url="${3}" feed_rule="${4}" feed_flag="${5}"
642 start_ts
="$(date +%s)"
643 feed
="${feed}v${proto}"
644 tmp_load
="${ban_tmpfile}.${feed}.load"
645 tmp_raw
="${ban_tmpfile}.${feed}.raw"
646 tmp_split
="${ban_tmpfile}.${feed}.split"
647 tmp_file
="${ban_tmpfile}.${feed}.file"
648 tmp_flush
="${ban_tmpfile}.${feed}.flush"
649 tmp_nft
="${ban_tmpfile}.${feed}.nft"
650 tmp_allow
="${ban_tmpfile}.${feed%v*}"
652 [ "${ban_loginput}" = "1" ] && log_input="log level ${ban_nftloglevel} prefix \"banIP/inp-wan/${ban_blocktype}/${feed}: \""
653 [ "${ban_logforwardwan}" = "1" ] && log_forwardwan="log level ${ban_nftloglevel} prefix \"banIP/fwd-wan/${ban_blocktype}/${feed}: \""
654 [ "${ban_logforwardlan}" = "1" ] && log_forwardlan="log level ${ban_nftloglevel} prefix \"banIP/fwd-lan/reject/${feed}: \""
656 # set feed block direction
658 if [ "${ban_blockpolicy}" = "input" ]; then
659 if ! printf "%s" "${ban_blockinput}" | "${ban_grepcmd}" -q "${feed%v*}" &&
660 ! printf "%s" "${ban_blockforwardwan}" | "${ban_grepcmd}" -q "${feed%v*}" &&
661 ! printf "%s" "${ban_blockforwardlan}" | "${ban_grepcmd}" -q "${feed%v*}"; then
662 ban_blockinput
="${ban_blockinput} ${feed%v*}"
664 elif [ "${ban_blockpolicy}" = "forwardwan" ]; then
665 if ! printf "%s" "${ban_blockinput}" | "${ban_grepcmd}" -q "${feed%v*}" &&
666 ! printf "%s" "${ban_blockforwardwan}" | "${ban_grepcmd}" -q "${feed%v*}" &&
667 ! printf "%s" "${ban_blockforwardlan}" | "${ban_grepcmd}" -q "${feed%v*}"; then
668 ban_blockforwardwan
="${ban_blockforwardwan} ${feed%v*}"
670 elif [ "${ban_blockpolicy}" = "forwardlan" ]; then
671 if ! printf "%s" "${ban_blockinput}" | "${ban_grepcmd}" -q "${feed%v*}" &&
672 ! printf "%s" "${ban_blockforwardwan}" | "${ban_grepcmd}" -q "${feed%v*}" &&
673 ! printf "%s" "${ban_blockforwardlan}" | "${ban_grepcmd}" -q "${feed%v*}"; then
674 ban_blockforwardlan
="${ban_blockforwardlan} ${feed%v*}"
677 if printf "%s" "${ban_blockinput}" | "${ban_grepcmd}" -q "${feed%v*}"; then
678 feed_direction
="input"
680 if printf "%s" "${ban_blockforwardwan}" | "${ban_grepcmd}" -q "${feed%v*}"; then
681 feed_direction
="${feed_direction} forwardwan"
683 if printf "%s" "${ban_blockforwardlan}" | "${ban_grepcmd}" -q "${feed%v*}"; then
684 feed_direction
="${feed_direction} forwardlan"
689 for flag
in ${feed_flag}; do
690 if [ "${flag}" = "gz" ] && ! printf "%s" "${feed_comp}" | "${ban_grepcmd}" -qw "${flag}"; then
692 elif { [ "${flag}" = "tcp" ] || [ "${flag}" = "udp" ]; } && ! printf "%s" "${feed_proto}" | "${ban_grepcmd}" -qw "${flag}"; then
694 elif [ -n "${flag//[![:digit]]/}" ] && ! printf "%s" "${feed_dport}" | "${ban_grepcmd}" -qw "${flag}"; then
695 if [ -z "${feed_dport}" ]; then
698 feed_dport
="${feed_dport}, ${flag}"
702 [ -n "${feed_dport}" ] && feed_dport="${feed_proto:-"tcp"} dport { ${feed_dport} }"
704 # chain/rule maintenance
706 if [ "${ban_action}" = "reload" ] && "${ban_nftcmd}" -t list set inet banIP "${feed}" >/dev
/null
2>&1; then
707 ruleset_raw
="$("${ban_nftcmd}" -tj list ruleset 2>/dev/null)"
709 printf "%s\n" "flush set inet banIP ${feed}"
711 handle
="$(printf "%s
\n" "${ruleset_raw}" | "${ban_jsoncmd}" -ql1 -e "@.nftables[@.rule.table=\"banIP\"&&@.rule.chain=\"wan-input\"][@.expr[${expr}].match.right=\"@${feed}\"].handle
")"
712 [ -n "${handle}" ] && printf "%s\n" "delete rule inet banIP wan-input handle ${handle}"
713 handle
="$(printf "%s
\n" "${ruleset_raw}" | "${ban_jsoncmd}" -ql1 -e "@.nftables[@.rule.table=\"banIP\"&&@.rule.chain=\"wan-forward\"][@.expr[${expr}].match.right=\"@${feed}\"].handle
")"
714 [ -n "${handle}" ] && printf "%s\n" "delete rule inet banIP wan-forward handle ${handle}"
715 handle
="$(printf "%s
\n" "${ruleset_raw}" | "${ban_jsoncmd}" -ql1 -e "@.nftables[@.rule.table=\"banIP\"&&@.rule.chain=\"lan-forward\"][@.expr[${expr}].match.right=\"@${feed}\"].handle
")"
716 [ -n "${handle}" ] && printf "%s\n" "delete rule inet banIP lan-forward handle ${handle}"
721 # restore local backups
723 if [ "${feed%v*}" != "blocklist" ]; then
724 if [ -n "${ban_etagparm}" ] && [ "${ban_action}" = "reload" ] && [ "${feed_url}" != "local" ] && [ "${feed%v*}" != "allowlist" ]; then
726 if [ "${feed%v*}" = "country" ]; then
727 for country
in ${ban_country}; do
728 f_etag
"${feed}" "${feed_url}${country}-aggregated.zone" ".${country}"
730 [ "${rc}" = "4" ] && break
731 etag_rc
="$((etag_rc + rc))"
733 elif [ "${feed%v*}" = "asn" ]; then
734 for asn
in ${ban_asn}; do
735 f_etag
"${feed}" "${feed_url}AS${asn}" ".{asn}"
737 [ "${rc}" = "4" ] && break
738 etag_rc
="$((etag_rc + rc))"
741 f_etag
"${feed}" "${feed_url}"
745 if [ "${etag_rc}" = "0" ] || [ "${ban_action}" != "reload" ] || [ "${feed_url}" = "local" ]; then
746 if [ "${feed%v*}" = "allowlist" ] && [ ! -f "${tmp_allow}" ]; then
747 f_restore
"allowlist" "-" "${tmp_allow}" "${etag_rc}"
749 f_restore
"${feed}" "${feed_url}" "${tmp_load}" "${etag_rc}"
752 feed_rc
="${restore_rc}"
756 # prepare local/remote allowlist
758 if [ "${feed%v*}" = "allowlist" ] && [ ! -f "${tmp_allow}" ]; then
759 "${ban_catcmd}" "${ban_allowlist}" 2>/dev/null >"${tmp_allow}"
761 for feed_url
in ${ban_allowurl}; do
762 feed_log
="$("${ban_fetchcmd}" ${ban_fetchparm} "${tmp_load}" "${feed_url}" 2>&1)"
764 if [ "${feed_rc}" = "0" ] && [ -s "${tmp_load}" ]; then
765 "${ban_catcmd}" "${tmp_load}" 2>/dev/null >>"${tmp_allow}"
767 f_log
"info" "download for feed '${feed%v*}' failed (rc: ${feed_rc:-"-"}/log: ${feed_log})"
771 if [ "${feed_rc}" = "0" ]; then
772 f_backup
"allowlist" "${tmp_allow}"
773 elif [ -z "${restore_rc}" ] && [ "${feed_rc}" != "0" ]; then
774 f_restore
"allowlist" "-" "${tmp_allow}" "${feed_rc}"
781 if [ "${feed%v*}" = "allowlist" ]; then
783 printf "%s\n\n" "#!/usr/sbin/nft -f"
784 [ -s "${tmp_flush}" ] && "${ban_catcmd}" "${tmp_flush}"
785 if [ "${proto}" = "4MAC" ]; then
786 "${ban_awkcmd}" '/^([0-9A-f]{2}:){5}[0-9A-f]{2}(\/([0-9]|[1-3][0-9]|4[0-8]))?([[:space:]]+([0-9]{1,3}\.){3}(1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])(\/(1?[0-9]|2?[0-9]|3?[0-2]))?[[:space:]]*$|[[:space:]]+$|$)/{if(!$2)$2="0.0.0.0/0";if(!seen[$1]++)printf "%s . %s, ",tolower($1),$2}' "${tmp_allow}" >"${tmp_file}"
787 printf "%s\n" "add set inet banIP ${feed} { type ether_addr . ipv4_addr; flags interval; auto-merge; policy ${ban_nftpolicy}; $(f_getelements "${tmp_file}") }"
788 [ -z "${feed_direction##*forwardlan*}" ] && printf "%s\n" "add rule inet banIP lan-forward ether saddr . ip saddr @${feed} counter accept"
789 elif [ "${proto}" = "6MAC" ]; then
790 "${ban_awkcmd}" '/^([0-9A-f]{2}:){5}[0-9A-f]{2}(\/([0-9]|[1-3][0-9]|4[0-8]))?([[:space:]]+([0-9A-f]{0,4}:){1,7}[0-9A-f]{0,4}:?(\/(1?[0-2][0-8]|[0-9][0-9]))?[[:space:]]*$|[[:space:]]+$|$)/{if(!$2)$2="::/0";if(!seen[$1]++)printf "%s . %s, ",tolower($1),$2}' "${tmp_allow}" >"${tmp_file}"
791 printf "%s\n" "add set inet banIP ${feed} { type ether_addr . ipv6_addr; flags interval; auto-merge; policy ${ban_nftpolicy}; $(f_getelements "${tmp_file}") }"
792 [ -z "${feed_direction##*forwardlan*}" ] && printf "%s\n" "add rule inet banIP lan-forward ether saddr . ip6 saddr @${feed} counter accept"
793 elif [ "${proto}" = "4" ]; then
794 "${ban_awkcmd}" '/^(([0-9]{1,3}\.){3}(1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])(\/(1?[0-9]|2?[0-9]|3?[0-2]))?)([[:space:]].*|$)/{printf "%s, ",$1}' "${tmp_allow}" >"${tmp_file}"
795 printf "%s\n" "add set inet banIP ${feed} { type ipv4_addr; flags interval; auto-merge; policy ${ban_nftpolicy}; $(f_getelements "${tmp_file}") }"
796 if [ -z "${feed_direction##*input*}" ]; then
797 if [ "${ban_allowlistonly}" = "1" ]; then
798 if [ "${ban_blocktype}" = "reject" ]; then
799 printf "%s\n" "add rule inet banIP wan-input ip saddr != @${feed} ${log_input} counter goto reject-chain"
801 printf "%s\n" "add rule inet banIP wan-input ip saddr != @${feed} ${log_input} counter drop"
804 printf "%s\n" "add rule inet banIP wan-input ip saddr @${feed} counter accept"
807 if [ -z "${feed_direction##*forwardwan*}" ]; then
808 if [ "${ban_allowlistonly}" = "1" ]; then
809 if [ "${ban_blocktype}" = "reject" ]; then
810 printf "%s\n" "add rule inet banIP wan-forward ip saddr != @${feed} ${log_forwardwan} counter goto reject-chain"
812 printf "%s\n" "add rule inet banIP wan-forward ip saddr != @${feed} ${log_forwardwan} counter drop"
815 printf "%s\n" "add rule inet banIP wan-forward ip saddr @${feed} counter accept"
818 if [ -z "${feed_direction##*forwardlan*}" ]; then
819 if [ "${ban_allowlistonly}" = "1" ]; then
820 printf "%s\n" "add rule inet banIP lan-forward ip daddr != @${feed} ${log_forwardlan} counter goto reject-chain"
822 printf "%s\n" "add rule inet banIP lan-forward ip daddr @${feed} counter accept"
825 elif [ "${proto}" = "6" ]; then
826 "${ban_awkcmd}" '!/^([0-9A-f]{2}:){5}[0-9A-f]{2}.*/{printf "%s\n",$1}' "${tmp_allow}" |
827 "${ban_awkcmd}" '/^(([0-9A-f]{0,4}:){1,7}[0-9A-f]{0,4}:?(\/(1?[0-2][0-8]|[0-9][0-9]))?)([[:space:]].*|$)/{printf "%s, ",tolower($1)}' >"${tmp_file}"
828 printf "%s\n" "add set inet banIP ${feed} { type ipv6_addr; flags interval; auto-merge; policy ${ban_nftpolicy}; $(f_getelements "${tmp_file}") }"
829 if [ -z "${feed_direction##*input*}" ]; then
830 if [ "${ban_allowlistonly}" = "1" ]; then
831 if [ "${ban_blocktype}" = "reject" ]; then
832 printf "%s\n" "add rule inet banIP wan-input ip6 saddr != @${feed} ${log_input} counter goto reject-chain"
834 printf "%s\n" "add rule inet banIP wan-input ip6 saddr != @${feed} ${log_input} counter drop"
837 printf "%s\n" "add rule inet banIP wan-input ip6 saddr @${feed} counter accept"
840 if [ -z "${feed_direction##*forwardwan*}" ]; then
841 if [ "${ban_allowlistonly}" = "1" ]; then
842 if [ "${ban_blocktype}" = "reject" ]; then
843 printf "%s\n" "add rule inet banIP wan-forward ip6 saddr != @${feed} ${log_forwardwan} counter goto reject-chain"
845 printf "%s\n" "add rule inet banIP wan-forward ip6 saddr != @${feed} ${log_forwardwan} counter drop"
848 printf "%s\n" "add rule inet banIP wan-forward ip6 saddr @${feed} counter accept"
851 if [ -z "${feed_direction##*forwardlan*}" ]; then
852 if [ "${ban_allowlistonly}" = "1" ]; then
853 printf "%s\n" "add rule inet banIP lan-forward ip6 daddr != @${feed} ${log_forwardlan} counter goto reject-chain"
855 printf "%s\n" "add rule inet banIP lan-forward ip6 daddr @${feed} counter accept"
861 elif [ "${feed%v*}" = "blocklist" ]; then
863 printf "%s\n\n" "#!/usr/sbin/nft -f"
864 [ -s "${tmp_flush}" ] && "${ban_catcmd}" "${tmp_flush}"
865 if [ "${proto}" = "4MAC" ]; then
866 "${ban_awkcmd}" '/^([0-9A-f]{2}:){5}[0-9A-f]{2}(\/([0-9]|[1-3][0-9]|4[0-8]))?([[:space:]]+([0-9]{1,3}\.){3}(1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])(\/(1?[0-9]|2?[0-9]|3?[0-2]))?[[:space:]]*$|[[:space:]]+$|$)/{if(!$2)$2="0.0.0.0/0";if(!seen[$1]++)printf "%s . %s, ",tolower($1),$2}' "${ban_blocklist}" >"${tmp_file}"
867 printf "%s\n" "add set inet banIP ${feed} { type ether_addr . ipv4_addr; flags interval; auto-merge; policy ${ban_nftpolicy}; $(f_getelements "${tmp_file}") }"
868 [ -z "${feed_direction##*forwardlan*}" ] && printf "%s\n" "add rule inet banIP lan-forward ether saddr . ip saddr @${feed} counter goto reject-chain"
869 elif [ "${proto}" = "6MAC" ]; then
870 "${ban_awkcmd}" '/^([0-9A-f]{2}:){5}[0-9A-f]{2}(\/([0-9]|[1-3][0-9]|4[0-8]))?([[:space:]]+([0-9A-f]{0,4}:){1,7}[0-9A-f]{0,4}:?(\/(1?[0-2][0-8]|[0-9][0-9]))?[[:space:]]*$|[[:space:]]+$|$)/{if(!$2)$2="::/0";if(!seen[$1]++)printf "%s . %s, ",tolower($1),$2}' "${ban_blocklist}" >"${tmp_file}"
871 printf "%s\n" "add set inet banIP ${feed} { type ether_addr . ipv6_addr; flags interval; auto-merge; policy ${ban_nftpolicy}; $(f_getelements "${tmp_file}") }"
872 [ -z "${feed_direction##*forwardlan*}" ] && printf "%s\n" "add rule inet banIP lan-forward ether saddr . ip6 saddr @${feed} counter goto reject-chain"
873 elif [ "${proto}" = "4" ]; then
874 if [ "${ban_deduplicate}" = "1" ]; then
875 "${ban_awkcmd}" '/^(([0-9]{1,3}\.){3}(1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])(\/(1?[0-9]|2?[0-9]|3?[0-2]))?)([[:space:]].*|$)/{printf "%s,\n",$1}' "${ban_blocklist}" >"${tmp_raw}"
876 "${ban_awkcmd}" 'NR==FNR{member[$0];next}!($0 in member)' "${ban_tmpfile}.deduplicate" "${tmp_raw}" 2>/dev/null >"${tmp_split}"
877 "${ban_awkcmd}" 'BEGIN{FS="[ ,]"}NR==FNR{member[$1];next}!($1 in member)' "${ban_tmpfile}.deduplicate" "${ban_blocklist}" 2>/dev/null >"${tmp_raw}"
878 "${ban_catcmd}" "${tmp_raw}" 2>/dev/null >"${ban_blocklist}"
880 "${ban_awkcmd}" '/^(([0-9]{1,3}\.){3}(1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])(\/(1?[0-9]|2?[0-9]|3?[0-2]))?)([[:space:]].*|$)/{printf "%s,\n",$1}' "${ban_blocklist}" >"${tmp_split}"
882 "${ban_awkcmd}" '{ORS=" ";print}' "${tmp_split}" 2>/dev/null >"${tmp_file}"
883 printf "%s\n" "add set inet banIP ${feed} { type ipv4_addr; flags interval, timeout; auto-merge; policy ${ban_nftpolicy}; $(f_getelements "${tmp_file}") }"
884 if [ "${ban_blocktype}" = "reject" ]; then
885 [ -z "${feed_direction##*input*}" ] && printf "%s\n" "add rule inet banIP wan-input ip saddr @${feed} ${log_input} counter goto reject-chain"
886 [ -z "${feed_direction##*forwardwan*}" ] && printf "%s\n" "add rule inet banIP wan-forward ip saddr @${feed} ${log_forwardwan} counter goto reject-chain"
888 [ -z "${feed_direction##*input*}" ] && printf "%s\n" "add rule inet banIP wan-input ip saddr @${feed} ${log_input} counter drop"
889 [ -z "${feed_direction##*forwardwan*}" ] && printf "%s\n" "add rule inet banIP wan-forward ip saddr @${feed} ${log_forwardwan} counter drop"
891 [ -z "${feed_direction##*forwardlan*}" ] && printf "%s\n" "add rule inet banIP lan-forward ip daddr @${feed} ${log_forwardlan} counter goto reject-chain"
892 elif [ "${proto}" = "6" ]; then
893 if [ "${ban_deduplicate}" = "1" ]; then
894 "${ban_awkcmd}" '!/^([0-9A-f]{2}:){5}[0-9A-f]{2}.*/{printf "%s\n",$1}' "${ban_blocklist}" |
895 "${ban_awkcmd}" '/^(([0-9A-f]{0,4}:){1,7}[0-9A-f]{0,4}:?(\/(1?[0-2][0-8]|[0-9][0-9]))?)([[:space:]].*|$)/{printf "%s,\n",tolower($1)}' >"${tmp_raw}"
896 "${ban_awkcmd}" 'NR==FNR{member[$0];next}!($0 in member)' "${ban_tmpfile}.deduplicate" "${tmp_raw}" 2>/dev/null >"${tmp_split}"
897 "${ban_awkcmd}" 'BEGIN{FS="[ ,]"}NR==FNR{member[$1];next}!($1 in member)' "${ban_tmpfile}.deduplicate" "${ban_blocklist}" 2>/dev/null >"${tmp_raw}"
898 "${ban_catcmd}" "${tmp_raw}" 2>/dev/null >"${ban_blocklist}"
900 "${ban_awkcmd}" '!/^([0-9A-f]{2}:){5}[0-9A-f]{2}.*/{printf "%s\n",$1}' "${ban_blocklist}" |
901 "${ban_awkcmd}" '/^(([0-9A-f]{0,4}:){1,7}[0-9A-f]{0,4}:?(\/(1?[0-2][0-8]|[0-9][0-9]))?)([[:space:]].*|$)/{printf "%s,\n",tolower($1)}' >"${tmp_split}"
903 "${ban_awkcmd}" '{ORS=" ";print}' "${tmp_split}" 2>/dev/null >"${tmp_file}"
904 printf "%s\n" "add set inet banIP ${feed} { type ipv6_addr; flags interval, timeout; auto-merge; policy ${ban_nftpolicy}; $(f_getelements "${tmp_file}") }"
905 if [ "${ban_blocktype}" = "reject" ]; then
906 [ -z "${feed_direction##*input*}" ] && printf "%s\n" "add rule inet banIP wan-input ip6 saddr @${feed} ${log_input} counter goto reject-chain"
907 [ -z "${feed_direction##*forwardwan*}" ] && printf "%s\n" "add rule inet banIP wan-forward ip6 saddr @${feed} ${log_forwardwan} counter goto reject-chain"
909 [ -z "${feed_direction##*input*}" ] && printf "%s\n" "add rule inet banIP wan-input ip6 saddr @${feed} ${log_input} counter drop"
910 [ -z "${feed_direction##*forwardwan*}" ] && printf "%s\n" "add rule inet banIP wan-forward ip6 saddr @${feed} ${log_forwardwan} counter drop"
912 [ -z "${feed_direction##*forwardlan*}" ] && printf "%s\n" "add rule inet banIP lan-forward ip6 daddr @${feed} ${log_forwardlan} counter goto reject-chain"
917 # handle external feeds
919 elif [ "${restore_rc}" != "0" ] && [ "${feed_url}" != "local" ]; then
920 # handle country downloads
922 if [ "${feed%v*}" = "country" ]; then
923 for country
in ${ban_country}; do
924 feed_log
="$("${ban_fetchcmd}" ${ban_fetchparm} "${tmp_raw}" "${feed_url}${country}-aggregated.zone
" 2>&1)"
926 [ "${feed_rc}" = "0" ] && "${ban_catcmd}" "${tmp_raw}" 2>/dev/null >>"${tmp_load}"
930 # handle asn downloads
932 elif [ "${feed%v*}" = "asn" ]; then
933 for asn
in ${ban_asn}; do
934 feed_log
="$("${ban_fetchcmd}" ${ban_fetchparm} "${tmp_raw}" "${feed_url}AS${asn}" 2>&1)"
936 [ "${feed_rc}" = "0" ] && "${ban_catcmd}" "${tmp_raw}" 2>/dev/null >>"${tmp_load}"
940 # handle compressed downloads
942 elif [ "${feed_comp}" = "gz" ]; then
943 feed_log
="$("${ban_fetchcmd}" ${ban_fetchparm} "${tmp_raw}" "${feed_url}" 2>&1)"
945 [ "${feed_rc}" = "0" ] && "${ban_zcatcmd}" "${tmp_raw}" 2>/dev/null >"${tmp_load}"
948 # handle normal downloads
951 feed_log
="$("${ban_fetchcmd}" ${ban_fetchparm} "${tmp_load}" "${feed_url}" 2>&1)"
955 [ "${feed_rc}" != "0" ] && f_log "info" "download for feed '${feed}' failed (rc: ${feed_rc:-"-"}/log: ${feed_log})"
959 if [ "${restore_rc}" != "0" ] && [ "${feed_rc}" = "0" ] && [ "${feed_url}" != "local" ] && [ ! -s "${tmp_nft}" ]; then
960 f_backup
"${feed}" "${tmp_load}"
962 elif [ -z "${restore_rc}" ] && [ "${feed_rc}" != "0" ] && [ "${feed_url}" != "local" ] && [ ! -s "${tmp_nft}" ]; then
963 f_restore
"${feed}" "${feed_url}" "${tmp_load}" "${feed_rc}"
967 # build nft file with Sets and rules for regular downloads
969 if [ "${feed_rc}" = "0" ] && [ ! -s "${tmp_nft}" ]; then
972 if [ "${ban_deduplicate}" = "1" ] && [ "${feed_url}" != "local" ]; then
973 "${ban_awkcmd}" "${feed_rule}" "${tmp_load}" 2>/dev/null >"${tmp_raw}"
974 "${ban_awkcmd}" 'NR==FNR{member[$0];next}!($0 in member)' "${ban_tmpfile}.deduplicate" "${tmp_raw}" 2>/dev/null | tee -a "${ban_tmpfile}.deduplicate" >"${tmp_split}"
976 "${ban_awkcmd}" "${feed_rule}" "${tmp_load}" 2>/dev/null >"${tmp_split}"
982 if [ "${feed_rc}" = "0" ]; then
983 if [ -n "${ban_splitsize//[![:digit]]/}" ] && [ "${ban_splitsize//[![:digit]]/}" -gt "0" ]; then
984 if ! "${ban_awkcmd}" "NR%${ban_splitsize//[![:digit]]/}==1{file=\"${tmp_file}.\"++i;}{ORS=\" \";print > file}" "${tmp_split}" 2>/dev
/null
; then
985 rm -f "${tmp_file}".
*
986 f_log
"info" "can't split Set '${feed}' to size '${ban_splitsize//[![:digit]]/}'"
989 "${ban_awkcmd}" '{ORS=" ";print}' "${tmp_split}" 2>/dev/null >"${tmp_file}.1"
993 rm -f "${tmp_raw}" "${tmp_load}"
994 if [ "${feed_rc}" = "0" ] && [ "${proto}" = "4" ]; then
996 # nft header (IPv4 Set)
998 printf "%s\n\n" "#!/usr/sbin/nft -f"
999 [ -s "${tmp_flush}" ] && "${ban_catcmd}" "${tmp_flush}"
1000 printf "%s\n" "add set inet banIP ${feed} { type ipv4_addr; flags interval; auto-merge; policy ${ban_nftpolicy}; $(f_getelements "${tmp_file}.1") }"
1002 # input and forward rules
1004 if [ "${ban_blocktype}" = "reject" ]; then
1005 [ -z "${feed_direction##*input*}" ] && printf "%s\n" "add rule inet banIP wan-input ${feed_dport} ip saddr @${feed} ${log_input} counter goto reject-chain"
1006 [ -z "${feed_direction##*forwardwan*}" ] && printf "%s\n" "add rule inet banIP wan-forward ${feed_dport} ip saddr @${feed} ${log_forwardwan} counter goto reject-chain"
1008 [ -z "${feed_direction##*input*}" ] && printf "%s\n" "add rule inet banIP wan-input ${feed_dport} ip saddr @${feed} ${log_input} counter drop"
1009 [ -z "${feed_direction##*forwardwan*}" ] && printf "%s\n" "add rule inet banIP wan-forward ${feed_dport} ip saddr @${feed} ${log_forwardwan} counter drop"
1011 [ -z "${feed_direction##*forwardlan*}" ] && printf "%s\n" "add rule inet banIP lan-forward ${feed_dport} ip daddr @${feed} ${log_forwardlan} counter goto reject-chain"
1013 elif [ "${feed_rc}" = "0" ] && [ "${proto}" = "6" ]; then
1015 # nft header (IPv6 Set)
1017 printf "%s\n\n" "#!/usr/sbin/nft -f"
1018 [ -s "${tmp_flush}" ] && "${ban_catcmd}" "${tmp_flush}"
1019 printf "%s\n" "add set inet banIP ${feed} { type ipv6_addr; flags interval; auto-merge; policy ${ban_nftpolicy}; $(f_getelements "${tmp_file}.1") }"
1021 # input and forward rules
1023 if [ "${ban_blocktype}" = "reject" ]; then
1024 [ -z "${feed_direction##*input*}" ] && printf "%s\n" "add rule inet banIP wan-input ${feed_dport} ip6 saddr @${feed} ${log_input} counter goto reject-chain"
1025 [ -z "${feed_direction##*forwardwan*}" ] && printf "%s\n" "add rule inet banIP wan-forward ${feed_dport} ip6 saddr @${feed} ${log_forwardwan} counter goto reject-chain"
1027 [ -z "${feed_direction##*input*}" ] && printf "%s\n" "add rule inet banIP wan-input ${feed_dport} ip6 saddr @${feed} ${log_input} counter drop"
1028 [ -z "${feed_direction##*forwardwan*}" ] && printf "%s\n" "add rule inet banIP wan-forward ${feed_dport} ip6 saddr @${feed} ${log_forwardwan} counter drop"
1030 [ -z "${feed_direction##*forwardlan*}" ] && printf "%s\n" "add rule inet banIP lan-forward ${feed_dport} ip6 daddr @${feed} ${log_forwardlan} counter goto reject-chain"
1035 # load generated nft file in banIP table
1037 if [ "${feed_rc}" = "0" ]; then
1038 if [ "${feed%v*}" = "allowlist" ]; then
1039 cnt_dl
="$("${ban_awkcmd}" 'END{printf "%d
",NR}' "${tmp_allow}" 2>/dev/null)"
1041 cnt_dl
="$("${ban_awkcmd}" 'END{printf "%d
",NR}' "${tmp_split}" 2>/dev/null)"
1043 if [ "${cnt_dl:-"0"}" -gt "0" ] || [ "${feed_url}" = "local" ] || [ "${feed%v*}" = "allowlist" ] || [ "${feed%v*}" = "blocklist" ]; then
1044 feed_log
="$("${ban_nftcmd}" -f "${tmp_nft}" 2>&1)"
1047 # load additional split files
1049 if [ "${feed_rc}" = "0" ]; then
1050 for split_file
in "${tmp_file}".
*; do
1051 [ ! -f "${split_file}" ] && break
1052 if [ "${split_file##*.}" = "1" ]; then
1053 rm -f "${split_file}"
1056 if ! "${ban_nftcmd}" add element inet banIP "${feed}" "{ $("${ban_catcmd}" "${split_file}") }" >/dev
/null
2>&1; then
1057 f_log
"info" "can't add split file '${split_file##*.}' to Set '${feed}'"
1059 rm -f "${split_file}"
1061 if [ "${ban_debug}" = "1" ] && [ "${ban_reportelements}" = "1" ]; then
1062 cnt_set
="$("${ban_nftcmd}" -j list set inet banIP "${feed}" 2>/dev/null | "${ban_jsoncmd}" -qe '@.nftables[*].set.elem[*]' | wc -l 2>/dev/null)"
1066 f_log
"info" "skip empty feed '${feed}'"
1069 rm -f "${tmp_split}" "${tmp_nft}"
1070 end_ts
="$(date +%s)"
1072 f_log
"debug" "f_down ::: feed: ${feed}, cnt_dl: ${cnt_dl:-"-"}, cnt_set: ${cnt_set:-"-"}, split_size: ${ban_splitsize:-"-"}, time: $((end_ts - start_ts)), rc: ${feed_rc:-"-"}, log: ${feed_log:-"-"}"
1078 local backup_rc
="4" feed
="${1}" feed_file
="${2}"
1080 if [ -s "${feed_file}" ]; then
1081 gzip -cf "${feed_file}" >"${ban_backupdir}/banIP.${feed}.gz"
1085 f_log
"debug" "f_backup ::: feed: ${feed}, file: banIP.${feed}.gz, rc: ${backup_rc}"
1086 return "${backup_rc}"
1092 local tmp_feed restore_rc
="4" feed
="${1}" feed_url="${2}" feed_file="${3}" in_rc="${4}"
1094 [ "${feed_url}" = "local" ] && tmp_feed="${feed%v*}v4" || tmp_feed="${feed}"
1095 if [ -s "${ban_backupdir}/banIP.${tmp_feed}.gz" ]; then
1096 "${ban_zcatcmd}" "${ban_backupdir}/banIP.${tmp_feed}.gz" 2>/dev/null >"${feed_file}"
1100 f_log
"debug" "f_restore ::: feed: ${feed}, file: banIP.${tmp_feed}.gz, in_rc: ${in_rc:-"-"}, rc: ${restore_rc}"
1101 return "${restore_rc}"
1104 # remove disabled Sets
1107 local expr feedlist tmp_del ruleset_raw item table_sets handle del_set feed_log feed_rc
1110 json_get_keys feedlist
1111 tmp_del
="${ban_tmpfile}.final.delete"
1112 ruleset_raw
="$("${ban_nftcmd}" -tj list ruleset 2>/dev/null)"
1113 table_sets
="$(printf "%s
\n" "${ruleset_raw}" | "${ban_jsoncmd}" -qe '@.nftables[@.set.table="banIP
"].set.name')"
1115 printf "%s\n\n" "#!/usr/sbin/nft -f"
1116 for item
in ${table_sets}; do
1117 if ! printf "%s" "allowlist blocklist ${ban_feed}" | "${ban_grepcmd}" -q "${item%v*}" ||
1118 ! printf "%s" "allowlist blocklist ${feedlist}" | "${ban_grepcmd}" -q "${item%v*}"; then
1119 del_set
="${del_set}${item}, "
1120 rm -f "${ban_backupdir}/banIP.${item}.gz"
1121 printf "%s\n" "flush set inet banIP ${item}"
1123 handle
="$(printf "%s
\n" "${ruleset_raw}" | "${ban_jsoncmd}" -ql1 -e "@.nftables[@.rule.table=\"banIP\"&&@.rule.chain=\"wan-input\"][@.expr[${expr}].match.right=\"@${item}\"].handle
")"
1124 [ -n "${handle}" ] && printf "%s\n" "delete rule inet banIP wan-input handle ${handle}"
1125 handle
="$(printf "%s
\n" "${ruleset_raw}" | "${ban_jsoncmd}" -ql1 -e "@.nftables[@.rule.table=\"banIP\"&&@.rule.chain=\"wan-forward\"][@.expr[${expr}].match.right=\"@${item}\"].handle
")"
1126 [ -n "${handle}" ] && printf "%s\n" "delete rule inet banIP wan-forward handle ${handle}"
1127 handle
="$(printf "%s
\n" "${ruleset_raw}" | "${ban_jsoncmd}" -ql1 -e "@.nftables[@.rule.table=\"banIP\"&&@.rule.chain=\"lan-forward\"][@.expr[${expr}].match.right=\"@${item}\"].handle
")"
1128 [ -n "${handle}" ] && printf "%s\n" "delete rule inet banIP lan-forward handle ${handle}"
1130 printf "%s\n\n" "delete set inet banIP ${item}"
1135 if [ -n "${del_set}" ]; then
1136 del_set
="$(f_trim "${del_set}")"
1137 feed_log
="$("${ban_nftcmd}" -f "${tmp_del}" 2>&1)"
1142 f_log
"debug" "f_rmset ::: sets: ${del_set:-"-"}, rc: ${feed_rc:-"-"}, log: ${feed_log:-"-"}"
1145 # generate status information
1148 local object end_time duration table_sets cnt_elements
="0" custom_feed
="0" split="0" status
="${1}"
1150 [ -z "${ban_dev}" ] && f_conf
1151 if [ "${status}" = "active" ]; then
1152 if [ -n "${ban_starttime}" ] && [ "${ban_action}" != "boot" ]; then
1153 end_time
="$(date "+%s
")"
1154 duration
="$(((end_time - ban_starttime) / 60))m $(((end_time - ban_starttime) % 60))s"
1156 table_sets
="$("${ban_nftcmd}" -tj list ruleset 2>/dev/null | "${ban_jsoncmd}" -qe '@.nftables[@.set.table="banIP
"].set.name')"
1157 if [ "${ban_reportelements}" = "1" ]; then
1158 for object
in ${table_sets}; do
1159 cnt_elements
="$((cnt_elements + $("${ban_nftcmd}" -j list set inet banIP "${object}" 2>/dev/null | "${ban_jsoncmd}" -qe '@.nftables[*].set.elem[*]' | wc -l 2>/dev/null)))"
1162 runtime
="action: ${ban_action:-"-"}, log: ${ban_logreadcmd##*/}, fetch: ${ban_fetchcmd##*/}, duration: ${duration:-"-"}, date: $(date "+%Y-
%m-
%d
%H
:%M
:%S
")"
1164 [ -s "${ban_customfeedfile}" ] && custom_feed
="1"
1165 [ "${ban_splitsize:-"0"}" -gt "0" ] && split="1"
1169 json_load_file
"${ban_rtfile}" >/dev
/null
2>&1
1170 json_add_string
"status" "${status}"
1171 json_add_string
"version" "${ban_ver}"
1172 json_add_string
"element_count" "${cnt_elements}"
1173 json_add_array
"active_feeds"
1174 for object
in ${table_sets:-"-"}; do
1175 json_add_string
"${object}" "${object}"
1178 json_add_array
"wan_devices"
1179 for object
in ${ban_dev:-"-"}; do
1180 json_add_string
"${object}" "${object}"
1183 json_add_array
"wan_interfaces"
1184 for object
in ${ban_ifv4:-"-"} ${ban_ifv6:-"-"}; do
1185 json_add_string
"${object}" "${object}"
1188 json_add_array
"vlan_allow"
1189 for object
in ${ban_vlanallow:-"-"}; do
1190 json_add_string
"${object}" "${object}"
1193 json_add_array
"vlan_block"
1194 for object
in ${ban_vlanblock:-"-"}; do
1195 json_add_string
"${object}" "${object}"
1198 json_add_array
"active_uplink"
1199 for object
in ${ban_uplink:-"-"}; do
1200 json_add_string
"${object}" "${object}"
1203 json_add_string
"nft_info" "priority: ${ban_nftpriority}, policy: ${ban_nftpolicy}, loglevel: ${ban_nftloglevel}, expiry: ${ban_nftexpiry:-"-"}"
1204 json_add_string
"run_info" "base: ${ban_basedir}, backup: ${ban_backupdir}, report: ${ban_reportdir}"
1205 json_add_string
"run_flags" "auto: $(f_char ${ban_autodetect}), proto (4/6): $(f_char ${ban_protov4})/$(f_char ${ban_protov6}), log (wan-inp/wan-fwd/lan-fwd): $(f_char ${ban_loginput})/$(f_char ${ban_logforwardwan})/$(f_char ${ban_logforwardlan}), dedup: $(f_char ${ban_deduplicate}), split: $(f_char ${split}), custom feed: $(f_char ${custom_feed}), allowed only: $(f_char ${ban_allowlistonly})"
1206 json_add_string
"last_run" "${runtime:-"-"}"
1207 json_add_string
"system_info" "cores: ${ban_cores}, memory: ${ban_memory}, device: ${ban_sysver}"
1208 json_dump
>"${ban_rtfile}"
1211 # get status information
1214 local key keylist value values
1216 [ -z "${ban_dev}" ] && f_conf
1217 json_load_file
"${ban_rtfile}" >/dev
/null
2>&1
1218 if json_get_keys keylist
; then
1219 printf "%s\n" "::: banIP runtime information"
1220 for key
in ${keylist}; do
1221 if [ "${key}" = "active_feeds" ] ||
[ "${key}" = "active_uplink" ]; then
1222 json_get_values values
"${key}" >/dev
/null
2>&1
1223 value
="${values// /, }"
1224 elif [ "${key}" = "wan_devices" ]; then
1225 json_get_values values
"${key}" >/dev
/null
2>&1
1226 value
="wan: ${values// /, } / "
1227 json_get_values values
"wan_interfaces" >/dev
/null
2>&1
1228 value
="${value}wan-if: ${values// /, } / "
1229 json_get_values values
"vlan_allow" >/dev
/null
2>&1
1230 value
="${value}vlan-allow: ${values// /, } / "
1231 json_get_values values
"vlan_block" >/dev
/null
2>&1
1232 value
="${value}vlan-block: ${values// /, }"
1233 key
="active_devices"
1235 json_get_var value
"${key}" >/dev
/null
2>&1
1236 if [ "${key}" = "status" ]; then
1237 value
="${value} ($(f_actual))"
1240 if [ "${key}" != "wan_interfaces" ] && [ "${key}" != "vlan_allow" ] && [ "${key}" != "vlan_block" ]; then
1241 printf " + %-17s : %s\n" "${key}" "${value:-"-"}"
1245 printf "%s\n" "::: no banIP runtime information available"
1252 local cnt list domain lookup ip elementsv4 elementsv6 start_time end_time duration cnt_domain
="0" cnt_ip
="0" feed
="${1}"
1254 [ -z "${ban_dev}" ] && f_conf
1255 start_time
="$(date "+%s
")"
1256 if [ "${feed}" = "allowlist" ]; then
1257 list
="$("${ban_awkcmd}" '/^([[:alnum:]_-]{1,63}\.)+[[:alpha:]]+([[:space:]]|$)/{printf "%s
",tolower($1)}' "${ban_allowlist}" 2>/dev/null)"
1258 elif [ "${feed}" = "blocklist" ]; then
1259 list
="$("${ban_awkcmd}" '/^([[:alnum:]_-]{1,63}\.)+[[:alpha:]]+([[:space:]]|$)/{printf "%s
",tolower($1)}' "${ban_blocklist}" 2>/dev/null)"
1262 for domain
in ${list}; do
1263 lookup
="$("${ban_lookupcmd}" "${domain}" ${ban_resolver} 2>/dev/null | "${ban_awkcmd}" '/^Address[ 0-9]*: /{if(!seen[$NF]++)printf "%s ",$NF}' 2>/dev/null)"
1264 for ip in ${lookup}; do
1265 if [ "${ip%%.*}" = "0" ] || [ -z "${ip%%::*}" ]; then
1268 if { [ "${feed}" = "allowlist" ] && ! "${ban_grepcmd}" -q "^${ip}" "${ban_allowlist}"; } ||
1269 { [ "${feed}" = "blocklist" ] && ! "${ban_grepcmd}" -q "^${ip}" "${ban_blocklist}"; }; then
1270 if [ "${ip##*:}" = "${ip}" ]; then
1271 elementsv4="${elementsv4} ${ip},"
1273 elementsv6="${elementsv6} ${ip},"
1275 if [ "${feed}" = "allowlist" ] && [ "${ban_autoallowlist}" = "1" ]; then
1276 printf "%-42s%s\n" "${ip}" "# '${domain}' added on $(date "+%Y-%m-%d %H:%M:%S")" >>"${ban_allowlist}"
1277 elif [ "${feed}" = "blocklist" ] && [ "${ban_autoblocklist}" = "1" ]; then
1278 printf "%-42s%s\n" "${ip}" "# '${domain}' added on $(date "+%Y-%m-%d %H:%M:%S")" >>"${ban_blocklist}"
1280 cnt_ip="$((cnt_ip + 1))"
1284 cnt_domain="$((cnt_domain + 1))"
1286 if [ -n "${elementsv4}" ]; then
1287 if ! "${ban_nftcmd}" add element inet banIP "${feed}v4" "{ ${elementsv4} }" >/dev/null 2>&1; then
1288 f_log "info" "can't add lookup
file to Set
'${feed}v4'"
1291 if [ -n "${elementsv6}" ]; then
1292 if ! "${ban_nftcmd}" add element inet banIP "${feed}v6" "{ ${elementsv6} }" >/dev/null 2>&1; then
1293 f_log "info
" "can
't add lookup file to Set '${feed}v6
'"
1296 end_time="$(date "+%s")"
1297 duration="$(((end_time - start_time) / 60))m $(((end_time - start_time) % 60))s"
1299 f_log "debug" "f_lookup ::: feed: ${feed}, domains: ${cnt_domain}, IPs: ${cnt_ip}, duration: ${duration}"
1305 local report_jsn report_txt tmp_val ruleset_raw item table_sets set_cnt set_input set_forwardwan set_forwardlan set_cntinput set_cntforwardwan set_cntforwardlan set_proto set_dport set_details
1306 local expr detail jsnval timestamp autoadd_allow autoadd_block sum_sets sum_setinput sum_setforwardwan sum_setforwardlan sum_setelements sum_cntinput sum_cntforwardwan sum_cntforwardlan output="${1}"
1308 [ -z "${ban_dev}" ] && f_conf
1309 f_mkdir "${ban_reportdir}"
1310 report_jsn="${ban_reportdir}/ban_report.jsn"
1311 report_txt="${ban_reportdir}/ban_report.txt"
1313 # json output preparation
1315 ruleset_raw="$("${ban_nftcmd}" -tj list ruleset 2>/dev/null)"
1316 table_sets="$(printf "%s" "${ruleset_raw}" | "${ban_jsoncmd}" -qe '@.nftables
[@.
set.table
="banIP"].
set.name
')"
1319 sum_setforwardwan="0"
1320 sum_setforwardlan="0"
1323 sum_cntforwardwan="0"
1324 sum_cntforwardlan="0"
1325 timestamp="$(date "+%Y-%m-%d %H:%M:%S")"
1329 printf "\t%s\n" '"sets":{'
1330 for item in ${table_sets}; do
1332 set_cntforwardwan=""
1333 set_cntforwardlan=""
1337 [ -z "${set_cntinput}" ] && set_cntinput="$(printf "%s" "${ruleset_raw}" | "${ban_jsoncmd}" -ql1 -e "@.nftables[@.rule.table=\"banIP\"&&@.rule.chain=\"wan-input\"][@.expr[${expr}].match.right=\"@${item}\"].expr[*].counter.packets")"
1338 [ "${expr}" = "1" ] && [ -z "${set_dport}" ] && set_dport="$(printf "%s" "${ruleset_raw}" | "${ban_jsoncmd}" -ql1 -e "@.nftables[@.rule.table=\"banIP\"&&@.rule.chain=\"wan-input\"][@.expr[${expr}].match.right=\"@${item}\"].expr[*].match.right.set")"
1339 [ "${expr}" = "1" ] && [ -z "${set_proto}" ] && set_proto="$(printf "%s" "${ruleset_raw}" | "${ban_jsoncmd}" -ql1 -e "@.nftables[@.rule.table=\"banIP\"&&@.rule.chain=\"wan-input\"][@.expr[${expr}].match.right=\"@${item}\"].expr[*].match.left.payload.protocol")"
1340 [ -z "${set_cntforwardwan}" ] && set_cntforwardwan="$(printf "%s" "${ruleset_raw}" | "${ban_jsoncmd}" -ql1 -e "@.nftables[@.rule.table=\"banIP\"&&@.rule.chain=\"wan-forward\"][@.expr[${expr}].match.right=\"@${item}\"].expr[*].counter.packets")"
1341 [ "${expr}" = "1" ] && [ -z "${set_dport}" ] && set_dport="$(printf "%s" "${ruleset_raw}" | "${ban_jsoncmd}" -ql1 -e "@.nftables[@.rule.table=\"banIP\"&&@.rule.chain=\"wan-forward\"][@.expr[${expr}].match.right=\"@${item}\"].expr[*].match.right.set")"
1342 [ "${expr}" = "1" ] && [ -z "${set_proto}" ] && set_proto="$(printf "%s" "${ruleset_raw}" | "${ban_jsoncmd}" -ql1 -e "@.nftables[@.rule.table=\"banIP\"&&@.rule.chain=\"wan-forward\"][@.expr[${expr}].match.right=\"@${item}\"].expr[*].match.left.payload.protocol")"
1343 [ -z "${set_cntforwardlan}" ] && set_cntforwardlan="$(printf "%s" "${ruleset_raw}" | "${ban_jsoncmd}" -ql1 -e "@.nftables[@.rule.table=\"banIP\"&&@.rule.chain=\"lan-forward\"][@.expr[${expr}].match.right=\"@${item}\"].expr[*].counter.packets")"
1344 [ "${expr}" = "1" ] && [ -z "${set_dport}" ] && set_dport="$(printf "%s" "${ruleset_raw}" | "${ban_jsoncmd}" -ql1 -e "@.nftables[@.rule.table=\"banIP\"&&@.rule.chain=\"lan-forward\"][@.expr[${expr}].match.right=\"@${item}\"].expr[*].match.right.set")"
1345 [ "${expr}" = "1" ] && [ -z "${set_proto}" ] && set_proto="$(printf "%s" "${ruleset_raw}" | "${ban_jsoncmd}" -ql1 -e "@.nftables[@.rule.table=\"banIP\"&&@.rule.chain=\"lan-forward\"][@.expr[${expr}].match.right=\"@${item}\"].expr[*].match.left.payload.protocol")"
1347 if [ -n "${set_dport}" ]; then
1348 set_dport="${set_dport//[\{\}\":]/}"
1349 set_dport="${set_dport#\[ *}"
1350 set_dport="${set_dport%* \]}"
1351 set_dport="${set_proto}: $(f_trim "${set_dport}")"
1353 if [ "${ban_reportelements}" = "1" ]; then
1354 set_cnt="$("${ban_nftcmd}" -j list set inet banIP "${item}" 2>/dev/null | "${ban_jsoncmd}" -qe '@.nftables
[*].
set.elem
[*]' | wc -l 2>/dev/null)"
1355 sum_setelements="$((sum_setelements + set_cnt))"
1358 sum_setelements="n/a"
1360 if [ -n "${set_cntinput}" ]; then
1362 sum_setinput="$((sum_setinput + 1))"
1363 sum_cntinput="$((sum_cntinput + set_cntinput))"
1368 if [ -n "${set_cntforwardwan}" ]; then
1370 sum_setforwardwan="$((sum_setforwardwan + 1))"
1371 sum_cntforwardwan="$((sum_cntforwardwan + set_cntforwardwan))"
1374 set_cntforwardwan=""
1376 if [ -n "${set_cntforwardlan}" ]; then
1378 sum_setforwardlan="$((sum_setforwardlan + 1))"
1379 sum_cntforwardlan="$((sum_cntforwardlan + set_cntforwardlan))"
1382 set_cntforwardlan=""
1384 [ "${sum_sets}" -gt "0" ] && printf "%s\n" ","
1385 printf "\t\t%s\n" "\"${item}\":{"
1386 printf "\t\t\t%s\n" "\"cnt_elements\": \"${set_cnt}\","
1387 printf "\t\t\t%s\n" "\"cnt_input\": \"${set_cntinput}\","
1388 printf "\t\t\t%s\n" "\"input\": \"${set_input}\","
1389 printf "\t\t\t%s\n" "\"cnt_forwardwan\": \"${set_cntforwardwan}\","
1390 printf "\t\t\t%s\n" "\"wan_forward\": \"${set_forwardwan}\","
1391 printf "\t\t\t%s\n" "\"cnt_forwardlan\": \"${set_cntforwardlan}\","
1392 printf "\t\t\t%s\n" "\"lan_forward\": \"${set_forwardlan}\"",
1393 printf "\t\t\t%s\n" "\"port\": \"${set_dport:-"-"}\""
1395 sum_sets="$((sum_sets + 1))"
1397 printf "\n\t%s\n" "},"
1398 printf "\t%s\n" "\"timestamp\": \"${timestamp}\","
1399 printf "\t%s\n" "\"autoadd_allow\": \"$("${ban_grepcmd}" -c "added on ${timestamp% *}" "${ban_allowlist}")\","
1400 printf "\t%s\n" "\"autoadd_block\": \"$("${ban_grepcmd}" -c "added on ${timestamp% *}" "${ban_blocklist}")\","
1401 printf "\t%s\n" "\"sum_sets\": \"${sum_sets}\","
1402 printf "\t%s\n" "\"sum_setinput\": \"${sum_setinput}\","
1403 printf "\t%s\n" "\"sum_setforwardwan\": \"${sum_setforwardwan}\","
1404 printf "\t%s\n" "\"sum_setforwardlan\": \"${sum_setforwardlan}\","
1405 printf "\t%s\n" "\"sum_setelements\": \"${sum_setelements}\","
1406 printf "\t%s\n" "\"sum_cntinput\": \"${sum_cntinput}\","
1407 printf "\t%s\n" "\"sum_cntforwardwan\": \"${sum_cntforwardwan}\","
1408 printf "\t%s\n" "\"sum_cntforwardlan\": \"${sum_cntforwardlan}\""
1412 # text output preparation
1414 if [ "${output}" != "json" ] && [ -s "${report_jsn}" ]; then
1417 if json_load_file "${report_jsn}" >/dev/null 2>&1; then
1418 json_get_var timestamp "timestamp" >/dev/null 2>&1
1419 json_get_var autoadd_allow "autoadd_allow" >/dev/null 2>&1
1420 json_get_var autoadd_block "autoadd_block" >/dev/null 2>&1
1421 json_get_var sum_sets "sum_sets" >/dev/null 2>&1
1422 json_get_var sum_setinput "sum_setinput" >/dev/null 2>&1
1423 json_get_var sum_setforwardwan "sum_setforwardwan" >/dev/null 2>&1
1424 json_get_var sum_setforwardlan "sum_setforwardlan" >/dev/null 2>&1
1425 json_get_var sum_setelements "sum_setelements" >/dev/null 2>&1
1426 json_get_var sum_cntinput "sum_cntinput" >/dev/null 2>&1
1427 json_get_var sum_cntforwardwan "sum_cntforwardwan" >/dev/null 2>&1
1428 json_get_var sum_cntforwardlan "sum_cntforwardlan" >/dev/null 2>&1
1430 printf "%s\n%s\n%s\n" ":::" "::: banIP Set Statistics" ":::"
1431 printf "%s\n" " Timestamp: ${timestamp}"
1432 printf "%s\n" " ------------------------------"
1433 printf "%s\n" " auto-added to allowlist today: ${autoadd_allow}"
1434 printf "%s\n\n" " auto-added to blocklist today: ${autoadd_block}"
1435 json_select "sets" >/dev/null 2>&1
1436 json_get_keys table_sets >/dev/null 2>&1
1437 if [ -n "${table_sets}" ]; then
1438 printf "%-25s%-15s%-24s%-24s%-24s%s\n" " Set" "| Elements" "| WAN-Input (packets)" "| WAN-Forward (packets)" "| LAN-Forward (packets)" "| Port/Protocol Limit"
1439 printf "%s\n" " ---------------------+--------------+-----------------------+-----------------------+-----------------------+------------------------"
1440 for item in ${table_sets}; do
1441 printf " %-21s" "${item}"
1442 json_select "${item}"
1443 json_get_keys set_details
1444 for detail in ${set_details}; do
1445 json_get_var jsnval "${detail}" >/dev/null 2>&1
1448 printf "%-15s" "| ${jsnval}"
1450 "cnt_input" | "cnt_forwardwan" | "cnt_forwardlan")
1451 [ -n "${jsnval}" ] && tmp_val=": ${jsnval}"
1454 printf "%-24s" "| ${jsnval}${tmp_val}"
1462 printf "%s\n" " ---------------------+--------------+-----------------------+-----------------------+-----------------------+------------------------"
1463 printf "%-25s%-15s%-24s%-24s%s\n" " ${sum_sets}" "| ${sum_setelements}" "| ${sum_setinput} (${sum_cntinput})" "| ${sum_setforwardwan} (${sum_cntforwardwan})" "| ${sum_setforwardlan} (${sum_cntforwardlan})"
1469 # output channel (text|json|mail)
1473 [ -s "${report_txt}" ] && "${ban_catcmd}" "${report_txt}"
1476 [ -s "${report_jsn}" ] && "${ban_catcmd}" "${report_jsn}"
1479 [ -n "${ban_mailreceiver}" ] && [ -x "${ban_mailcmd}" ] && f_mail
1482 rm -f "${report_txt}"
1488 local item table_sets ip proto hold cnt result_flag="/var/run/banIP.search" input="${1}"
1490 if [ -n "${input}" ]; then
1491 ip="$(printf "%s" "${input}" | "${ban_awkcmd}" 'BEGIN{RS="(([0-9]{1,3}\\.){3}(1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])(\/(1?[0-9]|2?[0-9]|3?[0-2]))?[[:space:]]*$)"}{printf "%s",RT}')"
1492 [ -n "${ip}" ] && proto="v4
"
1493 if [ -z "${proto}" ]; then
1494 ip="$
(printf "%s" "${input}" | "${ban_awkcmd}" 'BEGIN{RS="(([0-9A-f]{0,4}:){1,7}[0-9A-f]{0,4}:?(\/(1?[0-2][0-8]|[0-9][0-9]))?)([[:space:]].*|$)"}{printf "%s",RT
}')"
1495 [ -n "${ip}" ] && proto="v6"
1498 if [ -n "${proto}" ]; then
1499 table_sets="$("${ban_nftcmd}" -tj list ruleset 2>/dev/null | "${ban_jsoncmd}" -qe "@.nftables[@.set.table=\"banIP\"&&@.set.type=\"ip${proto}_addr\"].set.name")"
1501 printf "%s\n%s\n%s\n" ":::" "::: no valid search input" ":::"
1504 printf "%s\n%s\n%s\n" ":::" "::: banIP Search" ":::"
1505 printf " %s\n" "Looking for IP '${ip}' on $(date "+%Y-%m-%d %H:%M:%S")"
1506 printf " %s\n" "---"
1508 for item in ${table_sets}; do
1509 [ -f "${result_flag}" ] && break
1511 if "${ban_nftcmd}" get element inet banIP "${item}" "{ ${ip} }" >/dev/null 2>&1; then
1512 printf " %s\n" "IP found in Set '${item}'"
1516 hold="$((cnt % ban_cores))"
1517 [ "${hold}" = "0" ] && wait
1521 [ -f "${result_flag}" ] && rm -f "${result_flag}" || printf " %s\n" "IP not found"
1527 local set_elements input="${1}"
1529 if [ -z "${input}" ]; then
1530 printf "%s\n%s\n%s\n" ":::" "::: no valid survey input" ":::"
1533 set_elements="$("${ban_nftcmd}" -j list set inet banIP "${input}" 2>/dev/null | "${ban_jsoncmd}" -qe '@.nftables
[*].
set.elem
[*]')"
1534 printf "%s\n%s\n%s\n" ":::" "::: banIP Survey" ":::"
1535 printf " %s\n" "List of elements in the Set '${input}' on $(date "+%Y-%m-%d %H:%M:%S")"
1536 printf " %s\n" "---"
1537 [ -n "${set_elements}" ] && printf "%s\n" "${set_elements}" || printf " %s\n" "empty Set"
1545 # load mail template
1547 if [ -r "${ban_mailtemplate}" ]; then
1548 . "${ban_mailtemplate}"
1550 f_log "info" "no mail template"
1552 [ -z "${mail_text}" ] && f_log "info" "no mail content"
1553 [ "${ban_debug}" = "1" ] && msmtp_debug="--debug"
1557 ban_mailhead="From: ${ban_mailsender}\nTo: ${ban_mailreceiver}\nSubject: ${ban_mailtopic}\nReply-to: ${ban_mailsender}\nMime-Version: 1.0\nContent-Type: text/html;charset=utf-8\nContent-Disposition: inline\n\n"
1558 printf "%b" "${ban_mailhead}${mail_text}" | "${ban_mailcmd}" --timeout=10 ${msmtp_debug} -a "${ban_mailprofile}" "${ban_mailreceiver}" >/dev/null 2>&1
1559 f_log "info" "send status mail (${?})"
1561 f_log "debug" "f_mail ::: notification: ${ban_mailnotification}, template: ${ban_mailtemplate}, profile: ${ban_mailprofile}, receiver: ${ban_mailreceiver}, rc: ${?}"
1567 local daemon logread_cmd loglimit_cmd nft_expiry line proto ip log_raw log_count rdap_log rdap_rc rdap_elements rdap_info
1569 if [ -f "${ban_logreadfile}" ]; then
1570 logread_cmd="${ban_logreadcmd} -qf ${ban_logreadfile} 2>/dev/null | ${ban_grepcmd} -e \"${ban_logterm%%??}\" 2>/dev/null"
1571 loglimit_cmd="${ban_logreadcmd} -qn ${ban_loglimit} ${ban_logreadfile} 2>/dev/null"
1572 elif printf "%s" "${ban_packages}" | "${ban_grepcmd}" -q '"logd'; then
1573 logread_cmd="${ban_logreadcmd} -fe \"${ban_logterm%%??}\" 2>/dev
/null
"
1574 loglimit_cmd="${ban_logreadcmd} -l ${ban_loglimit} 2>/dev
/null
"
1577 if [ -x "${ban_logreadcmd}" ] && [ -n "${logread_cmd}" ] && [ -n "${loglimit_cmd}" ] && [ -n "${ban_logterm%%??}" ] && [ "${ban_loglimit}" != "0" ]; then
1578 f_log "info
" "start detached banIP log service
(${ban_logreadcmd})"
1579 [ -n "${ban_nftexpiry}" ] && nft_expiry="timeout $(printf "%s" "${ban_nftexpiry}" | "${ban_grepcmd}" -oE "([0-9]+[d|h|m|s
])+$
")"
1580 eval "${logread_cmd}" |
1581 while read -r line
; do
1583 : >"${ban_rdapfile}"
1584 if [ -z "${daemon}" ]; then
1585 daemon
="$(printf "%s
" "${line}" | "${ban_awkcmd}" 'BEGIN{RS="dropbear"}{if(!seen
[RT
]++)printf "%s",RT
}')"
1586 [ -z "${daemon}" ] && daemon="sshd"
1588 ip="$(printf "%s" "${line}" | "${ban_awkcmd}" 'BEGIN{RS="(([0-9]{1,3}\\.){3}[0-9]{1,3})+"}{if(!seen[RT]++)printf "%s ",RT}')"
1589 ip="$
(f_trim
"${ip}")"
1591 [ -n "${ip}" ] && proto="v4
"
1592 if [ -z "${proto}" ]; then
1593 if [ "${daemon}" = "dropbear
" ]; then
1594 ip="$
(printf "%s" "${line}" | "${ban_awkcmd}" 'BEGIN{RS="([A-Fa-f0-9]{1,4}::?){3,7}([A-Fa-f0-9]:?)+"}{if(!seen
[RT
]++)printf "%s ",RT
}')"
1597 ip="$(printf "%s" "${line}" | "${ban_awkcmd}" 'BEGIN{RS="([A-Fa-f0-9]{1,4}::?){3,7}[A-Fa-f0-9]{1,4}"}{if(!seen[RT]++)printf "%s ",RT}')"
1599 ip="$
(f_trim
"${ip}")"
1601 [ -n "${ip}" ] && proto="v6
"
1603 if [ -n "${proto}" ] && ! "${ban_nftcmd}" get element inet banIP allowlist"${proto}" "{ ${ip} }" >/dev/null 2>&1 && ! "${ban_nftcmd}" get element inet banIP blocklist"${proto}" "{ ${ip} }" >/dev/null 2>&1; then
1604 f_log "info
" "suspicious IP
'${ip}'"
1605 log_raw="$
(eval ${loglimit_cmd})"
1606 log_count="$
(printf "%s\n" "${log_raw}" | "${ban_grepcmd}" -c "suspicious IP '${ip}'")"
1607 if [ "${log_count}" -ge "${ban_logcount}" ]; then
1608 if [ "${ban_autoblocksubnet}" = "1" ]; then
1609 rdap_log="$
("${ban_fetchcmd}" ${ban_rdapparm} "${ban_rdapfile}" "${ban_rdapurl}${ip}" 2>&1)"
1611 if [ "${rdap_rc}" = "0" ] && [ -s "${ban_rdapfile}" ]; then
1612 rdap_elements="$
(jsonfilter
-i "${ban_rdapfile}" -qe '@.cidr0_cidrs.*' |
awk 'BEGIN{FS="[\" ]"}{printf "%s/%s, ",$6,$11}')"
1613 rdap_info="$
(jsonfilter
-i "${ban_rdapfile}" -qe '@.country' -qe '@.notices[@.title="Source"].description[1]' |
awk 'BEGIN{RS="";FS="\n"}{printf "%s, %s",$1,$2}')"
1614 if [ -n "${rdap_elements//\/*/}" ]; then
1615 if "${ban_nftcmd}" add element inet banIP "blocklist${proto}" "{ ${rdap_elements%%??} ${nft_expiry} }" >/dev/null 2>&1; then
1616 f_log "info
" "add IP range
'${rdap_elements%%??}' (source: ${rdap_info:-"-"} ::: expiry: ${ban_nftexpiry:-"-"}) to blocklist${proto} set"
1620 f_log "info" "rdap request failed (rc: ${rdap_rc:-"-"}/log: ${rdap_log})"
1623 if [ "${ban_autoblocksubnet}" = "0" ] || [ "${rdap_rc}" != "0" ] || [ ! -s "${ban_rdapfile}" ] || [ -z "${rdap_elements//\/*/}" ]; then
1624 if "${ban_nftcmd}" add element inet banIP "blocklist${proto}" "{ ${ip} ${nft_expiry} }" >/dev/null 2>&1; then
1625 f_log "info" "add IP '${ip}' (expiry: ${ban_nftexpiry:-"-"}) to blocklist${proto} set"
1628 if [ -z "${ban_nftexpiry}" ] && [ "${ban_autoblocklist}" = "1" ] && ! "${ban_grepcmd}" -q "^${ip}" "${ban_blocklist}"; then
1629 printf "%-42s%s
\n" "${ip}" "# added on $(date "+%Y-%m-%d %H:%M:%S")" >>"${ban_blocklist}"
1630 f_log
"info" "add IP '${ip}' to local blocklist"
1636 f_log
"info" "start detached no-op banIP service"
1643 if [ -r "/lib/functions.sh" ] && [ -r "/lib/functions/network.sh" ] && [ -r "/usr/share/libubox/jshn.sh" ]; then
1644 .
"/lib/functions.sh"
1645 .
"/lib/functions/network.sh"
1646 .
"/usr/share/libubox/jshn.sh"
1648 f_log
"emerg" "system libraries not found"
1651 # initial system calls
1653 ban_awkcmd
="$(f_cmd gawk awk)"
1654 ban_catcmd
="$(f_cmd cat)"
1655 ban_fw4cmd
="$(f_cmd fw4)"
1656 ban_grepcmd
="$(f_cmd grep)"
1657 ban_jsoncmd
="$(f_cmd jsonfilter)"
1658 ban_logcmd
="$(f_cmd logger)"
1659 ban_lookupcmd
="$(f_cmd nslookup)"
1660 ban_mailcmd
="$(f_cmd msmtp true)"
1661 ban_nftcmd
="$(f_cmd nft)"
1662 ban_pgrepcmd
="$(f_cmd pgrep)"
1663 ban_sedcmd
="$(f_cmd sed)"
1664 ban_ubuscmd
="$(f_cmd ubus)"
1665 ban_zcatcmd
="$(f_cmd zcat)"
1667 if [ "${ban_action}" != "stop" ]; then
1668 [ ! -d "/etc/banip" ] && f_log
"err" "no banIP config directory"
1669 [ ! -r "/etc/config/banip" ] && f_log
"err" "no banIP config"
1670 [ "$(uci_get banip global ban_enabled)" = "0" ] && f_log
"err" "banIP is disabled"