You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1854 lines
59 KiB

  1. #!/bin/sh
  2. # banIP - ban incoming and outgoing ip adresses/subnets via ipset
  3. # written by Dirk Brenken (dev@brenken.org)
  4. #
  5. # This is free software, licensed under the GNU General Public License v3.
  6. #
  7. # (s)hellcheck exceptions
  8. # shellcheck disable=1091,2030,2031,2034,2039,2086,2129,2140,2143,2154,2181,2183,2188
  9. # set initial defaults
  10. #
  11. export LC_ALL=C
  12. export PATH="/usr/sbin:/usr/bin:/sbin:/bin"
  13. set -o pipefail
  14. ban_ver="0.7.8"
  15. ban_enabled="0"
  16. ban_mail_enabled="0"
  17. ban_proto4_enabled="0"
  18. ban_proto6_enabled="0"
  19. ban_logsrc_enabled="0"
  20. ban_logdst_enabled="0"
  21. ban_monitor_enabled="0"
  22. ban_autodetect="1"
  23. ban_autoblacklist="1"
  24. ban_autowhitelist="1"
  25. ban_whitelistonly="0"
  26. ban_logterms=""
  27. ban_loglimit="100"
  28. ban_ssh_logcount="3"
  29. ban_luci_logcount="3"
  30. ban_nginx_logcount="5"
  31. ban_mailactions=""
  32. ban_search=""
  33. ban_devs=""
  34. ban_ifaces=""
  35. ban_debug="0"
  36. ban_maxqueue="4"
  37. ban_fetchutil=""
  38. ban_ip_cmd="$(command -v ip)"
  39. ban_ipt4_cmd="$(command -v iptables)"
  40. ban_ipt4_savecmd="$(command -v iptables-save)"
  41. ban_ipt4_restorecmd="$(command -v iptables-restore)"
  42. ban_ipt6_cmd="$(command -v ip6tables)"
  43. ban_ipt6_savecmd="$(command -v ip6tables-save)"
  44. ban_ipt6_restorecmd="$(command -v ip6tables-restore)"
  45. ban_ipset_cmd="$(command -v ipset)"
  46. ban_logger_cmd="$(command -v logger)"
  47. ban_logread_cmd="$(command -v logread)"
  48. ban_allsources=""
  49. ban_sources=""
  50. ban_asns=""
  51. ban_countries=""
  52. ban_settype_src=""
  53. ban_settype_dst=""
  54. ban_settype_all=""
  55. ban_lan_inputchains_4=""
  56. ban_lan_inputchains_6=""
  57. ban_lan_forwardchains_4=""
  58. ban_lan_forwardchains_6=""
  59. ban_wan_inputchains_4=""
  60. ban_wan_inputchains_6=""
  61. ban_wan_forwardchains_4=""
  62. ban_wan_forwardchains_6=""
  63. ban_action="${1:-"start"}"
  64. ban_pidfile="/var/run/banip.pid"
  65. ban_bgpidfile="/var/run/banip_bg.pid"
  66. ban_tmpbase="/tmp"
  67. ban_rtfile="${ban_tmpbase}/ban_runtime.json"
  68. ban_srcfile="${ban_tmpbase}/ban_sources.json"
  69. ban_reportdir="${ban_tmpbase}/banIP-Report"
  70. ban_backupdir="${ban_tmpbase}/banIP-Backup"
  71. ban_srcarc="/etc/banip/banip.sources.gz"
  72. ban_dnsservice="/etc/banip/banip.dns"
  73. ban_mailservice="/etc/banip/banip.mail"
  74. ban_logservice="/etc/banip/banip.service"
  75. ban_maclist="/etc/banip/banip.maclist"
  76. ban_blacklist="/etc/banip/banip.blacklist"
  77. ban_whitelist="/etc/banip/banip.whitelist"
  78. ban_setcnt="0"
  79. ban_cnt="0"
  80. # load environment
  81. #
  82. f_load()
  83. {
  84. # get system information
  85. #
  86. ban_sysver="$(ubus -S call system board 2>/dev/null | jsonfilter -e '@.model' -e '@.release.description' | \
  87. awk 'BEGIN{ORS=", "}{print $0}' | awk '{print substr($0,1,length($0)-2)}')"
  88. # load config
  89. #
  90. f_conf
  91. # check status
  92. #
  93. if [ "${ban_enabled}" = "0" ]
  94. then
  95. f_bgsrv "stop"
  96. f_ipset "destroy"
  97. f_jsnup "disabled"
  98. f_rmbckp
  99. f_rmtmp
  100. f_log "info" "banIP is currently disabled, please set the config option 'ban_enabled' to '1' to use this service"
  101. exit 0
  102. fi
  103. f_dir "${ban_backupdir}"
  104. f_dir "${ban_reportdir}"
  105. }
  106. # check/create directories
  107. #
  108. f_dir()
  109. {
  110. local dir="${1}"
  111. if [ ! -d "${dir}" ]
  112. then
  113. mkdir -p "${dir}"
  114. if [ "${?}" = "0" ]
  115. then
  116. f_log "debug" "directory '${dir}' created"
  117. else
  118. f_log "err" "directory '${dir}' could not be created"
  119. fi
  120. else
  121. f_log "debug" "directory '${dir}' is used"
  122. fi
  123. }
  124. # load banIP config
  125. #
  126. f_conf()
  127. {
  128. if [ ! -r "/etc/config/banip" ] || [ -z "$(uci -q show banip.global.ban_autodetect)" ]
  129. then
  130. f_log "err" "no valid banIP config found, please re-install the package via opkg with the '--force-reinstall --force-maintainer' options"
  131. fi
  132. config_cb()
  133. {
  134. option_cb()
  135. {
  136. local option="${1}"
  137. local value="${2}"
  138. eval "${option}=\"${value}\""
  139. }
  140. list_cb()
  141. {
  142. local option="${1}"
  143. local value="${2}"
  144. if [ "${option}" = "ban_ifaces" ]
  145. then
  146. eval "${option}=\"$(printf "%s" "${ban_ifaces}")${value} \""
  147. elif [ "${option}" = "ban_sources" ]
  148. then
  149. eval "${option}=\"$(printf "%s" "${ban_sources}")${value} \""
  150. elif [ "${option}" = "ban_localsources" ]
  151. then
  152. eval "${option}=\"$(printf "%s" "${ban_localsources}")${value} \""
  153. elif [ "${option}" = "ban_extrasources" ]
  154. then
  155. eval "${option}=\"$(printf "%s" "${ban_extrasources}")${value} \""
  156. elif [ "${option}" = "ban_settype_src" ]
  157. then
  158. eval "${option}=\"$(printf "%s" "${ban_settype_src}")${value} \""
  159. elif [ "${option}" = "ban_settype_dst" ]
  160. then
  161. eval "${option}=\"$(printf "%s" "${ban_settype_dst}")${value} \""
  162. elif [ "${option}" = "ban_settype_all" ]
  163. then
  164. eval "${option}=\"$(printf "%s" "${ban_settype_all}")${value} \""
  165. elif [ "${option}" = "ban_mailactions" ]
  166. then
  167. eval "${option}=\"$(printf "%s" "${ban_mailactions}")${value} \""
  168. elif [ "${option}" = "ban_logterms" ]
  169. then
  170. eval "${option}=\"$(printf "%s" "${ban_logterms}")${value} \""
  171. elif [ "${option}" = "ban_countries" ]
  172. then
  173. eval "${option}=\"$(printf "%s" "${ban_countries}")${value} \""
  174. elif [ "${option}" = "ban_asns" ]
  175. then
  176. eval "${option}=\"$(printf "%s" "${ban_asns}")${value} \""
  177. elif [ "${option}" = "ban_lan_inputchains_4" ]
  178. then
  179. eval "${option}=\"$(printf "%s" "${ban_lan_inputchains_4}")${value} \""
  180. elif [ "${option}" = "ban_lan_inputchains_6" ]
  181. then
  182. eval "${option}=\"$(printf "%s" "${ban_lan_inputchains_6}")${value} \""
  183. elif [ "${option}" = "ban_lan_forwardchains_4" ]
  184. then
  185. eval "${option}=\"$(printf "%s" "${ban_lan_forwardchains_4}")${value} \""
  186. elif [ "${option}" = "ban_lan_forwardchains_6" ]
  187. then
  188. eval "${option}=\"$(printf "%s" "${ban_lan_forwardchains_6}")${value} \""
  189. elif [ "${option}" = "ban_wan_inputchains_4" ]
  190. then
  191. eval "${option}=\"$(printf "%s" "${ban_wan_inputchains_4}")${value} \""
  192. elif [ "${option}" = "ban_wan_inputchains_6" ]
  193. then
  194. eval "${option}=\"$(printf "%s" "${ban_wan_inputchains_6}")${value} \""
  195. elif [ "${option}" = "ban_wan_forwardchains_4" ]
  196. then
  197. eval "${option}=\"$(printf "%s" "${ban_wan_forwardchains_4}")${value} \""
  198. elif [ "${option}" = "ban_wan_forwardchains_6" ]
  199. then
  200. eval "${option}=\"$(printf "%s" "${ban_wan_forwardchains_6}")${value} \""
  201. fi
  202. }
  203. }
  204. config_load banip
  205. ban_chain="${ban_chain:-"banIP"}"
  206. ban_global_settype="${ban_global_settype:-"src+dst"}"
  207. ban_target_src="${ban_target_src:-"DROP"}"
  208. ban_target_dst="${ban_target_dst:-"REJECT"}"
  209. ban_lan_inputchains_4="${ban_lan_inputchains_4:-"input_lan_rule"}"
  210. ban_lan_inputchains_6="${ban_lan_inputchains_6:-"input_lan_rule"}"
  211. ban_lan_forwardchains_4="${ban_lan_forwardchains_4:-"forwarding_lan_rule"}"
  212. ban_lan_forwardchains_6="${ban_lan_forwardchains_6:-"forwarding_lan_rule"}"
  213. ban_wan_inputchains_4="${ban_wan_inputchains_4:-"input_wan_rule"}"
  214. ban_wan_inputchains_6="${ban_wan_inputchains_6:-"input_wan_rule"}"
  215. ban_wan_forwardchains_4="${ban_wan_forwardchains_4:-"forwarding_wan_rule"}"
  216. ban_wan_forwardchains_6="${ban_wan_forwardchains_6:-"forwarding_wan_rule"}"
  217. ban_logchain_src="${ban_logchain_src:-"${ban_chain}_log_src"}"
  218. ban_logchain_dst="${ban_logchain_dst:-"${ban_chain}_log_dst"}"
  219. ban_logtarget_src="${ban_target_src}"
  220. ban_logtarget_dst="${ban_target_dst}"
  221. if [ "${ban_logsrc_enabled}" = "1" ]
  222. then
  223. ban_logprefix_src="${ban_logprefix_src:-"[banIP-${ban_ver%-*}, src/${ban_target_src}] "}"
  224. ban_logopts_src="${ban_logopts_src:-"-m limit --limit 2/sec"}"
  225. ban_target_src="${ban_logchain_src}"
  226. fi
  227. if [ "${ban_logdst_enabled}" = "1" ]
  228. then
  229. ban_logprefix_dst="${ban_logprefix_dst:-"[banIP-${ban_ver%-*}, dst/${ban_target_dst}] "}"
  230. ban_logopts_dst="${ban_logopts_dst:-"-m limit --limit 2/sec"}"
  231. ban_target_dst="${ban_logchain_dst}"
  232. fi
  233. ban_localsources="${ban_localsources:-"maclist whitelist blacklist"}"
  234. ban_logterms="${ban_logterms:-"dropbear sshd luci nginx"}"
  235. f_log "debug" "f_conf ::: ifaces: ${ban_ifaces:-"-"}, chain: ${ban_chain}, set_type: ${ban_global_settype}, log_chains (src/dst): ${ban_logchain_src}/${ban_logchain_dst}, targets (src/dst): ${ban_target_src}/${ban_target_dst}, whitelist_only: ${ban_whitelistonly}"
  236. f_log "debug" "f_conf ::: lan_inputs (4/6): ${ban_lan_inputchains_4}/${ban_lan_inputchains_6}, lan_forwards (4/6): ${ban_lan_forwardchains_4}/${ban_lan_forwardchains_6}, wan_inputs (4/6): ${ban_wan_inputchains_4}/${ban_wan_inputchains_6}, wan_forwards (4/6): ${ban_wan_forwardchains_4}/${ban_wan_forwardchains_6}"
  237. f_log "debug" "f_conf ::: local_sources: ${ban_localsources:-"-"}, extra_sources: ${ban_extrasources:-"-"}, log_terms: ${ban_logterms:-"-"}, log_prefixes (src/dst): ${ban_logprefix_src}/${ban_logprefix_dst}, log_options (src/dst): ${ban_logopts_src}/${ban_logopts_dst}"
  238. }
  239. # check environment
  240. #
  241. f_env()
  242. {
  243. local util utils packages iface tmp cnt="0" cnt_max="10"
  244. ban_starttime="$(date "+%s")"
  245. f_jsnup "running"
  246. f_log "info" "start banIP processing (${ban_action})"
  247. # create temp directory & files
  248. #
  249. f_tmp
  250. # get wan devices and wan subnets
  251. #
  252. if [ "${ban_autodetect}" = "1" ] && [ -z "${ban_ifaces}" ]
  253. then
  254. while [ "${cnt}" -le "${cnt_max}" ]
  255. do
  256. network_find_wan iface
  257. if [ -n "${iface}" ] && [ -z "$(printf "%s\n" "${ban_ifaces}" | grep -F "${iface}")" ]
  258. then
  259. ban_proto4_enabled="1"
  260. ban_ifaces="${ban_ifaces}${iface} "
  261. uci_set banip global ban_proto4_enabled "1"
  262. uci_add_list banip global ban_ifaces "${iface}"
  263. fi
  264. network_find_wan6 iface
  265. if [ -n "${iface}" ] && [ -z "$(printf "%s\n" "${ban_ifaces}" | grep -F "${iface}")" ]
  266. then
  267. ban_proto6_enabled="1"
  268. ban_ifaces="${ban_ifaces}${iface} "
  269. uci_set banip global ban_proto6_enabled "1"
  270. uci_add_list banip global ban_ifaces "${iface}"
  271. fi
  272. if [ -z "${ban_ifaces}" ]
  273. then
  274. if [ "${cnt}" -le "${cnt_max}" ]
  275. then
  276. network_flush_cache
  277. cnt=$((cnt+1))
  278. sleep 1
  279. else
  280. break
  281. fi
  282. else
  283. if [ -n "$(uci -q changes "banip")" ]
  284. then
  285. uci_commit "banip"
  286. fi
  287. break
  288. fi
  289. done
  290. fi
  291. while [ "${cnt}" -le "${cnt_max}" ]
  292. do
  293. for iface in ${ban_ifaces}
  294. do
  295. network_get_device tmp "${iface}"
  296. if [ -n "${tmp}" ] && [ -z "$(printf "%s\n" "${ban_devs}" | grep -F "${tmp}")" ]
  297. then
  298. ban_devs="${ban_devs} ${tmp}"
  299. else
  300. network_get_physdev tmp "${iface}"
  301. if [ -n "${tmp}" ] && [ -z "$(printf "%s\n" "${ban_devs}" | grep -F "${tmp}")" ]
  302. then
  303. ban_devs="${ban_devs} ${tmp}"
  304. fi
  305. fi
  306. network_get_subnet tmp "${iface}"
  307. if [ -n "${tmp}" ] && [ -z "$(printf "%s\n" "${ban_subnets}" | grep -F "${tmp}")" ]
  308. then
  309. ban_subnets="${ban_subnets} ${tmp}"
  310. fi
  311. network_get_subnet6 tmp "${iface}"
  312. if [ -n "${tmp}" ] && [ -z "$(printf "%s\n" "${ban_subnets}" | grep -F "${tmp}")" ]
  313. then
  314. ban_subnets="${ban_subnets} ${tmp}"
  315. fi
  316. done
  317. if [ -z "${ban_devs}" ] || [ -z "${ban_subnets}" ]
  318. then
  319. if [ "${cnt}" -le "${cnt_max}" ]
  320. then
  321. network_flush_cache
  322. cnt=$((cnt+1))
  323. sleep 1
  324. else
  325. break
  326. fi
  327. else
  328. break
  329. fi
  330. done
  331. ban_ipdevs="$("${ban_ip_cmd}" link show 2>/dev/null | awk 'BEGIN{FS="[@: ]"}/^[0-9:]/{if($3!="lo"){ORS=" ";print $3}}')"
  332. if [ -z "${ban_ifaces}" ] || [ -z "${ban_devs}" ] || [ -z "${ban_ipdevs}" ]
  333. then
  334. f_log "err" "logical wan interface(s)/device(s) '${ban_ifaces:-"-"}/${ban_devs:-"-"}' not found, please please check your configuration"
  335. elif [ -z "${ban_ipdevs}" ]
  336. then
  337. f_log "err" "ip device(s) '${ban_ipdevs:-"-"}' not found, please please check your configuration"
  338. fi
  339. # check ipset/iptables utility
  340. #
  341. if [ ! -x "${ban_ipset_cmd}" ]
  342. then
  343. f_log "err" "ipset utility '${ban_ipset_cmd:-"-"}' not executable, please install package 'ipset'"
  344. fi
  345. if { [ "${ban_proto4_enabled}" = "1" ] && { [ ! -x "${ban_ipt4_cmd}" ] || [ ! -x "${ban_ipt4_savecmd}" ] || [ ! -x "${ban_ipt4_restorecmd}" ]; }; } || \
  346. { [ "${ban_proto6_enabled}" = "1" ] && { [ ! -x "${ban_ipt6_cmd}" ] || [ ! -x "${ban_ipt6_savecmd}" ] || [ ! -x "${ban_ipt6_restorecmd}" ]; }; }
  347. then
  348. f_log "err" "iptables utilities '${ban_ipt4_cmd:-"-"}, ${ban_ipt4_savecmd:-"-"}, ${ban_ipt4_restorecmd:-"-"}/${ban_ipt6_cmd:-"-"}', ${ban_ipt6_savecmd:-"-"}, ${ban_ipt6_restorecmd:-"-"} not executable, please install the relevant iptables packages"
  349. fi
  350. # check download utility
  351. #
  352. if [ -z "${ban_fetchutil}" ]
  353. then
  354. while [ -z "${packages}" ] && [ "${cnt}" -le "${cnt_max}" ]
  355. do
  356. packages="$(opkg list-installed 2>/dev/null)"
  357. cnt=$((cnt+1))
  358. sleep 1
  359. done
  360. if [ -z "${packages}" ]
  361. then
  362. f_log "err" "local opkg package repository is not available, please set 'ban_fetchutil' manually"
  363. fi
  364. utils="aria2c curl wget uclient-fetch"
  365. for util in ${utils}
  366. do
  367. if { [ "${util}" = "uclient-fetch" ] && [ -n "$(printf "%s" "${packages}" | grep "^libustream-")" ]; } || \
  368. { [ "${util}" = "wget" ] && [ -n "$(printf "%s" "${packages}" | grep "^wget -")" ]; } || \
  369. [ "${util}" = "curl" ] || [ "${util}" = "aria2c" ]
  370. then
  371. if [ -x "$(command -v "${util}")" ]
  372. then
  373. ban_fetchutil="${util}"
  374. uci_set banip global ban_fetchutil "${util}"
  375. uci_commit "banip"
  376. break
  377. fi
  378. fi
  379. done
  380. elif [ ! -x "$(command -v "${ban_fetchutil}")" ]
  381. then
  382. unset ban_fetchutil
  383. fi
  384. case "${ban_fetchutil}" in
  385. "aria2c")
  386. ban_fetchparm="${ban_fetchparm:-"--timeout=20 --allow-overwrite=true --auto-file-renaming=false --check-certificate=true --log-level=warn --dir=/ -o"}"
  387. ;;
  388. "curl")
  389. ban_fetchparm="${ban_fetchparm:-"--connect-timeout 20 --silent --show-error --location -o"}"
  390. ;;
  391. "uclient-fetch")
  392. ban_fetchparm="${ban_fetchparm:-"--timeout=20 -O"}"
  393. ;;
  394. "wget")
  395. ban_fetchparm="${ban_fetchparm:-"--no-cache --no-cookies --max-redirect=0 --timeout=20 -O"}"
  396. ;;
  397. esac
  398. if [ -n "${ban_fetchutil}" ] && [ -n "${ban_fetchparm}" ]
  399. then
  400. ban_fetchutil="$(command -v "${ban_fetchutil}")"
  401. else
  402. f_log "err" "download utility with SSL support not found, please install 'uclient-fetch' with a 'libustream-*' variant or another download utility like 'wget', 'curl' or 'aria2'"
  403. fi
  404. # load JSON source file
  405. #
  406. if [ ! -r "${ban_srcfile}" ]
  407. then
  408. if [ -r "${ban_srcarc}" ]
  409. then
  410. zcat "${ban_srcarc}" > "${ban_srcfile}"
  411. else
  412. f_log "err" "banIP source archive not found"
  413. fi
  414. fi
  415. if [ -r "${ban_srcfile}" ]
  416. then
  417. json_load_file "${ban_srcfile}"
  418. json_get_keys ban_allsources
  419. ban_allsources="${ban_allsources} maclist blacklist whitelist"
  420. else
  421. f_log "err" "banIP source file not found"
  422. fi
  423. f_log "debug" "f_env ::: auto_detect: ${ban_autodetect}, fetch_util: ${ban_fetchutil:-"-"}, fetch_parm: ${ban_fetchparm:-"-"}, src_file: ${ban_srcfile:-"-"}, log_terms: ${ban_logterms}, interfaces: ${ban_ifaces:-"-"}, devices: ${ban_devs:-"-"}, subnets: ${ban_subnets:-"-"}, ip_devices: ${ban_ipdevs:-"-"}, protocols (4/6): ${ban_proto4_enabled}/${ban_proto6_enabled}"
  424. }
  425. # create temporary files and directories
  426. #
  427. f_tmp()
  428. {
  429. f_dir "${ban_tmpbase}"
  430. ban_tmpdir="$(mktemp -p "${ban_tmpbase}" -d)"
  431. ban_tmpfile="$(mktemp -p "${ban_tmpdir}" -tu)"
  432. if [ ! -f "${ban_pidfile}" ] || [ ! -s "${ban_pidfile}" ]
  433. then
  434. printf "%s" "${$}" > "${ban_pidfile}"
  435. fi
  436. f_log "debug" "f_tmp ::: tmp_base: ${ban_tmpbase:-"-"}, tmp_dir: ${ban_tmpdir:-"-"}, pid_file: ${ban_pidfile:-"-"}"
  437. }
  438. # remove temporary files and directories
  439. #
  440. f_rmtmp()
  441. {
  442. if [ -d "${ban_tmpdir}" ]
  443. then
  444. rm -rf "${ban_tmpdir}"
  445. fi
  446. rm -f "${ban_srcfile}"
  447. > "${ban_pidfile}"
  448. f_log "debug" "f_rmtmp ::: tmp_base: ${ban_tmpbase:-"-"}, tmp_dir: ${ban_tmpdir:-"-"}, pid_file: ${ban_pidfile:-"-"}"
  449. }
  450. # remove backup files
  451. #
  452. f_rmbckp()
  453. {
  454. if [ -d "${ban_backupdir}" ]
  455. then
  456. rm -f "${ban_backupdir}/banIP."*".gz"
  457. fi
  458. }
  459. # status helper function
  460. #
  461. f_char()
  462. {
  463. local result input="${1}"
  464. if [ "${input}" = "1" ]
  465. then
  466. result="✔"
  467. else
  468. result="✘"
  469. fi
  470. printf "%s" "${result}"
  471. }
  472. # apply iptables rules
  473. #
  474. f_iptrule()
  475. {
  476. local rc timeout="-w 5" action="${1}" chain="${2}" rule="${3}" pos="${4}"
  477. if [ "${ban_proto4_enabled}" = "1" ] && { [ "${src_name}" = "maclist" ] || [ "${src_name##*_}" = "4" ]; }
  478. then
  479. rc="$("${ban_ipt4_cmd}" "${timeout}" -C ${chain} ${rule} 2>/dev/null; printf "%u" ${?})"
  480. if { [ "${rc}" != "0" ] && { [ "${action}" = "-A" ] || [ "${action}" = "-I" ]; }; } || \
  481. { [ "${rc}" = "0" ] && [ "${action}" = "-D" ]; }
  482. then
  483. "${ban_ipt4_cmd}" "${timeout}" "${action}" ${chain} ${pos} ${rule} 2>/dev/null
  484. rc="${?}"
  485. else
  486. rc=0
  487. fi
  488. fi
  489. if [ "${ban_proto6_enabled}" = "1" ] && { [ "${src_name}" = "maclist" ] || [ "${src_name##*_}" = "6" ]; }
  490. then
  491. rc="$("${ban_ipt6_cmd}" "${timeout}" -C ${chain} ${rule} 2>/dev/null; printf "%u" ${?})"
  492. if { [ "${rc}" != "0" ] && { [ "${action}" = "-A" ] || [ "${action}" = "-I" ]; }; } || \
  493. { [ "${rc}" = "0" ] && [ "${action}" = "-D" ]; }
  494. then
  495. "${ban_ipt6_cmd}" "${timeout}" "${action}" ${chain} ${pos} ${rule} 2>/dev/null
  496. rc="${?}"
  497. else
  498. rc=0
  499. fi
  500. fi
  501. if [ -n "${rc}" ] && [ "${rc}" != "0" ]
  502. then
  503. > "${tmp_err}"
  504. f_log "info" "${src_name}: iptables action '${action:-"-"}' failed with '${chain}, ${pos:-"-"}, ${rule:-"-"}'"
  505. fi
  506. }
  507. # iptables controller
  508. #
  509. f_iptables()
  510. {
  511. local ipt_cmd chain chainsets dev pos timeout="-w 5" destroy="${1}"
  512. if [ "${ban_action}" != "refresh" ] && [ "${ban_action}" != "resume" ]
  513. then
  514. for dev in ${ban_ipdevs}
  515. do
  516. if [ "${src_name}" = "maclist" ]
  517. then
  518. f_iptrule "-D" "${ban_chain}" "-o ${dev} -m set --match-set ${src_name} src -j RETURN"
  519. elif [ "${src_name%_*}" = "whitelist" ]
  520. then
  521. f_iptrule "-D" "${ban_chain}" "-i ${dev} -m set ! --match-set ${src_name} src -j ${ban_logtarget_src}"
  522. f_iptrule "-D" "${ban_chain}" "-o ${dev} -m set ! --match-set ${src_name} dst -j ${ban_logtarget_dst}"
  523. f_iptrule "-D" "${ban_chain}" "-i ${dev} -m set ! --match-set ${src_name} src -j ${ban_logchain_src}"
  524. f_iptrule "-D" "${ban_chain}" "-o ${dev} -m set ! --match-set ${src_name} dst -j ${ban_logchain_dst}"
  525. f_iptrule "-D" "${ban_chain}" "-i ${dev} -m set --match-set ${src_name} src -j RETURN"
  526. f_iptrule "-D" "${ban_chain}" "-o ${dev} -m set --match-set ${src_name} dst -j RETURN"
  527. else
  528. f_iptrule "-D" "${ban_chain}" "-i ${dev} -m set --match-set ${src_name} src -j ${ban_logtarget_src}"
  529. f_iptrule "-D" "${ban_chain}" "-o ${dev} -m set --match-set ${src_name} dst -j ${ban_logtarget_dst}"
  530. f_iptrule "-D" "${ban_chain}" "-i ${dev} -m set --match-set ${src_name} src -j ${ban_logchain_src}"
  531. f_iptrule "-D" "${ban_chain}" "-o ${dev} -m set --match-set ${src_name} dst -j ${ban_logchain_dst}"
  532. fi
  533. done
  534. fi
  535. if [ -z "${destroy}" ] && { [ "${cnt}" -gt "0" ] || [ "${src_name%_*}" = "blacklist" ] || [ "${src_name%_*}" = "whitelist" ]; }
  536. then
  537. if [ "${src_name##*_}" = "4" ]
  538. then
  539. ipt_cmd="${ban_ipt4_cmd}"
  540. if [ ! -f "${ban_tmpfile}.${src_name##*_}.chains" ]
  541. then
  542. > "${ban_tmpfile}.${src_name##*_}.chains"
  543. chainsets="${ban_lan_inputchains_4} ${ban_wan_inputchains_4} ${ban_lan_forwardchains_4} ${ban_wan_forwardchains_4}"
  544. for chain in ${chainsets}
  545. do
  546. f_iptrule "-I" "${chain}" "-j ${ban_chain}"
  547. done
  548. f_iptrule "-A" "${ban_chain}" "-p udp --dport 67:68 --sport 67:68 -j RETURN"
  549. f_iptrule "-A" "${ban_chain}" "-m conntrack ! --ctstate NEW -j RETURN"
  550. fi
  551. elif [ "${src_name##*_}" = "6" ]
  552. then
  553. ipt_cmd="${ban_ipt6_cmd}"
  554. if [ ! -f "${ban_tmpfile}.${src_name##*_}.chains" ]
  555. then
  556. > "${ban_tmpfile}.${src_name##*_}.chains"
  557. chainsets="${ban_lan_inputchains_6} ${ban_wan_inputchains_6} ${ban_lan_forwardchains_6} ${ban_wan_forwardchains_6}"
  558. for chain in ${chainsets}
  559. do
  560. f_iptrule "-I" "${chain}" "-j ${ban_chain}"
  561. done
  562. f_iptrule "-A" "${ban_chain}" "-p ipv6-icmp -s fe80::/10 -d fe80::/10 -j RETURN"
  563. f_iptrule "-A" "${ban_chain}" "-p udp -s fc00::/6 --sport 547 -d fc00::/6 --dport 546 -j RETURN"
  564. f_iptrule "-A" "${ban_chain}" "-m conntrack ! --ctstate NEW -j RETURN"
  565. fi
  566. fi
  567. if [ "${src_settype}" != "dst" ]
  568. then
  569. for dev in ${ban_devs}
  570. do
  571. if [ "${src_name}" = "maclist" ]
  572. then
  573. f_iptrule "-I" "${ban_chain}" "-o ${dev} -m set --match-set ${src_name} src -j RETURN" "1"
  574. elif [ "${src_name%_*}" = "whitelist" ]
  575. then
  576. pos="$(( $("${ipt_cmd}" "${timeout}" -vnL "${ban_chain}" --line-numbers | grep -cF "RETURN")+1))"
  577. if [ "${ban_whitelistonly}" = "1" ]
  578. then
  579. f_iptrule "-I" "${ban_chain}" "-i ${dev} -m set ! --match-set ${src_name} src -j ${ban_target_src}" "${pos}"
  580. else
  581. f_iptrule "-I" "${ban_chain}" "-i ${dev} -m set --match-set ${src_name} src -j RETURN" "${pos}"
  582. fi
  583. else
  584. f_iptrule "${action:-"-A"}" "${ban_chain}" "-i ${dev} -m set --match-set ${src_name} src -j ${ban_target_src}"
  585. fi
  586. done
  587. fi
  588. if [ "${src_settype}" != "src" ]
  589. then
  590. for dev in ${ban_devs}
  591. do
  592. if [ "${src_name%_*}" = "whitelist" ]
  593. then
  594. pos="$(( $("${ipt_cmd}" "${timeout}" -vnL "${ban_chain}" --line-numbers | grep -cF "RETURN")+1))"
  595. if [ "${ban_whitelistonly}" = "1" ]
  596. then
  597. f_iptrule "-I" "${ban_chain}" "-o ${dev} -m set ! --match-set ${src_name} dst -j ${ban_target_dst}" "${pos}"
  598. else
  599. f_iptrule "-I" "${ban_chain}" "-o ${dev} -m set --match-set ${src_name} dst -j RETURN" "${pos}"
  600. fi
  601. elif [ "${src_name}" != "maclist" ]
  602. then
  603. f_iptrule "${action:-"-A"}" "${ban_chain}" "-o ${dev} -m set --match-set ${src_name} dst -j ${ban_target_dst}"
  604. fi
  605. done
  606. fi
  607. else
  608. "${ban_ipset_cmd}" -q destroy "${src_name}"
  609. fi
  610. }
  611. # ipset controller
  612. #
  613. f_ipset()
  614. {
  615. local src src_list action rule ipt_cmd out_rc max="0" cnt="0" cnt_ip="0" cnt_cidr="0" cnt_mac="0" timeout="-w 5" mode="${1}" in_rc="4"
  616. case "${mode}" in
  617. "backup")
  618. gzip -cf "${tmp_load}" 2>/dev/null > "${ban_backupdir}/banIP.${src_name}.gz"
  619. out_rc="${?}"
  620. f_log "debug" "f_ipset ::: name: ${src_name:-"-"}, mode: ${mode:-"-"}, out_rc: ${out_rc}"
  621. return "${out_rc}"
  622. ;;
  623. "restore")
  624. if [ -f "${ban_backupdir}/banIP.${src_name}.gz" ]
  625. then
  626. zcat "${ban_backupdir}/banIP.${src_name}.gz" 2>/dev/null > "${tmp_load}"
  627. out_rc="${?}"
  628. else
  629. out_rc="${in_rc}"
  630. fi
  631. f_log "debug" "f_ipset ::: name: ${src_name:-"-"}, mode: ${mode:-"-"}, out_rc: ${out_rc}"
  632. return "${out_rc}"
  633. ;;
  634. "remove")
  635. if [ -f "${ban_backupdir}/banIP.${src_name}.gz" ]
  636. then
  637. rm -f "${ban_backupdir}/banIP.${src_name}.gz"
  638. out_rc="${?}"
  639. else
  640. out_rc="${in_rc}"
  641. fi
  642. f_log "debug" "f_ipset ::: name: ${src_name:-"-"}, mode: ${mode:-"-"}, out_rc: ${out_rc}"
  643. return "${out_rc}"
  644. ;;
  645. "initial")
  646. for proto in "4" "6"
  647. do
  648. if [ "${proto}" = "4" ] && [ "${ban_proto4_enabled}" = "1" ]
  649. then
  650. ipt_cmd="${ban_ipt4_cmd}"
  651. chainsets="${ban_lan_inputchains_4} ${ban_lan_forwardchains_4} ${ban_wan_inputchains_4} ${ban_wan_forwardchains_4}"
  652. elif [ "${proto}" = "6" ] && [ "${ban_proto6_enabled}" = "1" ]
  653. then
  654. ipt_cmd="${ban_ipt6_cmd}"
  655. chainsets="${ban_lan_inputchains_6} ${ban_lan_forwardchains_6} ${ban_wan_inputchains_6} ${ban_wan_forwardchains_6}"
  656. fi
  657. if { [ "${proto}" = "4" ] && [ "${ban_proto4_enabled}" = "1" ]; } || \
  658. { [ "${proto}" = "6" ] && [ "${ban_proto6_enabled}" = "1" ]; }
  659. then
  660. if [ -z "$("${ipt_cmd}" "${timeout}" -nL "${ban_chain}" 2>/dev/null)" ]
  661. then
  662. "${ipt_cmd}" "${timeout}" -N "${ban_chain}" 2>/dev/null
  663. out_rc="${?}"
  664. f_log "debug" "f_ipset ::: name: ${src_name:-"-"}, mode: ${mode:-"-"}, chain: ${ban_chain:-"-"}, out_rc: ${out_rc}"
  665. else
  666. out_rc=0
  667. for chain in ${chainsets}
  668. do
  669. f_iptrule "-D" "${chain}" "-j ${ban_chain}"
  670. done
  671. fi
  672. if [ "${ban_logsrc_enabled}" = "1" ] && [ "${out_rc}" = "0" ] && [ -z "$("${ipt_cmd}" "${timeout}" -nL "${ban_logchain_src}" 2>/dev/null)" ]
  673. then
  674. "${ipt_cmd}" "${timeout}" -N "${ban_logchain_src}" 2>/dev/null
  675. out_rc="${?}"
  676. if [ "${out_rc}" = "0" ]
  677. then
  678. "${ipt_cmd}" "${timeout}" -A "${ban_logchain_src}" -j LOG ${ban_logopts_src} --log-prefix "${ban_logprefix_src}"
  679. out_rc="${?}"
  680. if [ "${out_rc}" = "0" ]
  681. then
  682. "${ipt_cmd}" "${timeout}" -A "${ban_logchain_src}" -j "${ban_logtarget_src}"
  683. out_rc="${?}"
  684. fi
  685. fi
  686. f_log "debug" "f_ipset ::: name: ${src_name:-"-"}, mode: ${mode:-"-"}, logchain_src: ${ban_logchain_src:-"-"}, out_rc: ${out_rc}"
  687. fi
  688. if [ "${ban_logdst_enabled}" = "1" ] && [ "${out_rc}" = "0" ] && [ -z "$("${ipt_cmd}" "${timeout}" -nL "${ban_logchain_dst}" 2>/dev/null)" ]
  689. then
  690. "${ipt_cmd}" "${timeout}" -N "${ban_logchain_dst}" 2>/dev/null
  691. out_rc="${?}"
  692. if [ "${out_rc}" = "0" ]
  693. then
  694. "${ipt_cmd}" "${timeout}" -A "${ban_logchain_dst}" -j LOG ${ban_logopts_dst} --log-prefix "${ban_logprefix_dst}"
  695. out_rc="${?}"
  696. if [ "${out_rc}" = "0" ]
  697. then
  698. "${ipt_cmd}" "${timeout}" -A "${ban_logchain_dst}" -j "${ban_logtarget_dst}"
  699. out_rc="${?}"
  700. fi
  701. fi
  702. f_log "debug" "f_ipset ::: name: initial, mode: ${mode:-"-"}, logchain_dst: ${ban_logchain_dst:-"-"}, out_rc: ${out_rc}"
  703. fi
  704. fi
  705. done
  706. out_rc="${out_rc:-"${in_rc}"}"
  707. f_log "debug" "f_ipset ::: name: ${src_name:-"-"}, mode: ${mode:-"-"}, out_rc: ${out_rc}"
  708. return "${out_rc}"
  709. ;;
  710. "create")
  711. if [ -z "$("${ban_ipset_cmd}" -q -n list "${src_name}")" ] && \
  712. { [ -s "${tmp_file}" ] || [ "${src_name%_*}" = "whitelist" ] || [ "${src_name%_*}" = "blacklist" ]; }
  713. then
  714. max="$(awk 'END{print NR}' "${tmp_file}" 2>/dev/null)"
  715. max=$((max+262144))
  716. if [ "${src_name}" = "maclist" ]
  717. then
  718. "${ban_ipset_cmd}" create "${src_name}" hash:mac hashsize 64 maxelem "${max}" counters timeout "${ban_maclist_timeout:-"0"}"
  719. out_rc="${?}"
  720. elif [ "${src_name%_*}" = "whitelist" ]
  721. then
  722. "${ban_ipset_cmd}" create "${src_name}" hash:net hashsize 64 maxelem "${max}" family "${src_ipver}" counters timeout "${ban_whitelist_timeout:-"0"}"
  723. out_rc="${?}"
  724. elif [ "${src_name%_*}" = "blacklist" ]
  725. then
  726. "${ban_ipset_cmd}" create "${src_name}" hash:net hashsize 64 maxelem "${max}" family "${src_ipver}" counters timeout "${ban_blacklist_timeout:-"0"}"
  727. out_rc="${?}"
  728. else
  729. "${ban_ipset_cmd}" create "${src_name}" hash:net hashsize 64 maxelem "${max}" family "${src_ipver}" counters
  730. out_rc="${?}"
  731. fi
  732. elif [ -n "$("${ban_ipset_cmd}" -q -n list "${src_name}")" ]
  733. then
  734. "${ban_ipset_cmd}" -q flush "${src_name}"
  735. out_rc="${?}"
  736. fi
  737. if [ -s "${tmp_file}" ] && [ "${out_rc}" = "0" ]
  738. then
  739. "${ban_ipset_cmd}" -q -! restore < "${tmp_file}"
  740. out_rc="${?}"
  741. if [ "${out_rc}" = "0" ]
  742. then
  743. src_list="$("${ban_ipset_cmd}" -q list "${src_name}")"
  744. cnt="$(printf "%s\n" "${src_list}" | awk '/^Number of entries:/{print $4}')"
  745. cnt_mac="$(printf "%s\n" "${src_list}" | grep -cE "^(([0-9A-Z][0-9A-Z]:){5}[0-9A-Z]{2} )")"
  746. cnt_cidr="$(printf "%s\n" "${src_list}" | grep -cE "(/[0-9]{1,3} )")"
  747. cnt_ip=$((cnt-cnt_cidr-cnt_mac))
  748. printf "%s\n" "${cnt}" > "${tmp_cnt}"
  749. fi
  750. fi
  751. f_iptables
  752. end_ts="$(date +%s)"
  753. out_rc="${out_rc:-"${in_rc}"}"
  754. f_log "debug" "f_ipset ::: name: ${src_name:-"-"}, mode: ${mode:-"-"}, ipver: ${src_ipver:-"-"}, settype: ${src_settype:-"-"}, count(sum/ip/cidr/mac): ${cnt}/${cnt_ip}/${cnt_cidr}/${cnt_mac}, time: $((end_ts-start_ts)), out_rc: ${out_rc}"
  755. return "${out_rc}"
  756. ;;
  757. "refresh")
  758. if [ -n "$("${ban_ipset_cmd}" -q -n list "${src_name}")" ]
  759. then
  760. out_rc=0
  761. src_list="$("${ban_ipset_cmd}" -q list "${src_name}")"
  762. cnt="$(printf "%s\n" "${src_list}" | awk '/^Number of entries:/{print $4}')"
  763. cnt_mac="$(printf "%s\n" "${src_list}" | grep -cE "^(([0-9A-Z][0-9A-Z]:){5}[0-9A-Z]{2} )")"
  764. cnt_cidr="$(printf "%s\n" "${src_list}" | grep -cE "(/[0-9]{1,3} )")"
  765. cnt_ip=$((cnt-cnt_cidr-cnt_mac))
  766. printf "%s\n" "${cnt}" > "${tmp_cnt}"
  767. f_iptables
  768. fi
  769. end_ts="$(date +%s)"
  770. out_rc="${out_rc:-"${in_rc}"}"
  771. f_log "debug" "f_ipset ::: name: ${src_name:-"-"}, mode: ${mode:-"-"}, count(sum/ip/cidr/mac): ${cnt}/${cnt_ip}/${cnt_cidr}/${cnt_mac}, time: $((end_ts-start_ts)), out_rc: ${out_rc}"
  772. return "${out_rc}"
  773. ;;
  774. "suspend")
  775. for src in ${ban_sources} ${ban_localsources}
  776. do
  777. if [ "${src}" = "maclist" ] && [ -n "$("${ban_ipset_cmd}" -q -n list "${src}")" ]
  778. then
  779. tmp_file="${ban_backupdir}/${src}.file"
  780. "${ban_ipset_cmd}" -q save "${src}" | tail -n +2 > "${tmp_file}"
  781. "${ban_ipset_cmd}" -q flush "${src}"
  782. else
  783. for proto in "4" "6"
  784. do
  785. if [ -n "$("${ban_ipset_cmd}" -q -n list "${src}_${proto}")" ]
  786. then
  787. tmp_file="${ban_backupdir}/${src}_${proto}.file"
  788. "${ban_ipset_cmd}" -q save "${src}_${proto}" | tail -n +2 > "${tmp_file}"
  789. "${ban_ipset_cmd}" -q flush "${src}_${proto}"
  790. fi
  791. done
  792. fi
  793. done
  794. f_log "debug" "f_ipset ::: name: ${src:-"-"}, mode: ${mode:-"-"}"
  795. ;;
  796. "resume")
  797. if [ -f "${ban_backupdir}/${src_name}.file" ]
  798. then
  799. "${ban_ipset_cmd}" -q -! restore < "${ban_backupdir}/${src_name}.file"
  800. out_rc="${?}"
  801. if [ "${out_rc}" = "0" ]
  802. then
  803. rm -f "${ban_backupdir}/${src_name}.file"
  804. src_list="$("${ban_ipset_cmd}" -q list "${src_name}")"
  805. cnt="$(printf "%s\n" "${src_list}" | awk '/^Number of entries:/{print $4}')"
  806. cnt_mac="$(printf "%s\n" "${src_list}" | grep -cE "^(([0-9A-Z][0-9A-Z]:){5}[0-9A-Z]{2} )")"
  807. cnt_cidr="$(printf "%s\n" "${src_list}" | grep -cE "(/[0-9]{1,3} )")"
  808. cnt_ip=$((cnt-cnt_cidr-cnt_mac))
  809. printf "%s\n" "${cnt}" > "${tmp_cnt}"
  810. fi
  811. f_iptables
  812. fi
  813. end_ts="$(date +%s)"
  814. out_rc="${out_rc:-"${in_rc}"}"
  815. f_log "debug" "f_ipset ::: name: ${src_name:-"-"}, mode: ${mode:-"-"}, ipver: ${src_ipver:-"-"}, settype: ${src_settype:-"-"}, count(sum/ip/cidr/mac): ${cnt}/${cnt_ip}/${cnt_cidr}/${cnt_mac}, time: $((end_ts-start_ts)), out_rc: ${out_rc}"
  816. return "${out_rc}"
  817. ;;
  818. "flush")
  819. if [ -n "$("${ban_ipset_cmd}" -q -n list "${src_name}")" ]
  820. then
  821. f_iptables "destroy"
  822. out_rc=0
  823. fi
  824. out_rc="${out_rc:-"${in_rc}"}"
  825. f_log "debug" "f_ipset ::: name: ${src_name:-"-"}, mode: ${mode:-"-"}, out_rc: ${out_rc}"
  826. return "${out_rc}"
  827. ;;
  828. "destroy")
  829. for chain in ${ban_chain} ${ban_logchain_src} ${ban_logchain_dst}
  830. do
  831. if [ -n "$("${ban_ipt4_cmd}" "${timeout}" -nL "${chain}" 2>/dev/null)" ]
  832. then
  833. "${ban_ipt4_savecmd}" | grep -v -- "-j ${chain}" | "${ban_ipt4_restorecmd}"
  834. "${ban_ipt4_cmd}" "${timeout}" -F "${chain}" 2>/dev/null
  835. "${ban_ipt4_cmd}" "${timeout}" -X "${chain}" 2>/dev/null
  836. fi
  837. if [ -n "$("${ban_ipt6_cmd}" "${timeout}" -nL "${chain}" 2>/dev/null)" ]
  838. then
  839. "${ban_ipt6_savecmd}" | grep -v -- "-j ${chain}" | "${ban_ipt6_restorecmd}"
  840. "${ban_ipt6_cmd}" "${timeout}" -F "${chain}" 2>/dev/null
  841. "${ban_ipt6_cmd}" "${timeout}" -X "${chain}" 2>/dev/null
  842. fi
  843. done
  844. for src in ${ban_sources} maclist blacklist whitelist
  845. do
  846. if [ "${src}" = "maclist" ] && [ -n "$("${ban_ipset_cmd}" -q -n list "${src}")" ]
  847. then
  848. "${ban_ipset_cmd}" -q destroy "${src}"
  849. else
  850. for proto in "4" "6"
  851. do
  852. if [ -n "$("${ban_ipset_cmd}" -q -n list "${src}_${proto}")" ]
  853. then
  854. "${ban_ipset_cmd}" -q destroy "${src}_${proto}"
  855. fi
  856. done
  857. fi
  858. done
  859. f_log "debug" "f_ipset ::: name: ${src_name:-"-"}, mode: ${mode:-"-"}"
  860. ;;
  861. esac
  862. }
  863. # write to syslog
  864. #
  865. f_log()
  866. {
  867. local class="${1}" log_msg="${2}"
  868. if [ -n "${log_msg}" ] && { [ "${class}" != "debug" ] || [ "${ban_debug}" = "1" ]; }
  869. then
  870. if [ -x "${ban_logger_cmd}" ]
  871. then
  872. "${ban_logger_cmd}" -p "${class}" -t "banIP-${ban_ver%-*}[${$}]" "${log_msg}"
  873. else
  874. printf "%s %s %s\n" "${class}" "banIP-${ban_ver%-*}[${$}]" "${log_msg}"
  875. fi
  876. if [ "${class}" = "err" ]
  877. then
  878. f_jsnup "error"
  879. f_ipset "destroy"
  880. f_rmbckp
  881. f_rmtmp
  882. exit 1
  883. fi
  884. fi
  885. }
  886. # kill all relevant background processes
  887. #
  888. f_pidx()
  889. {
  890. local pids ppid="${1}"
  891. pids="$(pgrep -P "${ppid}" 2>/dev/null | awk '{ORS=" ";print $0}')"
  892. kill -HUP "${ppid}" "${pids}" 2>/dev/null
  893. > "${ban_bgpidfile}"
  894. }
  895. # start log service to trace failed ssh/luci logins
  896. #
  897. f_bgsrv()
  898. {
  899. local bg_pid action="${1}"
  900. bg_pid="$(cat "${ban_bgpidfile}" 2>/dev/null)"
  901. if [ "${action}" = "start" ] && [ -x "${ban_logservice}" ] && [ "${ban_monitor_enabled}" = "1" ] && [ "${ban_whitelistonly}" = "0" ]
  902. then
  903. if [ -n "${bg_pid}" ]
  904. then
  905. f_pidx "${bg_pid}"
  906. fi
  907. if [ -n "$(printf "%s\n" "${ban_logterms}" | grep -F "dropbear")" ]
  908. then
  909. ban_search="Exit before auth from|"
  910. fi
  911. if [ -n "$(printf "%s\n" "${ban_logterms}" | grep -F "sshd")" ]
  912. then
  913. ban_search="${ban_search}error: maximum authentication attempts exceeded|sshd.*Connection closed by.*\[preauth\]|"
  914. fi
  915. if [ -n "$(printf "%s\n" "${ban_logterms}" | grep -F "luci")" ]
  916. then
  917. ban_search="${ban_search}luci: failed login|"
  918. fi
  919. if [ -n "$(printf "%s\n" "${ban_logterms}" | grep -F "nginx")" ]
  920. then
  921. ban_search="${ban_search}nginx\[[0-9]+\]:.*\[error\].*open().*client: [[:alnum:].:]+|"
  922. fi
  923. (
  924. "${ban_logservice}" "${ban_ver}" "${ban_search%?}" &
  925. printf "%s" "${!}" > "${ban_bgpidfile}"
  926. )
  927. elif { [ "${action}" = "stop" ] || [ "${ban_monitor_enabled}" = "0" ]; } && [ -n "${bg_pid}" ]
  928. then
  929. f_pidx "${bg_pid}"
  930. fi
  931. f_log "debug" "f_bgsrv ::: action: ${action:-"-"}, bg_pid (old/new): ${bg_pid}/$(cat "${ban_bgpidfile}" 2>/dev/null), monitor_enabled: ${ban_monitor_enabled:-"-"}, log_service: ${ban_logservice:-"-"}"
  932. }
  933. # download controller
  934. #
  935. f_down()
  936. {
  937. local src_name="${1}" proto="${2}" src_ipver="${3}" src_url="${4}" src_rule="${5}" src_comp="${6}"
  938. local ip start_ts end_ts src_settype src_log src_rc tmp_load tmp_file tmp_raw tmp_cnt tmp_err
  939. start_ts="$(date +%s)"
  940. if [ -n "$(printf "%s\n" "${ban_settype_src}" | grep -F "${src_name}")" ]
  941. then
  942. src_settype="src"
  943. elif [ -n "$(printf "%s\n" "${ban_settype_dst}" | grep -F "${src_name}")" ]
  944. then
  945. src_settype="dst"
  946. elif [ -n "$(printf "%s\n" "${ban_settype_all}" | grep -F "${src_name}")" ]
  947. then
  948. src_settype="src+dst"
  949. else
  950. src_settype="${ban_global_settype}"
  951. fi
  952. src_name="${src_name}_${proto}"
  953. tmp_load="${ban_tmpfile}.${src_name}.load"
  954. tmp_file="${ban_tmpfile}.${src_name}.file"
  955. tmp_raw="${tmp_file}.raw"
  956. tmp_cnt="${tmp_file}.cnt"
  957. tmp_err="${tmp_file}.err"
  958. # 'resume' mode
  959. #
  960. if [ "${ban_action}" = "resume" ]
  961. then
  962. if [ "${src_name%_*}" = "maclist" ]
  963. then
  964. src_name="maclist"
  965. fi
  966. f_ipset "resume"
  967. src_rc="${?}"
  968. if [ "${src_rc}" = "0" ]
  969. then
  970. return
  971. fi
  972. fi
  973. # handle local downloads
  974. #
  975. case "${src_name%_*}" in
  976. "blacklist"|"whitelist")
  977. printf "%s\n" "0" > "${tmp_cnt}"
  978. awk "${src_rule}" "${src_url}" > "${tmp_file}"
  979. src_rc="${?}"
  980. if [ "${src_rc}" = "0" ]
  981. then
  982. f_ipset "create"
  983. if [ ! -f "${tmp_dns}" ] && { { [ "${proto}" = "4" ] && [ "${ban_proto4_enabled}" = "1" ]; } || \
  984. { [ "${proto}" = "6" ] && [ "${ban_proto6_enabled}" = "1" ] && [ "${ban_proto4_enabled}" = "0" ]; }; }
  985. then
  986. tmp_dns="${ban_tmpbase}/${src_name%_*}.dns"
  987. src_rule="/^([[:alnum:]_-]{1,63}\\.)+[[:alpha:]]+([[:space:]]|$)/{print tolower(\$1)}"
  988. awk "${src_rule}" "${src_url}" > "${tmp_dns}"
  989. src_rc="${?}"
  990. if [ "${src_rc}" = "0" ] && [ -s "${tmp_dns}" ]
  991. then
  992. ( "${ban_dnsservice}" "${ban_ver}" "${ban_action}" "${src_name%_*}" "${tmp_dns}" & )
  993. else
  994. rm -f "${tmp_dns}"
  995. fi
  996. fi
  997. else
  998. f_log "debug" "f_down ::: name: ${src_name}, url: ${src_url}, rule: ${src_rule}, rc: ${src_rc}"
  999. fi
  1000. return
  1001. ;;
  1002. "maclist")
  1003. src_name="${src_name%_*}"
  1004. tmp_file="${ban_tmpfile}.${src_name}.file"
  1005. tmp_cnt="${tmp_file}.cnt"
  1006. tmp_err="${tmp_file}.err"
  1007. awk "${src_rule}" "${src_url}" > "${tmp_file}"
  1008. src_rc="${?}"
  1009. if [ "${src_rc}" = "0" ]
  1010. then
  1011. f_ipset "create"
  1012. else
  1013. f_log "debug" "f_down ::: name: ${src_name}, url: ${src_url}, rule: ${src_rule}, rc: ${src_rc}"
  1014. fi
  1015. return
  1016. ;;
  1017. esac
  1018. # 'refresh' mode
  1019. #
  1020. if [ "${ban_action}" = "refresh" ]
  1021. then
  1022. f_ipset "refresh"
  1023. src_rc="${?}"
  1024. if [ "${src_rc}" = "0" ]
  1025. then
  1026. return
  1027. fi
  1028. fi
  1029. # 'start' mode
  1030. #
  1031. if [ "${ban_action}" = "start" ]
  1032. then
  1033. f_ipset "restore"
  1034. fi
  1035. src_rc="${?}"
  1036. if [ "${src_rc}" = "0" ]
  1037. then
  1038. awk "${src_rule}" "${tmp_load}" 2>/dev/null > "${tmp_file}"
  1039. src_rc="${?}"
  1040. if [ "${src_rc}" = "0" ]
  1041. then
  1042. f_ipset "create"
  1043. src_rc="${?}"
  1044. if [ "${src_rc}" = "0" ]
  1045. then
  1046. return
  1047. fi
  1048. fi
  1049. fi
  1050. # handle country related downloads
  1051. #
  1052. if [ "${src_name%_*}" = "country" ]
  1053. then
  1054. for country in ${ban_countries}
  1055. do
  1056. src_log="$("${ban_fetchutil}" ${ban_fetchparm} "${tmp_raw}" "${src_url}${country}-aggregated.zone" 2>&1)"
  1057. src_rc="${?}"
  1058. if [ "${src_rc}" = "0" ]
  1059. then
  1060. cat "${tmp_raw}" 2>/dev/null >> "${tmp_load}"
  1061. else
  1062. continue
  1063. fi
  1064. done
  1065. # handle asn related downloads
  1066. #
  1067. elif [ "${src_name%_*}" = "asn" ]
  1068. then
  1069. for asn in ${ban_asns}
  1070. do
  1071. src_log="$("${ban_fetchutil}" ${ban_fetchparm} "${tmp_raw}" "${src_url}AS${asn}" 2>&1)"
  1072. src_rc="${?}"
  1073. if [ "${src_rc}" = "0" ]
  1074. then
  1075. cat "${tmp_raw}" 2>/dev/null >> "${tmp_load}"
  1076. else
  1077. continue
  1078. fi
  1079. done
  1080. # handle compressed downloads
  1081. #
  1082. elif [ -n "${src_comp}" ]
  1083. then
  1084. case "${src_comp}" in
  1085. "gz")
  1086. src_log="$("${ban_fetchutil}" ${ban_fetchparm} "${tmp_raw}" "${src_url}" 2>&1)"
  1087. src_rc="${?}"
  1088. if [ "${src_rc}" -eq 0 ]
  1089. then
  1090. zcat "${tmp_raw}" 2>/dev/null > "${tmp_load}"
  1091. src_rc="${?}"
  1092. fi
  1093. ;;
  1094. esac
  1095. # handle normal downloads
  1096. #
  1097. else
  1098. src_log="$("${ban_fetchutil}" ${ban_fetchparm} "${tmp_load}" "${src_url}" 2>&1)"
  1099. src_rc="${?}"
  1100. fi
  1101. # download post-processing (backup, restore, regex)
  1102. #
  1103. if [ "${src_rc}" = "0" ]
  1104. then
  1105. f_ipset "backup"
  1106. src_rc="${?}"
  1107. elif [ "${ban_action}" != "start" ] && [ "${ban_action}" != "refresh" ]
  1108. then
  1109. f_ipset "restore"
  1110. src_rc="${?}"
  1111. fi
  1112. if [ "${src_rc}" = "0" ]
  1113. then
  1114. awk "${src_rule}" "${tmp_load}" 2>/dev/null > "${tmp_file}"
  1115. src_rc="${?}"
  1116. if [ "${src_rc}" = "0" ]
  1117. then
  1118. f_ipset "create"
  1119. src_rc="${?}"
  1120. elif [ "${ban_action}" != "refresh" ]
  1121. then
  1122. f_ipset "refresh"
  1123. src_rc="${?}"
  1124. fi
  1125. else
  1126. src_log="$(printf "%s" "${src_log}" | awk '{ORS=" ";print $0}')"
  1127. if [ "${ban_action}" != "refresh" ]
  1128. then
  1129. f_ipset "refresh"
  1130. src_rc="${?}"
  1131. fi
  1132. f_log "debug" "f_down ::: name: ${src_name}, url: ${src_url}, rule: ${src_rule}, rc: ${src_rc}, log: ${src_log:-"-"}"
  1133. fi
  1134. }
  1135. # main controller
  1136. #
  1137. f_main()
  1138. {
  1139. local src_name src_url_4 src_rule_4 src_url_6 src_rule_6 src_comp src_rc src_ts log_raw log_merge log_ips log_count hold err_file cnt_file cnt=0
  1140. # prepare logfile excerpts (dropbear, sshd, luci)
  1141. #
  1142. if [ "${ban_autoblacklist}" = "1" ] || [ "${ban_monitor_enabled}" = "1" ]
  1143. then
  1144. log_raw="$(${ban_logread_cmd} -l "${ban_loglimit}")"
  1145. if [ -n "$(printf "%s\n" "${ban_logterms}" | grep -F "dropbear")" ]
  1146. then
  1147. log_ips="$(printf "%s\n" "${log_raw}" | grep -E "Exit before auth from" | \
  1148. awk 'match($0,/<[0-9A-f:\.]+:/){printf "%s\n",substr($0,RSTART+1,RLENGTH-2)}' | awk '!seen[$NF]++' | awk '{ORS=" ";print $NF}')"
  1149. for ip in ${log_ips}
  1150. do
  1151. log_count="$(printf "%s\n" "${log_raw}" | grep -cE "Exit before auth from <${ip}")"
  1152. if [ "${log_count}" -ge "${ban_ssh_logcount}" ]
  1153. then
  1154. log_merge="${log_merge} ${ip}"
  1155. fi
  1156. done
  1157. fi
  1158. if [ -n "$(printf "%s\n" "${ban_logterms}" | grep -F "sshd")" ]
  1159. then
  1160. log_ips="$(printf "%s\n" "${log_raw}" | grep -E "error: maximum authentication attempts exceeded|sshd.*Connection closed by.*\[preauth\]" | \
  1161. awk 'match($0,/[0-9A-f:\.]+ port/){printf "%s\n",substr($0,RSTART,RLENGTH-5)}' | awk '!seen[$NF]++' | awk '{ORS=" ";print $NF}')"
  1162. for ip in ${log_ips}
  1163. do
  1164. log_count="$(printf "%s\n" "${log_raw}" | grep -cE "error: maximum authentication attempts exceeded.*${ip}|sshd.*Connection closed by.*${ip}.*\[preauth\]")"
  1165. if [ "${log_count}" -ge "${ban_ssh_logcount}" ]
  1166. then
  1167. log_merge="${log_merge} ${ip}"
  1168. fi
  1169. done
  1170. fi
  1171. if [ -n "$(printf "%s\n" "${ban_logterms}" | grep -F "luci")" ]
  1172. then
  1173. log_ips="$(printf "%s\n" "${log_raw}" | grep -E "luci: failed login on " | \
  1174. awk 'match($0,/[0-9A-f:\.]+$/){printf "%s\n",substr($0,RSTART,RLENGTH)}' | awk '!seen[$NF]++' | awk '{ORS=" ";print $NF}')"
  1175. for ip in ${log_ips}
  1176. do
  1177. log_count="$(printf "%s\n" "${log_raw}" | grep -cE "luci: failed login on .*from ${ip}")"
  1178. if [ "${log_count}" -ge "${ban_luci_logcount}" ]
  1179. then
  1180. log_merge="${log_merge} ${ip}"
  1181. fi
  1182. done
  1183. fi
  1184. if [ -n "$(printf "%s\n" "${ban_logterms}" | grep -F "nginx")" ]
  1185. then
  1186. log_ips="$(printf "%s\n" "${log_raw}" | grep -oE "nginx\[[0-9]+\]:.*\[error\].*open().*client: [[:alnum:].:]+" | \
  1187. awk '!seen[$NF]++' | awk '{ORS=" ";print $NF}')"
  1188. for ip in ${log_ips}
  1189. do
  1190. log_count="$(printf "%s\n" "${log_raw}" | grep -cE "nginx\[[0-9]+\]:.*\[error\].*open().*client: ${ip}")"
  1191. if [ "${log_count}" -ge "${ban_nginx_logcount}" ]
  1192. then
  1193. log_merge="${log_merge} ${ip}"
  1194. fi
  1195. done
  1196. fi
  1197. fi
  1198. # prepare new black- and whitelist entries
  1199. #
  1200. if [ "${ban_autowhitelist}" = "1" ] && [ -f "${ban_whitelist}" ]
  1201. then
  1202. for ip in ${ban_subnets}
  1203. do
  1204. if [ -z "$(grep -F "${ip}" "${ban_whitelist}")" ]
  1205. then
  1206. src_ts="# added on $(date "+%d.%m.%Y %H:%M:%S")"
  1207. printf "%-42s%s\n" "${ip}" "${src_ts}" >> "${ban_whitelist}"
  1208. f_log "info" "IP address '${ip}' added to whitelist"
  1209. fi
  1210. done
  1211. fi
  1212. if [ "${ban_autoblacklist}" = "1" ] && [ -f "${ban_blacklist}" ]
  1213. then
  1214. for ip in ${log_merge}
  1215. do
  1216. if [ -z "$(grep -F "${ip}" "${ban_blacklist}")" ]
  1217. then
  1218. src_ts="# added on $(date "+%d.%m.%Y %H:%M:%S")"
  1219. printf "%-42s%s\n" "${ip}" "${src_ts}" >> "${ban_blacklist}"
  1220. f_log "info" "IP address '${ip}' added to blacklist"
  1221. fi
  1222. done
  1223. fi
  1224. # initial ipset/iptables creation
  1225. #
  1226. f_ipset "initial"
  1227. if [ "${?}" != "0" ]
  1228. then
  1229. f_log "err" "banIP processing failed, fatal error during ipset/iptables creation (${ban_sysver})"
  1230. fi
  1231. # load local source files (maclist, blacklist, whitelist)
  1232. #
  1233. for src_name in ${ban_localsources}
  1234. do
  1235. if [ "${src_name}" = "maclist" ] && [ -s "${ban_maclist}" ]
  1236. then
  1237. (
  1238. src_rule_4="/^([0-9A-z][0-9A-z]:){5}[0-9A-z]{2}([[:space:]]|$)/{print \"add ${src_name} \"toupper(\$1)}"
  1239. f_down "${src_name}" "mac" "mac" "${ban_maclist}" "${src_rule_4}"
  1240. )&
  1241. fi
  1242. if [ "${ban_proto4_enabled}" = "1" ]
  1243. then
  1244. if [ "${src_name}" = "blacklist" ] && [ -s "${ban_blacklist}" ] && [ "${ban_whitelistonly}" = "0" ]
  1245. then
  1246. (
  1247. src_rule_4="/^(([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:]]|$)/{print \"add ${src_name}_4 \"\$1}"
  1248. f_down "${src_name}" "4" "inet" "${ban_blacklist}" "${src_rule_4}"
  1249. )&
  1250. elif [ "${src_name}" = "whitelist" ] && [ -s "${ban_whitelist}" ]
  1251. then
  1252. (
  1253. src_rule_4="/^(([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:]]|$)/{print \"add ${src_name}_4 \"\$1}"
  1254. f_down "${src_name}" "4" "inet" "${ban_whitelist}" "${src_rule_4}"
  1255. )&
  1256. fi
  1257. else
  1258. (
  1259. src_name="${src_name}_4"
  1260. f_ipset "flush"
  1261. )&
  1262. fi
  1263. if [ "${ban_proto6_enabled}" = "1" ]
  1264. then
  1265. if [ "${src_name}" = "blacklist" ] && [ -s "${ban_blacklist}" ] && [ "${ban_whitelistonly}" = "0" ]
  1266. then
  1267. (
  1268. src_rule_6="/^(([0-9A-f]{0,4}:){1,7}[0-9A-f]{0,4}:?(\\/(1?[0-2][0-8]|[0-9][0-9]))?)([[:space:]]|$)/{print \"add ${src_name}_6 \"\$1}"
  1269. f_down "${src_name}" "6" "inet6" "${ban_blacklist}" "${src_rule_6}"
  1270. )&
  1271. elif [ "${src_name}" = "whitelist" ] && [ -s "${ban_whitelist}" ]
  1272. then
  1273. (
  1274. src_rule_6="/^(([0-9A-f]{0,4}:){1,7}[0-9A-f]{0,4}:?(\\/(1?[0-2][0-8]|[0-9][0-9]))?)([[:space:]]|$)/{print \"add ${src_name}_6 \"\$1}"
  1275. f_down "${src_name}" "6" "inet6" "${ban_whitelist}" "${src_rule_6}"
  1276. )&
  1277. fi
  1278. else
  1279. (
  1280. src_name="${src_name}_6"
  1281. f_ipset "flush"
  1282. )&
  1283. fi
  1284. done
  1285. wait
  1286. # loop over all external sources
  1287. #
  1288. if [ "${ban_whitelistonly}" = "0" ]
  1289. then
  1290. for src_name in ${ban_sources}
  1291. do
  1292. # get source data from JSON file
  1293. #
  1294. json_select "${src_name}" >/dev/null 2>&1
  1295. if [ "${?}" != "0" ]
  1296. then
  1297. continue
  1298. fi
  1299. json_objects="url_4 rule_4 url_6 rule_6 comp"
  1300. for object in ${json_objects}
  1301. do
  1302. eval json_get_var src_${object} "\${object}" >/dev/null 2>&1
  1303. done
  1304. json_select ..
  1305. # handle external IPv4 source downloads in a subshell
  1306. #
  1307. if [ "${ban_proto4_enabled}" = "1" ] && [ -n "${src_url_4}" ] && [ -n "${src_rule_4}" ]
  1308. then
  1309. (
  1310. f_down "${src_name}" "4" "inet" "${src_url_4}" "${src_rule_4}" "${src_comp}"
  1311. )&
  1312. fi
  1313. # handle external IPv6 source downloads in a subshell
  1314. #
  1315. if [ "${ban_proto6_enabled}" = "1" ] && [ -n "${src_url_6}" ] && [ -n "${src_rule_6}" ]
  1316. then
  1317. (
  1318. f_down "${src_name}" "6" "inet6" "${src_url_6}" "${src_rule_6}" "${src_comp}"
  1319. )&
  1320. fi
  1321. # control/limit download queues
  1322. #
  1323. hold=$((cnt%ban_maxqueue))
  1324. if [ "${hold}" = "0" ]
  1325. then
  1326. wait
  1327. fi
  1328. cnt=$((cnt+1))
  1329. done
  1330. wait
  1331. fi
  1332. # error out
  1333. #
  1334. for err_file in "${ban_tmpfile}."*".err"
  1335. do
  1336. if [ -f "${err_file}" ]
  1337. then
  1338. f_log "err" "banIP processing failed, fatal iptables errors during subshell processing (${ban_sysver})"
  1339. fi
  1340. done
  1341. # finish processing
  1342. #
  1343. ban_sources=""
  1344. for cnt_file in "${ban_tmpfile}."*".cnt"
  1345. do
  1346. if [ -f "${cnt_file}" ]
  1347. then
  1348. read -r cnt < "${cnt_file}"
  1349. ban_cnt=$((ban_cnt+cnt))
  1350. ban_setcnt=$((ban_setcnt+1))
  1351. src_name="$(printf "%s" "${cnt_file}" | grep -Eo "[a-z0-9_]+.file.cnt")"
  1352. src_name="${src_name%%.*}"
  1353. if [ -z "$(printf "%s" "${ban_sources}" | grep -F "${src_name%_*}")" ]
  1354. then
  1355. ban_sources="${ban_sources} ${src_name%_*}"
  1356. ban_allsources="${ban_allsources//${src_name%_*}/}"
  1357. fi
  1358. fi
  1359. done
  1360. for src_name in ${ban_allsources}
  1361. do
  1362. if [ "${src_name}" = "maclist" ]
  1363. then
  1364. f_ipset "flush"
  1365. else
  1366. for proto in "4" "6"
  1367. do
  1368. src_name="${src_name%_*}_${proto}"
  1369. f_ipset "flush"
  1370. if [ "${src_name%_*}" != "blacklist" ] && [ "${src_name%_*}" != "whitelist" ]
  1371. then
  1372. f_ipset "remove"
  1373. fi
  1374. done
  1375. fi
  1376. done
  1377. f_log "info" "${ban_setcnt} IPSets with overall ${ban_cnt} IPs/Prefixes loaded successfully (${ban_sysver})"
  1378. f_jsnup
  1379. f_rmtmp
  1380. f_bgsrv "start"
  1381. }
  1382. # query ipsets for certain IP
  1383. #
  1384. f_query()
  1385. {
  1386. local src proto result query_start query_end query_timeout="30" match="0" search="${1}"
  1387. if [ -z "${search}" ]
  1388. then
  1389. printf "%s\n" "::: missing search term, please submit a single ip or mac address :::"
  1390. else
  1391. query_start="$(date "+%s")"
  1392. printf "%s\n%s\n%s\n" ":::" "::: search '${search}' in banIP related IPSets" ":::"
  1393. for src in ${ban_localsources} ${ban_sources} ${ban_extrasources}
  1394. do
  1395. if [ "${src}" = "maclist" ] && [ -n "$("${ban_ipset_cmd}" -q -n list "${src}")" ]
  1396. then
  1397. result="$(ipset -q test ${src} ${search} >/dev/null 2>&1; printf "%u" "${?}")"
  1398. if [ "${result}" = "0" ]
  1399. then
  1400. match="1"
  1401. printf "%s\n" " - found in IPSet '${src}'"
  1402. break
  1403. fi
  1404. else
  1405. for proto in "4" "6"
  1406. do
  1407. if [ -n "$("${ban_ipset_cmd}" -q -n list "${src}_${proto}")" ]
  1408. then
  1409. result="$(ipset -q test ${src}_${proto} ${search} >/dev/null 2>&1; printf "%u" "${?}")"
  1410. if [ "${result}" = "0" ]
  1411. then
  1412. match="1"
  1413. printf "%s\n" " - found in IPSet '${src}_${proto}'"
  1414. fi
  1415. fi
  1416. done
  1417. fi
  1418. query_end="$(date "+%s")"
  1419. if [ "$((query_end-query_start))" -gt "${query_timeout}" ]
  1420. then
  1421. printf "%s\n\n" " - [...]"
  1422. break
  1423. fi
  1424. done
  1425. if [ "${match}" = "0" ]
  1426. then
  1427. printf "%s\n\n" " - no match"
  1428. fi
  1429. fi
  1430. }
  1431. # generate statistics
  1432. #
  1433. f_report()
  1434. {
  1435. local report_json report_txt bg_pid content proto src src_list cnt cnt_mac cnt_cidr cnt_ip cnt_acc cnt_sum="0" cnt_set_sum="1" cnt_acc_sum="0" cnt_mac_sum="0" cnt_ip_sum="0" cnt_cidr_sum="0" cnt_set_sum="0" action="${1}"
  1436. report_json="${ban_reportdir}/ban_report.json"
  1437. report_txt="${ban_reportdir}/ban_mailreport.txt"
  1438. # build json file
  1439. #
  1440. if [ "${action}" != "json" ] && { [ -n "$("${ban_ipt4_savecmd}" | grep " ${ban_chain} ")" ] || [ -n "$("${ban_ipt6_savecmd}" | grep " ${ban_chain} ")" ]; }
  1441. then
  1442. > "${report_json}"
  1443. > "${report_txt}"
  1444. printf "%s\n" "{" >> "${report_json}"
  1445. printf "\t%s\n" "\"ipsets\": {" >> "${report_json}"
  1446. for src in ${ban_localsources} ${ban_sources} ${ban_extrasources}
  1447. do
  1448. if [ -n "$(printf "%s" "${ban_extrasources}" | grep -F "${src}")" ]
  1449. then
  1450. set_type="n/a"
  1451. else
  1452. if [ -n "$(printf "%s\n" "${ban_settype_src}" | grep -F "${src}")" ]
  1453. then
  1454. set_type="src"
  1455. elif [ -n "$(printf "%s\n" "${ban_settype_dst}" | grep -F "${src}")" ]
  1456. then
  1457. set_type="dst"
  1458. elif [ -n "$(printf "%s\n" "${ban_settype_all}" | grep -F "${src}")" ]
  1459. then
  1460. set_type="src+dst"
  1461. else
  1462. set_type="${ban_global_settype}"
  1463. fi
  1464. fi
  1465. if [ "${src}" = "maclist" ]
  1466. then
  1467. src_list="$("${ban_ipset_cmd}" -q list "${src}")"
  1468. if [ -n "${src_list}" ]
  1469. then
  1470. cnt="$(printf "%s" "${src_list}" | awk '/^Number of entries:/{print $4}')"
  1471. cnt_acc="$(printf "%s" "${src_list}" | grep -cE "packets [1-9]+")"
  1472. cnt_acc_sum=$((cnt_acc_sum+cnt_acc))
  1473. cnt_mac_sum="${cnt}"
  1474. cnt_sum=$((cnt_sum+cnt))
  1475. if [ "${cnt_set_sum}" != "0" ]
  1476. then
  1477. printf "%s\n" "," >> "${report_json}"
  1478. fi
  1479. printf "\t\t%s\n" "\"${src}\": {" >> "${report_json}"
  1480. printf "\t\t\t%s\n" "\"type\": \"${set_type}\"," >> "${report_json}"
  1481. printf "\t\t\t%s\n" "\"count\": \"${cnt}\"," >> "${report_json}"
  1482. printf "\t\t\t%s\n" "\"count_ip\": \"0\"," >> "${report_json}"
  1483. printf "\t\t\t%s\n" "\"count_cidr\": \"0\"," >> "${report_json}"
  1484. printf "\t\t\t%s\n" "\"count_mac\": \"${cnt}\"," >> "${report_json}"
  1485. printf "\t\t\t%s" "\"count_acc\": \"${cnt_acc}\"" >> "${report_json}"
  1486. printf ",\n\t\t\t%s" "\"member_acc\": [" >> "${report_json}"
  1487. printf "%s" "${src_list}" | awk 'match($0,/ packets [1-9]+/){printf "%s %s\n",$1,substr($0,RSTART+9,RLENGTH-9)}' | \
  1488. awk 'BEGIN{i=0};{i=i+1;if(i==1){printf "\n\t\t\t\t\t{\n\t\t\t\t\t\t\"member\": \"%s\",\n\t\t\t\t\t\t\"packets\": \"%s\"\n\t\t\t\t\t}",$1,$2}else{printf ",\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\"member\": \"%s\",\n\t\t\t\t\t\t\t\"packets\": \"%s\"\n\t\t\t\t\t\t}",$1,$2}}' >> "${report_json}"
  1489. printf "\n\t\t\t%s\n" "]" >> "${report_json}"
  1490. printf "\t\t%s" "}" >> "${report_json}"
  1491. cnt_set_sum=$((cnt_set_sum+1))
  1492. fi
  1493. else
  1494. for proto in "4" "6"
  1495. do
  1496. src_list="$("${ban_ipset_cmd}" -q list "${src}_${proto}")"
  1497. if [ -n "${src_list}" ]
  1498. then
  1499. cnt="$(printf "%s\n" "${src_list}" | awk '/^Number of entries:/{print $4}')"
  1500. cnt_cidr="$(printf "%s\n" "${src_list}" | grep -cE "/[0-9]{1,3} ")"
  1501. cnt_ip=$((cnt-cnt_cidr-cnt_mac))
  1502. cnt_acc="$(printf "%s\n" "${src_list}" | grep -cE "packets [1-9]+")"
  1503. cnt_cidr_sum=$((cnt_cidr_sum+cnt_cidr))
  1504. cnt_ip_sum=$((cnt_ip_sum+cnt_ip))
  1505. cnt_acc_sum=$((cnt_acc_sum+cnt_acc))
  1506. cnt_sum=$((cnt_sum+cnt))
  1507. if [ "${cnt_set_sum}" != "0" ]
  1508. then
  1509. printf "%s\n" "," >> "${report_json}"
  1510. fi
  1511. printf "\t\t%s\n" "\"${src}_${proto}\": {" >> "${report_json}"
  1512. printf "\t\t\t%s\n" "\"type\": \"${set_type}\"," >> "${report_json}"
  1513. printf "\t\t\t%s\n" "\"count\": \"${cnt}\"," >> "${report_json}"
  1514. printf "\t\t\t%s\n" "\"count_ip\": \"${cnt_ip}\"," >> "${report_json}"
  1515. printf "\t\t\t%s\n" "\"count_cidr\": \"${cnt_cidr}\"," >> "${report_json}"
  1516. printf "\t\t\t%s\n" "\"count_mac\": \"0\"," >> "${report_json}"
  1517. printf "\t\t\t%s" "\"count_acc\": \"${cnt_acc}\"" >> "${report_json}"
  1518. printf ",\n\t\t\t%s" "\"member_acc\": [" >> "${report_json}"
  1519. printf "%s" "${src_list}" | awk 'match($0,/ packets [1-9]+/){printf "%s %s\n",$1,substr($0,RSTART+9,RLENGTH-9)}' | \
  1520. awk 'BEGIN{i=0};{i=i+1;if(i==1){printf "\n\t\t\t\t\t{\n\t\t\t\t\t\t\"member\": \"%s\",\n\t\t\t\t\t\t\"packets\": \"%s\"\n\t\t\t\t\t}",$1,$2}else{printf ",\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\"member\": \"%s\",\n\t\t\t\t\t\t\t\"packets\": \"%s\"\n\t\t\t\t\t\t}",$1,$2}}' >> "${report_json}"
  1521. printf "\n\t\t\t%s\n" "]" >> "${report_json}"
  1522. printf "\t\t%s" "}" >> "${report_json}"
  1523. cnt_set_sum=$((cnt_set_sum+1))
  1524. fi
  1525. done
  1526. fi
  1527. done
  1528. printf "\n\t%s" "}" >> "${report_json}"
  1529. printf ",\n\t%s\n" "\"timestamp\": \"$(date "+%d.%m.%Y %H:%M:%S")\"," >> "${report_json}"
  1530. printf "\t%s\n" "\"cnt_set_sum\": \"${cnt_set_sum}\"," >> "${report_json}"
  1531. printf "\t%s\n" "\"cnt_ip_sum\": \"${cnt_ip_sum}\"," >> "${report_json}"
  1532. printf "\t%s\n" "\"cnt_cidr_sum\": \"${cnt_cidr_sum}\"," >> "${report_json}"
  1533. printf "\t%s\n" "\"cnt_mac_sum\": \"${cnt_mac_sum}\"," >> "${report_json}"
  1534. printf "\t%s\n" "\"cnt_sum\": \"${cnt_sum}\"," >> "${report_json}"
  1535. printf "\t%s\n" "\"cnt_acc_sum\": \"${cnt_acc_sum}\"" >> "${report_json}"
  1536. printf "%s\n" "}" >> "${report_json}"
  1537. fi
  1538. # output preparation
  1539. #
  1540. if [ -s "${report_json}" ] && { [ "${action}" = "cli" ] || [ "${action}" = "mail" ]; }
  1541. then
  1542. printf "%s\n%s\n%s\n" ":::" "::: report on all banIP related IPSets" ":::" >> "${report_txt}"
  1543. json_load_file "${report_json}" >/dev/null 2>&1
  1544. json_get_var value "timestamp" >/dev/null 2>&1
  1545. printf " + %s\n" "Report timestamp ::: ${value}" >> "${report_txt}"
  1546. json_get_var value "cnt_set_sum" >/dev/null 2>&1
  1547. printf " + %s\n" "Number of all IPSets ::: ${value:-"0"}" >> "${report_txt}"
  1548. json_get_var value "cnt_sum" >/dev/null 2>&1
  1549. printf " + %s\n" "Number of all entries ::: ${value:-"0"}" >> "${report_txt}"
  1550. json_get_var value "cnt_ip_sum" >/dev/null 2>&1
  1551. printf " + %s\n" "Number of IP entries ::: ${value:-"0"}" >> "${report_txt}"
  1552. json_get_var value "cnt_cidr_sum" >/dev/null 2>&1
  1553. printf " + %s\n" "Number of CIDR entries ::: ${value:-"0"}" >> "${report_txt}"
  1554. json_get_var value "cnt_mac_sum" >/dev/null 2>&1
  1555. printf " + %s\n" "Number of MAC entries ::: ${value:-"0"}" >> "${report_txt}"
  1556. json_get_var value "cnt_acc_sum" >/dev/null 2>&1
  1557. printf " + %s\n" "Number of accessed entries ::: ${value:-"0"}" >> "${report_txt}"
  1558. json_select "ipsets"
  1559. json_get_keys ipsetlist
  1560. if [ -n "${ipsetlist}" ]
  1561. then
  1562. printf "%s\n%s\n%s\n" ":::" "::: IPSet details" ":::" >> "${report_txt}"
  1563. printf "%-25s%-12s%-11s%-10s%-10s%-10s%-10s%s\n" " Name" "Type" "Count" "Cnt_IP" "Cnt_CIDR" "Cnt_MAC" "Cnt_ACC" "Entry details (Entry/Count)" >> "${report_txt}"
  1564. printf "%s\n" " --------------------------------------------------------------------------------------------------------------------" >> "${report_txt}"
  1565. fi
  1566. for ipset in ${ipsetlist}
  1567. do
  1568. set_info="${ipset}"
  1569. acc_info=""
  1570. json_select "${ipset}"
  1571. json_get_keys detaillist
  1572. for detail in ${detaillist}
  1573. do
  1574. if [ "${detail}" != "member_acc" ]
  1575. then
  1576. json_get_var value "${detail}" >/dev/null 2>&1
  1577. set_info="${set_info} ${value}"
  1578. elif [ "${detail}" = "member_acc" ]
  1579. then
  1580. index=1
  1581. json_select "${detail}"
  1582. while json_get_type type "${index}" && [ "${type}" = "object" ]
  1583. do
  1584. json_get_values values "${index}" >/dev/null 2>&1
  1585. acc_info="${acc_info} ${values}"
  1586. index=$((index+1))
  1587. done
  1588. json_select ".."
  1589. fi
  1590. done
  1591. printf " %-21s%-12s%-11s%-10s%-10s%-10s%s\n" ${set_info} >> "${report_txt}"
  1592. if [ -n "${acc_info}" ]
  1593. then
  1594. printf " %-25s%s\n" ${acc_info} >> "${report_txt}"
  1595. fi
  1596. printf "%s\n" " --------------------------------------------------------------------------------------------------------------------" >> "${report_txt}"
  1597. json_select ".."
  1598. done
  1599. content="$(cat "${report_txt}" 2>/dev/null)"
  1600. rm -f "${report_txt}"
  1601. fi
  1602. # report output
  1603. #
  1604. if [ "${action}" = "cli" ]
  1605. then
  1606. printf "%s\n" "${content}"
  1607. elif [ "${action}" = "json" ]
  1608. then
  1609. cat "${ban_reportdir}/ban_report.json"
  1610. elif [ "${action}" = "mail" ] && [ "${ban_mail_enabled}" = "1" ] && [ -x "${ban_mailservice}" ]
  1611. then
  1612. ( "${ban_mailservice}" "${ban_ver}" "${content}" >/dev/null 2>&1 )&
  1613. bg_pid="${!}"
  1614. fi
  1615. f_log "debug" "f_report ::: action: ${action}, report_json: ${report_json}, report_txt: ${report_txt}, bg_pid: ${bg_pid:-"-"}"
  1616. }
  1617. # update runtime information
  1618. #
  1619. f_jsnup()
  1620. {
  1621. local memory entry runtime cnt_info status="${1:-"enabled"}"
  1622. if [ "${status}" = "enabled" ] || [ "${status}" = "error" ]
  1623. then
  1624. ban_endtime="$(date "+%s")"
  1625. cnt_info="${ban_setcnt} IPSets with ${ban_cnt} IPs/Prefixes"
  1626. memory="$(awk '/^MemTotal|^MemFree|^MemAvailable/{ORS="/"; print int($2/1000)}' "/proc/meminfo" 2>/dev/null | awk '{print substr($0,1,length($0)-1)}')"
  1627. if [ "$(( (ban_endtime-ban_starttime)/60 ))" -lt "60" ]
  1628. then
  1629. runtime="${ban_action}, $(( (ban_endtime-ban_starttime)/60 ))m $(( (ban_endtime-ban_starttime)%60 ))s, ${memory:-0}, $(date "+%d.%m.%Y %H:%M:%S")"
  1630. else
  1631. runtime="${ban_action}, n/a, ${memory:-0}, $(date "+%d.%m.%Y %H:%M:%S")"
  1632. fi
  1633. fi
  1634. > "${ban_rtfile}"
  1635. json_load_file "${ban_rtfile}" >/dev/null 2>&1
  1636. json_init
  1637. json_add_string "status" "${status}"
  1638. json_add_string "version" "${ban_ver}"
  1639. json_add_string "ipset_info" "${cnt_info:-"-"}"
  1640. json_add_array "active_sources"
  1641. if [ "${status}" = "running" ] || [ "${status}" = "error" ]
  1642. then
  1643. json_add_object
  1644. json_add_string "source" "-"
  1645. json_close_object
  1646. else
  1647. for entry in ${ban_sources}
  1648. do
  1649. json_add_object
  1650. json_add_string "source" "${entry}"
  1651. json_close_object
  1652. done
  1653. fi
  1654. json_close_array
  1655. json_add_array "active_devs"
  1656. for entry in ${ban_devs}
  1657. do
  1658. json_add_object
  1659. json_add_string "dev" "${entry}"
  1660. json_close_object
  1661. done
  1662. json_close_array
  1663. json_add_array "active_ifaces"
  1664. for entry in ${ban_ifaces}
  1665. do
  1666. json_add_object
  1667. json_add_string "iface" "${entry}"
  1668. json_close_object
  1669. done
  1670. json_close_array
  1671. json_add_array "active_logterms"
  1672. for entry in ${ban_logterms}
  1673. do
  1674. json_add_object
  1675. json_add_string "term" "${entry}"
  1676. json_close_object
  1677. done
  1678. json_close_array
  1679. json_add_array "active_subnets"
  1680. for entry in ${ban_subnets}
  1681. do
  1682. json_add_object
  1683. json_add_string "subnet" "${entry}"
  1684. json_close_object
  1685. done
  1686. json_close_array
  1687. json_add_string "run_infos" "settype: ${ban_global_settype}, backup_dir: ${ban_backupdir}, report_dir: ${ban_reportdir}"
  1688. json_add_string "run_flags" "protocols (4/6): $(f_char ${ban_proto4_enabled})/$(f_char ${ban_proto6_enabled}), log (src/dst): $(f_char ${ban_logsrc_enabled})/$(f_char ${ban_logdst_enabled}), monitor: $(f_char ${ban_monitor_enabled}), mail: $(f_char ${ban_mail_enabled}), whitelist only: $(f_char ${ban_whitelistonly})"
  1689. json_add_string "last_run" "${runtime:-"-"}"
  1690. json_add_string "system" "${ban_sysver}"
  1691. json_dump > "${ban_rtfile}"
  1692. if [ "${ban_mail_enabled}" = "1" ] && [ -x "${ban_mailservice}" ] && { [ "${status}" = "error" ] || \
  1693. { [ "${status}" = "enabled" ] && { [ -z "${ban_mailactions}" ] || [ -n "$(printf "%s\n" "${ban_mailactions}" | grep -F "${ban_action}")" ]; }; }; }
  1694. then
  1695. ( "${ban_mailservice}" "${ban_ver}" >/dev/null 2>&1 )&
  1696. bg_pid="${!}"
  1697. fi
  1698. f_log "debug" "f_jsnup ::: status: ${status:-"-"}, action: ${ban_action}, mail_enabled: ${ban_mail_enabled}, mail_actions: ${ban_mailactions}, mail_service: ${ban_mailservice}, mail_pid: ${bg_pid:-"-"}"
  1699. }
  1700. # source required system libraries
  1701. #
  1702. if [ -r "/lib/functions.sh" ] && [ -r "/lib/functions/network.sh" ] && [ -r "/usr/share/libubox/jshn.sh" ]
  1703. then
  1704. . "/lib/functions.sh"
  1705. . "/lib/functions/network.sh"
  1706. . "/usr/share/libubox/jshn.sh"
  1707. else
  1708. f_log "err" "system libraries not found"
  1709. fi
  1710. if [ "${ban_action}" = "suspend" ] || [ "${ban_action}" = "resume" ] || \
  1711. [ "${ban_action}" = "report" ] || [ "${ban_action}" = "query" ]
  1712. then
  1713. json_load_file "${ban_rtfile}" >/dev/null 2>&1
  1714. json_get_var ban_status "status"
  1715. fi
  1716. # version information
  1717. #
  1718. if [ "${ban_action}" = "version" ]
  1719. then
  1720. printf "%s\n" "${ban_ver}"
  1721. exit 0
  1722. fi
  1723. # handle different banIP actions
  1724. #
  1725. f_load
  1726. case "${ban_action}" in
  1727. "stop")
  1728. f_bgsrv "stop"
  1729. f_ipset "destroy"
  1730. f_jsnup "stopped"
  1731. f_rmbckp
  1732. ;;
  1733. "restart")
  1734. f_ipset "destroy"
  1735. f_rmbckp
  1736. f_env
  1737. f_main
  1738. ;;
  1739. "suspend")
  1740. if [ "${ban_status}" = "enabled" ] && [ "${ban_whitelistonly}" = "0" ]
  1741. then
  1742. f_bgsrv "stop"
  1743. f_jsnup "running"
  1744. f_ipset "suspend"
  1745. f_jsnup "paused"
  1746. fi
  1747. f_rmtmp
  1748. ;;
  1749. "resume")
  1750. if [ "${ban_status}" = "paused" ] && [ "${ban_whitelistonly}" = "0" ]
  1751. then
  1752. f_env
  1753. f_main
  1754. else
  1755. f_rmtmp
  1756. fi
  1757. ;;
  1758. "query")
  1759. if [ "${ban_status}" = "enabled" ]
  1760. then
  1761. f_query "${2}"
  1762. fi
  1763. ;;
  1764. "report")
  1765. if [ "${ban_status}" = "enabled" ] || [ "${2}" = "json" ]
  1766. then
  1767. f_report "${2}"
  1768. fi
  1769. ;;
  1770. "start"|"reload"|"refresh")
  1771. f_env
  1772. f_main
  1773. ;;
  1774. esac