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.

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