adblock.sh 18 KB

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