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.

461 lines
13 KiB

  1. #!/bin/sh
  2. # dns based ad/abuse domain blocking
  3. # written by Dirk Brenken (dev@brenken.org)
  4. # This is free software, licensed under the GNU General Public License v3.
  5. # You should have received a copy of the GNU General Public License
  6. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  7. # set initial defaults
  8. #
  9. LC_ALL=C
  10. PATH="/usr/sbin:/usr/bin:/sbin:/bin"
  11. adb_ver="2.0.2"
  12. adb_enabled=1
  13. adb_debug=0
  14. adb_whitelist="/etc/adblock/adblock.whitelist"
  15. adb_whitelist_rset="\$1 ~/^([A-Za-z0-9_-]+\.){1,}[A-Za-z]+/{print tolower(\"^\"\$1\"\\\|[.]\"\$1)}"
  16. adb_dns="dnsmasq"
  17. adb_dnsdir="/tmp/dnsmasq.d"
  18. adb_dnshidedir="${adb_dnsdir}/.adb_hidden"
  19. adb_dnsprefix="adb_list"
  20. adb_dnsformat="awk '{print \"local=/\"\$0\"/\"}'"
  21. adb_fetch="/usr/bin/wget"
  22. adb_fetchparm="--no-config --quiet --tries=1 --no-cache --no-cookies --max-redirect=0 --timeout=5 --no-check-certificate -O"
  23. # f_envload: load adblock environment
  24. #
  25. f_envload()
  26. {
  27. # source in system library
  28. #
  29. if [ -r "/lib/functions.sh" ]
  30. then
  31. . "/lib/functions.sh"
  32. else
  33. f_log "error" "status ::: system library not found"
  34. fi
  35. # parse global section by callback
  36. #
  37. config_cb()
  38. {
  39. local type="${1}"
  40. if [ "${type}" = "adblock" ]
  41. then
  42. option_cb()
  43. {
  44. local option="${1}"
  45. local value="${2}"
  46. eval "${option}=\"${value}\""
  47. }
  48. else
  49. reset_cb
  50. fi
  51. }
  52. # parse 'service' and 'source' sections
  53. #
  54. parse_config()
  55. {
  56. local value opt section="${1}" options="enabled adb_dir adb_src adb_src_rset adb_src_cat"
  57. if [ "${section}" != "backup" ]
  58. then
  59. eval "adb_sources=\"${adb_sources} ${section}\""
  60. fi
  61. for opt in ${options}
  62. do
  63. config_get value "${section}" "${opt}"
  64. if [ -n "${value}" ]
  65. then
  66. eval "${opt}_${section}=\"${value}\""
  67. fi
  68. done
  69. }
  70. # load adblock config
  71. #
  72. config_load adblock
  73. config_foreach parse_config service
  74. config_foreach parse_config source
  75. }
  76. # f_envcheck: check/set environment prerequisites
  77. #
  78. f_envcheck()
  79. {
  80. # check 'enabled' option
  81. #
  82. if [ "${adb_enabled}" != "1" ]
  83. then
  84. if [ "$(ls -dA "${adb_dnsdir}/${adb_dnsprefix}"* >/dev/null 2>&1)" ]
  85. then
  86. f_rmdns
  87. f_dnsrestart
  88. fi
  89. f_log "info " "status ::: adblock is currently disabled, please set adb_enabled to '1' to use this service"
  90. exit 0
  91. fi
  92. # check fetch utility
  93. #
  94. if [ -z "${adb_fetch}" ] || [ ! -f "${adb_fetch}" ]
  95. then
  96. f_log "error" "status ::: no download utility with ssl support found/configured"
  97. fi
  98. # create dns hideout directory
  99. #
  100. if [ ! -d "${adb_dnshidedir}" ]
  101. then
  102. mkdir -p -m 660 "${adb_dnshidedir}"
  103. else
  104. rm -f "${adb_dnshidedir}/${adb_dnsprefix}"*
  105. fi
  106. # create adblock temp file/directory
  107. #
  108. adb_tmpload="$(mktemp -tu)"
  109. adb_tmpfile="$(mktemp -tu)"
  110. adb_tmpdir="$(mktemp -p /tmp -d)"
  111. # prepare whitelist entries
  112. #
  113. if [ -s "${adb_whitelist}" ]
  114. then
  115. awk "${adb_whitelist_rset}" "${adb_whitelist}" > "${adb_tmpdir}/tmp.whitelist"
  116. fi
  117. # get system information
  118. #
  119. adb_sysver="$(ubus -S call system board | jsonfilter -e '@.release.description')"
  120. }
  121. # f_rmtemp: remove temporary files & directories
  122. #
  123. f_rmtemp()
  124. {
  125. rm -f "${adb_tmpload}"
  126. rm -f "${adb_tmpfile}"
  127. rm -rf "${adb_tmpdir}"
  128. }
  129. # f_rmdns: remove dns related files & directories
  130. #
  131. f_rmdns()
  132. {
  133. rm -f "${adb_dnsdir}/${adb_dnsprefix}"*
  134. rm -f "${adb_dir_backup}/${adb_dnsprefix}"*.gz
  135. rm -rf "${adb_dnshidedir}"
  136. ubus call service delete "{\"name\":\"adblock_stats\",\"instances\":\"stats\"}"
  137. }
  138. # f_dnsrestart: restart the dns server
  139. #
  140. f_dnsrestart()
  141. {
  142. local cnt=0
  143. dns_running="false"
  144. sync
  145. killall -q -TERM "${adb_dns}"
  146. while [ ${cnt} -le 10 ]
  147. do
  148. dns_running="$(ubus -S call service list '{"name":"dnsmasq"}' | jsonfilter -l 1 -e '@.dnsmasq.instances.*.running')"
  149. if [ "${dns_running}" = "true" ]
  150. then
  151. return 0
  152. fi
  153. cnt=$((cnt+1))
  154. sleep 1
  155. done
  156. /etc/init.d/"${adb_dns}" restart
  157. sleep 1
  158. }
  159. # f_list: backup/restore/remove block lists
  160. #
  161. f_list()
  162. {
  163. local mode="${1}"
  164. if [ "${enabled_backup}" = "1" ] && [ -d "${adb_dir_backup}" ]
  165. then
  166. case "${mode}" in
  167. backup)
  168. gzip -cf "${adb_tmpfile}" > "${adb_dir_backup}/${adb_dnsprefix}.${src_name}.gz"
  169. ;;
  170. restore)
  171. rm -f "${adb_dnsdir}/${adb_dnsprefix}.${src_name}"
  172. if [ -f "${adb_dir_backup}/${adb_dnsprefix}.${src_name}.gz" ]
  173. then
  174. gunzip -cf "${adb_dir_backup}/${adb_dnsprefix}.${src_name}.gz" > "${adb_tmpfile}"
  175. fi
  176. ;;
  177. remove)
  178. rm -f "${adb_dnsdir}/${adb_dnsprefix}.${src_name}"
  179. if [ -f "${adb_dir_backup}/${adb_dnsprefix}.${src_name}.gz" ]
  180. then
  181. rm -f "${adb_dir_backup}/${adb_dnsprefix}.${src_name}.gz"
  182. fi
  183. ;;
  184. esac
  185. fi
  186. }
  187. # f_switch: suspend/resume adblock processing
  188. #
  189. f_switch()
  190. {
  191. if [ -d "${adb_dnshidedir}" ]
  192. then
  193. local source target status mode="${1}"
  194. local dns_active="$(find "${adb_dnsdir}" -maxdepth 1 -type f -name "${adb_dnsprefix}*" -print)"
  195. local dns_passive="$(find "${adb_dnshidedir}" -maxdepth 1 -type f -name "${adb_dnsprefix}*" -print)"
  196. if [ -n "${dns_active}" ] && [ "${mode}" = "suspend" ]
  197. then
  198. source="${adb_dnsdir}/${adb_dnsprefix}"
  199. target="${adb_dnshidedir}"
  200. status="suspended"
  201. elif [ -n "${dns_passive}" ] && [ "${mode}" = "resume" ]
  202. then
  203. source="${adb_dnshidedir}/${adb_dnsprefix}"
  204. target="${adb_dnsdir}"
  205. status="resumed"
  206. fi
  207. if [ -n "${status}" ]
  208. then
  209. mv -f "${source}"* "${target}"
  210. f_dnsrestart
  211. f_log "info " "status ::: adblock processing ${status}"
  212. fi
  213. fi
  214. }
  215. # f_query: query block lists for certain (sub-)domains
  216. #
  217. f_query()
  218. {
  219. local search result cnt
  220. local domain="${1}"
  221. local tld="${domain#*.}"
  222. local dns_active="$(find "${adb_dnsdir}" -maxdepth 1 -type f -name "${adb_dnsprefix}*" -print)"
  223. if [ -z "${dns_active}" ]
  224. then
  225. printf "%s\n" ":: no active block lists found, please start adblock first"
  226. elif [ -z "${domain}" ] || [ "${domain}" = "${tld}" ]
  227. then
  228. printf "%s\n" ":: invalid domain input, please submit a specific (sub-)domain, i.e. 'www.abc.xyz'"
  229. else
  230. while [ "${domain}" != "${tld}" ]
  231. do
  232. search="${domain//./\.}"
  233. result="$(grep -Hm 1 "[/\.]${search}/" "${adb_dnsdir}/${adb_dnsprefix}"* | awk -F ':|/' '{print " "$4"\t: "$6}')"
  234. cnt="$(grep -hc "[/\.]${search}/" "${adb_dnsdir}/${adb_dnsprefix}"* | awk '{sum += $1} END {printf sum}')"
  235. printf "%s\n" ":: distinct results for domain '${domain}' (overall ${cnt})"
  236. if [ -z "${result}" ]
  237. then
  238. printf "%s\n" " no matches in active block lists"
  239. else
  240. printf "%s\n" "${result}"
  241. fi
  242. domain="${tld}"
  243. tld="${domain#*.}"
  244. done
  245. fi
  246. }
  247. # f_log: write to syslog, exit on error
  248. #
  249. f_log()
  250. {
  251. local class="${1}"
  252. local log_msg="${2}"
  253. if [ -n "${log_msg}" ] && ([ "${class}" != "debug" ] || [ ${adb_debug} -eq 1 ])
  254. then
  255. logger -t "adblock-[${adb_ver}] ${class}" "${log_msg}"
  256. if [ "${class}" = "error" ]
  257. then
  258. f_debug
  259. f_rmtemp
  260. f_rmdns
  261. f_dnsrestart
  262. exit 255
  263. fi
  264. fi
  265. }
  266. # f_debug: gather memory & space information
  267. f_debug()
  268. {
  269. local mem_total=0 mem_free=0 mem_swap=0 tmp_space=0 backup_space=0
  270. if [ ${adb_debug} -eq 1 ]
  271. then
  272. mem_total="$(awk '$1 ~ /^MemTotal/ {printf $2}' "/proc/meminfo")"
  273. mem_free="$(awk '$1 ~ /^MemFree/ {printf $2}' "/proc/meminfo")"
  274. mem_swap="$(awk '$1 ~ /^SwapTotal/ {printf $2}' "/proc/meminfo")"
  275. f_log "debug" "memory ::: total: ${mem_total}, free: ${mem_free}, swap: ${mem_swap}"
  276. if [ -d "${adb_tmpdir}" ]
  277. then
  278. tmp_space="$(df "${adb_tmpdir}" 2>/dev/null | tail -n1 | awk '{printf $4}')"
  279. fi
  280. if [ -d "${adb_dir_backup}" ]
  281. then
  282. backup_space="$(df "${adb_dir_backup}" 2>/dev/null | tail -n1 | awk '{printf $4}')"
  283. fi
  284. f_log "debug" "space ::: tmp_dir: ${adb_tmpdir}, tmp_kb: ${tmp_space}, backup: ${enabled_backup}, backup_dir: ${adb_dir_backup}, backup_kb: ${backup_space}"
  285. fi
  286. }
  287. # main function for block list processing
  288. #
  289. f_main()
  290. {
  291. local enabled url rc cnt sum_cnt=0
  292. local src_name src_rset shalla_file shalla_archive
  293. f_debug
  294. f_log "debug" "main ::: tool: ${adb_fetch}, parm: ${adb_fetchparm}"
  295. for src_name in ${adb_sources}
  296. do
  297. eval "enabled=\"\${enabled_${src_name}}\""
  298. eval "url=\"\${adb_src_${src_name}}\""
  299. eval "src_rset=\"\${adb_src_rset_${src_name}}\""
  300. adb_dnsfile="${adb_dnsdir}/${adb_dnsprefix}.${src_name}"
  301. > "${adb_tmpload}"
  302. > "${adb_tmpfile}"
  303. # basic pre-checks
  304. #
  305. if [ "${enabled}" = "0" ] || [ -z "${url}" ] || [ -z "${src_rset}" ]
  306. then
  307. f_list remove
  308. continue
  309. fi
  310. # download block list
  311. #
  312. f_log "debug" "loop ::: name: ${src_name}, enabled: ${enabled}, dnsfile: ${adb_dnsfile}"
  313. if [ "${src_name}" = "blacklist" ]
  314. then
  315. cat "${url}" > "${adb_tmpload}"
  316. rc=${?}
  317. elif [ "${src_name}" = "shalla" ]
  318. then
  319. shalla_archive="${adb_tmpdir}/shallalist.tar.gz"
  320. shalla_file="${adb_tmpdir}/shallalist.txt"
  321. "${adb_fetch}" ${adb_fetchparm} "${shalla_archive}" "${url}"
  322. rc=${?}
  323. if [ ${rc} -eq 0 ]
  324. then
  325. > "${shalla_file}"
  326. for category in ${adb_src_cat_shalla}
  327. do
  328. tar -xOzf "${shalla_archive}" BL/${category}/domains >> "${shalla_file}"
  329. rc=${?}
  330. if [ ${rc} -ne 0 ]
  331. then
  332. break
  333. fi
  334. done
  335. cat "${shalla_file}" > "${adb_tmpload}"
  336. rm -f "${shalla_file}"
  337. fi
  338. rm -f "${shalla_archive}"
  339. rm -rf "${adb_tmpdir}/BL"
  340. else
  341. "${adb_fetch}" ${adb_fetchparm} "${adb_tmpload}" "${url}"
  342. rc=${?}
  343. fi
  344. # check download result and prepare domain output (incl. list backup/restore)
  345. #
  346. f_log "debug" "loop ::: name: ${src_name}, load-rc: ${rc}"
  347. if [ ${rc} -eq 0 ] && [ -s "${adb_tmpload}" ]
  348. then
  349. awk "${src_rset}" "${adb_tmpload}" > "${adb_tmpfile}"
  350. if [ -s "${adb_tmpfile}" ]
  351. then
  352. f_list backup
  353. else
  354. f_list restore
  355. fi
  356. else
  357. f_list restore
  358. fi
  359. # remove whitelist domains, sort and make them unique, final list preparation
  360. #
  361. if [ -s "${adb_tmpfile}" ]
  362. then
  363. if [ -s "${adb_tmpdir}/tmp.whitelist" ]
  364. then
  365. grep -vf "${adb_tmpdir}/tmp.whitelist" "${adb_tmpfile}" | sort -u | eval "${adb_dnsformat}" > "${adb_dnsfile}"
  366. else
  367. sort -u "${adb_tmpfile}" | eval "${adb_dnsformat}" > "${adb_dnsfile}"
  368. fi
  369. rc=${?}
  370. if [ ${rc} -ne 0 ]
  371. then
  372. f_list remove
  373. fi
  374. fi
  375. f_log "debug" "loop ::: name: ${src_name}, list-rc: ${rc}"
  376. done
  377. # make overall sort, restart & check dns server
  378. #
  379. for src_name in $(ls -dASr "${adb_dnsdir}/${adb_dnsprefix}"* 2>/dev/null)
  380. do
  381. if [ -s "${adb_tmpdir}/blocklist.overall" ]
  382. then
  383. sort "${adb_tmpdir}/blocklist.overall" "${adb_tmpdir}/blocklist.overall" "${src_name}" | uniq -u > "${adb_tmpdir}/tmp.blocklist"
  384. cat "${adb_tmpdir}/tmp.blocklist" > "${src_name}"
  385. fi
  386. cat "${src_name}" >> "${adb_tmpdir}/blocklist.overall"
  387. cnt="$(wc -l < "${src_name}")"
  388. sum_cnt=$((sum_cnt + cnt))
  389. done
  390. f_dnsrestart
  391. if [ "${dns_running}" = "true" ]
  392. then
  393. f_debug
  394. f_rmtemp
  395. f_log "info " "status ::: block lists with overall ${sum_cnt} domains loaded (${adb_sysver})"
  396. ubus call service set "{\"name\":\"adblock_stats\",\"instances\":{\"stats\":{\"env\":{\"blocked_domains\":\"${sum_cnt}\",\"last_rundate\":\"$(/bin/date "+%d.%m.%Y %H:%M:%S")\"}}}}"
  397. exit 0
  398. fi
  399. f_log "error" "status ::: dns server restart with active block lists failed"
  400. }
  401. # handle different adblock actions
  402. #
  403. if [ "${adb_procd}" = "true" ]
  404. then
  405. f_envload
  406. case "${1}" in
  407. stop)
  408. f_rmtemp
  409. f_rmdns
  410. f_dnsrestart
  411. ;;
  412. suspend)
  413. f_switch suspend
  414. ;;
  415. resume)
  416. f_switch resume
  417. ;;
  418. query)
  419. f_query "${2}"
  420. ;;
  421. *)
  422. f_envcheck
  423. f_main
  424. ;;
  425. esac
  426. fi
  427. exit 0