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.

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