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.

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