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.

536 lines
16 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.3.0-3"
  12. adb_enabled=1
  13. adb_debug=0
  14. adb_backup=0
  15. adb_backupdir="/mnt"
  16. adb_whitelist="/etc/adblock/adblock.whitelist"
  17. adb_whitelist_rset="\$1 ~/^([A-Za-z0-9_-]+\.){1,}[A-Za-z]+/{print tolower(\"^\"\$1\"\\\|[.]\"\$1)}"
  18. adb_fetch="/usr/bin/wget"
  19. adb_fetchparm="--no-config --quiet --no-cache --no-cookies --max-redirect=0 --timeout=10 --no-check-certificate -O"
  20. adb_dnslist="dnsmasq unbound"
  21. adb_dnsprefix="adb_list"
  22. # f_envload: load adblock environment
  23. #
  24. f_envload()
  25. {
  26. local dns_up cnt=0
  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. # set dns backend environment
  36. #
  37. while [ ${cnt} -le 10 ]
  38. do
  39. for dns in ${adb_dnslist}
  40. do
  41. dns_up="$(ubus -S call service list "{\"name\":\"${dns}\"}" | jsonfilter -l1 -e "@.${dns}.instances.*.running")"
  42. if [ "${dns_up}" = "true" ]
  43. then
  44. case "${dns}" in
  45. dnsmasq)
  46. adb_dns="dnsmasq"
  47. adb_dnsdir="/tmp/dnsmasq.d"
  48. adb_dnshidedir="${adb_dnsdir}/.adb_hidden"
  49. adb_dnsformat="awk '{print \"local=/\"\$0\"/\"}'"
  50. break 2
  51. ;;
  52. unbound)
  53. adb_dns="unbound"
  54. adb_dnsdir="/var/lib/unbound"
  55. adb_dnshidedir="${adb_dnsdir}/.adb_hidden"
  56. adb_dnsformat="awk '{print \"local-zone: \042\"\$0\"\042 static\"}'"
  57. break 2
  58. ;;
  59. esac
  60. fi
  61. done
  62. sleep 1
  63. cnt=$((cnt+1))
  64. done
  65. if [ -z "${adb_dns}" ]
  66. then
  67. f_log "error" "status ::: no active/supported DNS backend found"
  68. fi
  69. # parse global section by callback
  70. #
  71. config_cb()
  72. {
  73. local type="${1}"
  74. if [ "${type}" = "adblock" ]
  75. then
  76. option_cb()
  77. {
  78. local option="${1}"
  79. local value="${2}"
  80. eval "${option}=\"${value}\""
  81. }
  82. else
  83. reset_cb
  84. fi
  85. }
  86. # parse 'source' section
  87. #
  88. parse_config()
  89. {
  90. local value opt section="${1}" options="enabled adb_src adb_src_rset adb_src_cat"
  91. eval "adb_sources=\"${adb_sources} ${section}\""
  92. for opt in ${options}
  93. do
  94. config_get value "${section}" "${opt}"
  95. if [ -n "${value}" ]
  96. then
  97. eval "${opt}_${section}=\"${value}\""
  98. fi
  99. done
  100. }
  101. # load adblock config
  102. #
  103. config_load adblock
  104. config_foreach parse_config source
  105. }
  106. # f_envcheck: check/set environment prerequisites
  107. #
  108. f_envcheck()
  109. {
  110. # check 'enabled' option
  111. #
  112. if [ ${adb_enabled} -ne 1 ]
  113. then
  114. if [ "$(ls -dA "${adb_dnsdir}/${adb_dnsprefix}"* >/dev/null 2>&1)" ]
  115. then
  116. f_rmdns
  117. f_dnsrestart
  118. fi
  119. f_log "info " "status ::: adblock is currently disabled, please set adb_enabled to '1' to use this service"
  120. exit 0
  121. fi
  122. # check fetch utility
  123. #
  124. if [ ! -x "${adb_fetch}" ] && [ "$(readlink -fn "/bin/wget")" = "/bin/uclient-fetch" ]
  125. then
  126. adb_fetch="/bin/uclient-fetch"
  127. adb_fetchparm="-q --timeout=10 --no-check-certificate -O"
  128. fi
  129. if [ -z "${adb_fetch}" ] || [ -z "${adb_fetchparm}" ] || [ ! -x "${adb_fetch}" ] || [ "$(readlink -fn "${adb_fetch}")" = "/bin/busybox" ]
  130. then
  131. f_log "error" "status ::: required download utility with ssl support not found, e.g. install full 'wget' package"
  132. fi
  133. # create dns hideout directory
  134. #
  135. if [ ! -d "${adb_dnshidedir}" ]
  136. then
  137. mkdir -p -m 660 "${adb_dnshidedir}"
  138. chown -R "${adb_dns}":"${adb_dns}" "${adb_dnshidedir}" 2>/dev/null
  139. else
  140. rm -f "${adb_dnshidedir}/${adb_dnsprefix}"*
  141. fi
  142. # create adblock temp file/directory
  143. #
  144. adb_tmpload="$(mktemp -tu)"
  145. adb_tmpfile="$(mktemp -tu)"
  146. adb_tmpdir="$(mktemp -p /tmp -d)"
  147. # prepare whitelist entries
  148. #
  149. if [ -s "${adb_whitelist}" ]
  150. then
  151. awk "${adb_whitelist_rset}" "${adb_whitelist}" > "${adb_tmpdir}/tmp.whitelist"
  152. fi
  153. }
  154. # f_rmtemp: remove temporary files & directories
  155. #
  156. f_rmtemp()
  157. {
  158. rm -f "${adb_tmpload}"
  159. rm -f "${adb_tmpfile}"
  160. rm -rf "${adb_tmpdir}"
  161. }
  162. # f_rmdns: remove dns related files & directories
  163. #
  164. f_rmdns()
  165. {
  166. if [ -n "${adb_dns}" ]
  167. then
  168. rm -f "${adb_dnsdir}/${adb_dnsprefix}"*
  169. rm -f "${adb_backupdir}/${adb_dnsprefix}"*.gz
  170. rm -rf "${adb_dnshidedir}"
  171. fi
  172. ubus call service delete "{\"name\":\"adblock_stats\",\"instances\":\"statistics\"}" 2>/dev/null
  173. }
  174. # f_dnsrestart: restart the dns backend
  175. #
  176. f_dnsrestart()
  177. {
  178. local cnt=0
  179. adb_dnsup="false"
  180. killall -q -TERM "${adb_dns}"
  181. while [ ${cnt} -le 10 ]
  182. do
  183. adb_dnsup="$(ubus -S call service list "{\"name\":\"${adb_dns}\"}" | jsonfilter -l1 -e "@.${adb_dns}.instances.*.running")"
  184. if [ "${adb_dnsup}" = "true" ]
  185. then
  186. break
  187. fi
  188. cnt=$((cnt+1))
  189. sleep 1
  190. done
  191. f_log "debug" "restart ::: dns: ${adb_dns}, dns-up: ${adb_dnsup}, count: ${cnt}"
  192. }
  193. # f_list: backup/restore/remove block lists
  194. #
  195. f_list()
  196. {
  197. local mode="${1}"
  198. if [ ${adb_backup} -eq 0 ]
  199. then
  200. rc=0
  201. fi
  202. case "${mode}" in
  203. backup)
  204. if [ ${adb_backup} -eq 1 ] && [ -d "${adb_backupdir}" ]
  205. then
  206. gzip -cf "${adb_tmpfile}" > "${adb_backupdir}/${adb_dnsprefix}.${src_name}.gz"
  207. rc=${?}
  208. fi
  209. ;;
  210. restore)
  211. if [ ${adb_backup} -eq 1 ] && [ -d "${adb_backupdir}" ]
  212. then
  213. rm -f "${adb_dnsdir}/${adb_dnsprefix}.${src_name}"
  214. if [ -f "${adb_backupdir}/${adb_dnsprefix}.${src_name}.gz" ]
  215. then
  216. gunzip -cf "${adb_backupdir}/${adb_dnsprefix}.${src_name}.gz" > "${adb_tmpfile}"
  217. rc=${?}
  218. fi
  219. fi
  220. ;;
  221. remove)
  222. rm -f "${adb_dnsdir}/${adb_dnsprefix}.${src_name}"
  223. if [ -d "${adb_backupdir}" ]
  224. then
  225. rm -f "${adb_backupdir}/${adb_dnsprefix}.${src_name}.gz"
  226. fi
  227. rc=${?}
  228. ;;
  229. esac
  230. f_log "debug" "list ::: name: ${src_name}, mode: ${mode}, rc: ${rc}"
  231. }
  232. # f_switch: suspend/resume adblock processing
  233. #
  234. f_switch()
  235. {
  236. if [ -d "${adb_dnshidedir}" ]
  237. then
  238. local source target status mode="${1}"
  239. local dns_active="$(find "${adb_dnsdir}" -maxdepth 1 -type f -name "${adb_dnsprefix}*" -print)"
  240. local dns_passive="$(find "${adb_dnshidedir}" -maxdepth 1 -type f -name "${adb_dnsprefix}*" -print)"
  241. if [ -n "${dns_active}" ] && [ "${mode}" = "suspend" ]
  242. then
  243. source="${adb_dnsdir}/${adb_dnsprefix}"
  244. target="${adb_dnshidedir}"
  245. status="suspended"
  246. elif [ -n "${dns_passive}" ] && [ "${mode}" = "resume" ]
  247. then
  248. source="${adb_dnshidedir}/${adb_dnsprefix}"
  249. target="${adb_dnsdir}"
  250. status="resumed"
  251. fi
  252. if [ -n "${status}" ]
  253. then
  254. mv -f "${source}"* "${target}"
  255. f_dnsrestart
  256. f_log "info " "status ::: adblock processing ${status}"
  257. fi
  258. fi
  259. }
  260. # f_query: query block lists for certain (sub-)domains
  261. #
  262. f_query()
  263. {
  264. local search result cnt
  265. local domain="${1}"
  266. local tld="${domain#*.}"
  267. local dns_active="$(find "${adb_dnsdir}" -maxdepth 1 -type f -name "${adb_dnsprefix}*" -print)"
  268. if [ -z "${dns_active}" ]
  269. then
  270. printf "%s\n" "::: no active block lists found, please start adblock first"
  271. elif [ -z "${domain}" ] || [ "${domain}" = "${tld}" ]
  272. then
  273. printf "%s\n" "::: invalid domain input, please submit a specific (sub-)domain, e.g. 'www.abc.xyz'"
  274. else
  275. cd "${adb_dnsdir}"
  276. while [ "${domain}" != "${tld}" ]
  277. do
  278. search="${domain//./\.}"
  279. result="$(grep -Hm1 "[/\"\.]${search}[/\"]" "${adb_dnsprefix}"* | awk -F ':|=|/|\"' '{printf(" %-20s : %s\n",$1,$4)}')"
  280. printf "%s\n" "::: distinct results for domain '${domain}'"
  281. if [ -z "${result}" ]
  282. then
  283. printf "%s\n" " no match"
  284. else
  285. printf "%s\n" "${result}"
  286. fi
  287. domain="${tld}"
  288. tld="${domain#*.}"
  289. done
  290. fi
  291. }
  292. # f_log: write to syslog, exit on error
  293. #
  294. f_log()
  295. {
  296. local class="${1}"
  297. local log_msg="${2}"
  298. if [ -n "${log_msg}" ] && ([ "${class}" != "debug" ] || [ ${adb_debug} -eq 1 ])
  299. then
  300. logger -t "adblock-[${adb_ver}] ${class}" "${log_msg}"
  301. if [ "${class}" = "error" ]
  302. then
  303. logger -t "adblock-[${adb_ver}] ${class}" "Please check the online documentation 'https://github.com/openwrt/packages/blob/master/net/adblock/files/README.md'"
  304. f_rmtemp
  305. f_rmdns
  306. exit 255
  307. fi
  308. fi
  309. }
  310. # f_debug: gather memory & space information
  311. #
  312. f_debug()
  313. {
  314. local mem_total=0 mem_free=0 mem_swap=0 tmp_space=0 backup_space=0
  315. if [ ${adb_debug} -eq 1 ]
  316. then
  317. mem_total="$(awk '$1 ~ /^MemTotal/ {printf $2}' "/proc/meminfo")"
  318. mem_free="$(awk '$1 ~ /^MemFree/ {printf $2}' "/proc/meminfo")"
  319. mem_swap="$(awk '$1 ~ /^SwapTotal/ {printf $2}' "/proc/meminfo")"
  320. f_log "debug" "memory ::: total: ${mem_total}, free: ${mem_free}, swap: ${mem_swap}"
  321. if [ -d "${adb_tmpdir}" ]
  322. then
  323. tmp_space="$(df "${adb_tmpdir}" 2>/dev/null | tail -n1 | awk '{printf $4}')"
  324. fi
  325. if [ -d "${adb_backupdir}" ]
  326. then
  327. backup_space="$(df "${adb_backupdir}" 2>/dev/null | tail -n1 | awk '{printf $4}')"
  328. fi
  329. f_log "debug" "space ::: tmp_dir: ${adb_tmpdir}, tmp_kb: ${tmp_space}, backup: ${adb_backup}, backup_dir: ${adb_backupdir}, backup_kb: ${backup_space}"
  330. fi
  331. }
  332. # main function for block list processing
  333. #
  334. f_main()
  335. {
  336. local enabled url rc cnt sum_cnt=0
  337. local src_name src_rset shalla_file shalla_archive list active_lists
  338. local sysver="$(ubus -S call system board | jsonfilter -e '@.release.description')"
  339. f_log "debug" "main ::: dns-backend: ${adb_dns}, fetch-tool: ${adb_fetch}, parm: ${adb_fetchparm}"
  340. for src_name in ${adb_sources}
  341. do
  342. eval "enabled=\"\${enabled_${src_name}}\""
  343. eval "url=\"\${adb_src_${src_name}}\""
  344. eval "src_rset=\"\${adb_src_rset_${src_name}}\""
  345. adb_dnsfile="${adb_tmpdir}/${adb_dnsprefix}.${src_name}"
  346. > "${adb_tmpload}"
  347. > "${adb_tmpfile}"
  348. # basic pre-checks
  349. #
  350. if [ "${enabled}" != "1" ] || [ -z "${url}" ] || [ -z "${src_rset}" ]
  351. then
  352. f_list remove
  353. continue
  354. fi
  355. # download block list
  356. #
  357. f_log "debug" "loop_0 ::: name: ${src_name}, enabled: ${enabled}, dnsfile: ${adb_dnsfile}"
  358. if [ "${src_name}" = "blacklist" ]
  359. then
  360. cat "${url}" 2>/dev/null > "${adb_tmpload}"
  361. rc=${?}
  362. elif [ "${src_name}" = "shalla" ]
  363. then
  364. shalla_archive="${adb_tmpdir}/shallalist.tar.gz"
  365. shalla_file="${adb_tmpdir}/shallalist.txt"
  366. "${adb_fetch}" ${adb_fetchparm} "${shalla_archive}" "${url}"
  367. rc=${?}
  368. if [ ${rc} -eq 0 ]
  369. then
  370. > "${shalla_file}"
  371. for category in ${adb_src_cat_shalla}
  372. do
  373. tar -xOzf "${shalla_archive}" BL/${category}/domains >> "${shalla_file}"
  374. rc=${?}
  375. if [ ${rc} -ne 0 ]
  376. then
  377. break
  378. fi
  379. done
  380. cat "${shalla_file}" 2>/dev/null > "${adb_tmpload}"
  381. rm -f "${shalla_file}"
  382. fi
  383. rm -f "${shalla_archive}"
  384. rm -rf "${adb_tmpdir}/BL"
  385. else
  386. "${adb_fetch}" ${adb_fetchparm} "${adb_tmpload}" "${url}"
  387. rc=${?}
  388. fi
  389. f_log "debug" "loop_1 ::: name: ${src_name}, rc: ${rc}"
  390. # check download result and prepare domain output (incl. list backup/restore)
  391. #
  392. if [ ${rc} -eq 0 ] && [ -s "${adb_tmpload}" ]
  393. then
  394. awk "${src_rset}" "${adb_tmpload}" > "${adb_tmpfile}"
  395. if [ -s "${adb_tmpfile}" ]
  396. then
  397. f_list backup
  398. else
  399. f_list restore
  400. fi
  401. else
  402. f_list restore
  403. fi
  404. f_log "debug" "loop_2 ::: name: ${src_name}, rc: ${rc}"
  405. # remove whitelist domains, final list preparation
  406. #
  407. if [ ${rc} -eq 0 ] && [ -s "${adb_tmpfile}" ]
  408. then
  409. if [ -s "${adb_tmpdir}/tmp.whitelist" ]
  410. then
  411. grep -vf "${adb_tmpdir}/tmp.whitelist" "${adb_tmpfile}" | sort -u | eval "${adb_dnsformat}" > "${adb_dnsfile}"
  412. else
  413. sort -u "${adb_tmpfile}" | eval "${adb_dnsformat}" > "${adb_dnsfile}"
  414. fi
  415. rc=${?}
  416. if [ ${rc} -ne 0 ]
  417. then
  418. f_list remove
  419. fi
  420. else
  421. f_list remove
  422. fi
  423. f_log "debug" "loop_3 ::: name: ${src_name}, rc: ${rc}"
  424. done
  425. # sort/unique overall
  426. #
  427. for src_name in $(ls -dASr "${adb_tmpdir}/${adb_dnsprefix}"* 2>/dev/null)
  428. do
  429. if [ -s "${adb_tmpdir}/blocklist.overall" ]
  430. then
  431. sort "${adb_tmpdir}/blocklist.overall" "${adb_tmpdir}/blocklist.overall" "${src_name}" | uniq -u > "${adb_tmpdir}/tmp.blocklist"
  432. cat "${adb_tmpdir}/tmp.blocklist" > "${src_name}"
  433. fi
  434. cat "${src_name}" >> "${adb_tmpdir}/blocklist.overall"
  435. cnt="$(wc -l < "${src_name}")"
  436. sum_cnt=$((sum_cnt + cnt))
  437. list="${src_name/*./}"
  438. if [ -z "${active_lists}" ]
  439. then
  440. active_lists="\"${list}\":\"${cnt}\""
  441. else
  442. active_lists="${active_lists},\"${list}\":\"${cnt}\""
  443. fi
  444. done
  445. # restart the dns backend and write statistics to procd service instance
  446. #
  447. mv -f "${adb_tmpdir}/${adb_dnsprefix}"* "${adb_dnsdir}" 2>/dev/null
  448. chown "${adb_dns}":"${adb_dns}" "${adb_dnsdir}/${adb_dnsprefix}"* 2>/dev/null
  449. f_dnsrestart
  450. f_debug
  451. if [ "${adb_dnsup}" = "true" ]
  452. then
  453. f_log "info " "status ::: block lists with overall ${sum_cnt} domains loaded (${sysver})"
  454. ubus call service set "{\"name\":\"adblock_stats\",
  455. \"instances\":{\"statistics\":{\"command\":[\"\"],
  456. \"data\":{\"active_lists\":[{${active_lists}}],
  457. \"adblock_version\":\"${adb_ver}\",
  458. \"blocked_domains\":\"${sum_cnt}\",
  459. \"dns_backend\":\"${adb_dns}\",
  460. \"last_rundate\":\"$(/bin/date "+%d.%m.%Y %H:%M:%S")\",
  461. \"system\":\"${sysver}\"}}}}"
  462. f_rmtemp
  463. return 0
  464. fi
  465. f_log "error" "status ::: dns backend restart with active block lists failed (${sysver})"
  466. }
  467. # handle different adblock actions
  468. #
  469. if [ "${adb_procd}" = "true" ]
  470. then
  471. f_envload
  472. case "${1}" in
  473. stop)
  474. f_rmtemp
  475. f_rmdns
  476. f_dnsrestart
  477. ;;
  478. restart)
  479. f_rmtemp
  480. f_rmdns
  481. f_envcheck
  482. f_main
  483. ;;
  484. suspend)
  485. f_switch suspend
  486. ;;
  487. resume)
  488. f_switch resume
  489. ;;
  490. query)
  491. f_query "${2}"
  492. ;;
  493. *)
  494. f_envcheck
  495. f_main
  496. ;;
  497. esac
  498. fi
  499. exit 0