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.

505 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.3.2"
  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" "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" "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 " "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" "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. if [ -d "${adb_tmpdir}" ]
  159. then
  160. rm -f "${adb_tmpload}"
  161. rm -f "${adb_tmpfile}"
  162. rm -rf "${adb_tmpdir}"
  163. fi
  164. }
  165. # f_rmdns: remove dns related files & directories
  166. #
  167. f_rmdns()
  168. {
  169. if [ -n "${adb_dns}" ]
  170. then
  171. rm -f "${adb_dnsdir}/${adb_dnsprefix}"*
  172. rm -f "${adb_backupdir}/${adb_dnsprefix}"*.gz
  173. rm -rf "${adb_dnshidedir}"
  174. fi
  175. ubus call service delete "{\"name\":\"adblock_stats\",\"instances\":\"statistics\"}" 2>/dev/null
  176. }
  177. # f_dnsrestart: restart the dns backend
  178. #
  179. f_dnsrestart()
  180. {
  181. local cnt=0
  182. "/etc/init.d/${adb_dns}" restart >/dev/null 2>&1
  183. while [ ${cnt} -le 10 ]
  184. do
  185. adb_dnsup="$(ubus -S call service list "{\"name\":\"${adb_dns}\"}" | jsonfilter -l1 -e "@.${adb_dns}.instances.*.running")"
  186. if [ "${adb_dnsup}" = "true" ]
  187. then
  188. return 0
  189. fi
  190. cnt=$((cnt+1))
  191. sleep 1
  192. done
  193. }
  194. # f_list: backup/restore/remove block lists
  195. #
  196. f_list()
  197. {
  198. local mode="${1}" in_rc="${adb_rc}" cnt=0
  199. case "${mode}" in
  200. backup)
  201. cnt="$(wc -l < "${adb_tmpfile}")"
  202. if [ ${adb_backup} -eq 1 ] && [ -d "${adb_backupdir}" ]
  203. then
  204. gzip -cf "${adb_tmpfile}" > "${adb_backupdir}/${adb_dnsprefix}.${src_name}.gz"
  205. adb_rc=${?}
  206. fi
  207. ;;
  208. restore)
  209. if [ ${adb_backup} -eq 1 ] && [ -d "${adb_backupdir}" ]
  210. then
  211. rm -f "${adb_dnsdir}/${adb_dnsprefix}.${src_name}"
  212. if [ -f "${adb_backupdir}/${adb_dnsprefix}.${src_name}.gz" ]
  213. then
  214. gunzip -cf "${adb_backupdir}/${adb_dnsprefix}.${src_name}.gz" > "${adb_tmpfile}"
  215. adb_rc=${?}
  216. fi
  217. fi
  218. ;;
  219. remove)
  220. rm -f "${adb_dnsdir}/${adb_dnsprefix}.${src_name}"
  221. if [ -d "${adb_backupdir}" ]
  222. then
  223. rm -f "${adb_backupdir}/${adb_dnsprefix}.${src_name}.gz"
  224. fi
  225. adb_rc=${?}
  226. ;;
  227. esac
  228. f_log "debug" "name: ${src_name}, mode: ${mode}, count: ${cnt}, in_rc: ${in_rc}, out_rc: ${adb_rc}"
  229. }
  230. # f_switch: suspend/resume adblock processing
  231. #
  232. f_switch()
  233. {
  234. if [ -d "${adb_dnshidedir}" ]
  235. then
  236. local source target status mode="${1}"
  237. local dns_active="$(find "${adb_dnsdir}" -maxdepth 1 -type f -name "${adb_dnsprefix}*" -print)"
  238. local dns_passive="$(find "${adb_dnshidedir}" -maxdepth 1 -type f -name "${adb_dnsprefix}*" -print)"
  239. if [ -n "${dns_active}" ] && [ "${mode}" = "suspend" ]
  240. then
  241. source="${adb_dnsdir}/${adb_dnsprefix}"
  242. target="${adb_dnshidedir}"
  243. status="suspended"
  244. elif [ -n "${dns_passive}" ] && [ "${mode}" = "resume" ]
  245. then
  246. source="${adb_dnshidedir}/${adb_dnsprefix}"
  247. target="${adb_dnsdir}"
  248. status="resumed"
  249. fi
  250. if [ -n "${status}" ]
  251. then
  252. mv -f "${source}"* "${target}"
  253. f_dnsrestart
  254. f_log "info " "adblock processing ${status}"
  255. fi
  256. fi
  257. }
  258. # f_query: query block lists for certain (sub-)domains
  259. #
  260. f_query()
  261. {
  262. local search result cnt
  263. local domain="${1}"
  264. local tld="${domain#*.}"
  265. local dns_active="$(find "${adb_dnsdir}" -maxdepth 1 -type f -name "${adb_dnsprefix}*" -print)"
  266. if [ -z "${dns_active}" ]
  267. then
  268. printf "%s\n" "::: no active block lists found, please start adblock first"
  269. elif [ -z "${domain}" ] || [ "${domain}" = "${tld}" ]
  270. then
  271. printf "%s\n" "::: invalid domain input, please submit a specific (sub-)domain, e.g. 'www.abc.xyz'"
  272. else
  273. cd "${adb_dnsdir}"
  274. while [ "${domain}" != "${tld}" ]
  275. do
  276. search="${domain//./\.}"
  277. result="$(grep -Hm1 "[/\"\.]${search}[/\"]" "${adb_dnsprefix}"* | awk -F ':|=|/|\"' '{printf(" %-20s : %s\n",$1,$4)}')"
  278. printf "%s\n" "::: distinct results for domain '${domain}'"
  279. if [ -z "${result}" ]
  280. then
  281. printf "%s\n" " no match"
  282. else
  283. printf "%s\n" "${result}"
  284. fi
  285. domain="${tld}"
  286. tld="${domain#*.}"
  287. done
  288. fi
  289. }
  290. # f_log: write to syslog, exit on error
  291. #
  292. f_log()
  293. {
  294. local class="${1}" log_msg="${2}"
  295. if [ -n "${log_msg}" ] && ([ "${class}" != "debug" ] || [ ${adb_debug} -eq 1 ])
  296. then
  297. logger -t "adblock-[${adb_ver}] ${class}" "${log_msg}"
  298. if [ "${class}" = "error" ]
  299. then
  300. logger -t "adblock-[${adb_ver}] ${class}" "Please check the online documentation 'https://github.com/openwrt/packages/blob/master/net/adblock/files/README.md'"
  301. f_rmtemp
  302. f_rmdns
  303. exit 255
  304. fi
  305. fi
  306. }
  307. # main function for block list processing
  308. #
  309. f_main()
  310. {
  311. local enabled url cnt sum_cnt=0 mem_total=0
  312. local src_name src_rset shalla_archive list active_lists
  313. local sysver="$(ubus -S call system board | jsonfilter -e '@.release.description')"
  314. mem_total="$(awk '$1 ~ /^MemTotal/ {printf $2}' "/proc/meminfo" 2>/dev/null)"
  315. f_log "info " "start adblock processing ..."
  316. for src_name in ${adb_sources}
  317. do
  318. eval "enabled=\"\${enabled_${src_name}}\""
  319. eval "url=\"\${adb_src_${src_name}}\""
  320. eval "src_rset=\"\${adb_src_rset_${src_name}}\""
  321. adb_dnsfile="${adb_tmpdir}/${adb_dnsprefix}.${src_name}"
  322. > "${adb_tmpload}"
  323. > "${adb_tmpfile}"
  324. adb_rc=0
  325. # basic pre-checks
  326. #
  327. if [ "${enabled}" != "1" ] || [ -z "${url}" ] || [ -z "${src_rset}" ]
  328. then
  329. f_list remove
  330. continue
  331. fi
  332. # download block list
  333. #
  334. f_log "debug" "name: ${src_name}, enabled: ${enabled}, backup: ${adb_backup}, dns: ${adb_dns}, fetch: ${adb_fetch}, memory: ${mem_total}"
  335. if [ "${src_name}" = "blacklist" ]
  336. then
  337. cat "${url}" 2>/dev/null > "${adb_tmpload}"
  338. adb_rc=${?}
  339. elif [ "${src_name}" = "shalla" ]
  340. then
  341. shalla_archive="${adb_tmpdir}/shallalist.tar.gz"
  342. "${adb_fetch}" ${adb_fetchparm} "${shalla_archive}" "${url}" 2>/dev/null
  343. adb_rc=${?}
  344. if [ ${adb_rc} -eq 0 ]
  345. then
  346. for category in ${adb_src_cat_shalla}
  347. do
  348. tar -xOzf "${shalla_archive}" BL/${category}/domains >> "${adb_tmpload}"
  349. adb_rc=${?}
  350. if [ ${adb_rc} -ne 0 ]
  351. then
  352. break
  353. fi
  354. done
  355. fi
  356. rm -f "${shalla_archive}"
  357. rm -rf "${adb_tmpdir}/BL"
  358. else
  359. "${adb_fetch}" ${adb_fetchparm} "${adb_tmpload}" "${url}" 2>/dev/null
  360. adb_rc=${?}
  361. fi
  362. # check download result and prepare domain output (incl. list backup/restore)
  363. #
  364. if [ ${adb_rc} -eq 0 ] && [ -s "${adb_tmpload}" ]
  365. then
  366. awk "${src_rset}" "${adb_tmpload}" > "${adb_tmpfile}"
  367. if [ -s "${adb_tmpfile}" ]
  368. then
  369. f_list backup
  370. else
  371. f_list restore
  372. fi
  373. else
  374. f_list restore
  375. fi
  376. # remove whitelist domains, final list preparation
  377. #
  378. if [ ${adb_rc} -eq 0 ] && [ -s "${adb_tmpfile}" ]
  379. then
  380. if [ -s "${adb_tmpdir}/tmp.whitelist" ]
  381. then
  382. grep -vf "${adb_tmpdir}/tmp.whitelist" "${adb_tmpfile}" | sort -u | eval "${adb_dnsformat}" > "${adb_dnsfile}"
  383. else
  384. sort -u "${adb_tmpfile}" | eval "${adb_dnsformat}" > "${adb_dnsfile}"
  385. fi
  386. adb_rc=${?}
  387. if [ ${adb_rc} -ne 0 ]
  388. then
  389. f_list remove
  390. fi
  391. else
  392. f_list remove
  393. fi
  394. done
  395. # overall sort
  396. #
  397. for src_name in $(ls -dASr "${adb_tmpdir}/${adb_dnsprefix}"* 2>/dev/null)
  398. do
  399. if [ ${mem_total} -ge 64000 ]
  400. then
  401. if [ -s "${adb_tmpdir}/blocklist.overall" ]
  402. then
  403. sort "${adb_tmpdir}/blocklist.overall" "${adb_tmpdir}/blocklist.overall" "${src_name}" | uniq -u > "${adb_tmpdir}/tmp.blocklist"
  404. mv -f "${adb_tmpdir}/tmp.blocklist" "${src_name}"
  405. fi
  406. cat "${src_name}" >> "${adb_tmpdir}/blocklist.overall"
  407. fi
  408. cnt="$(wc -l < "${src_name}")"
  409. sum_cnt=$((sum_cnt + cnt))
  410. list="${src_name/*./}"
  411. if [ -z "${active_lists}" ]
  412. then
  413. active_lists="\"${list}\":\"${cnt}\""
  414. else
  415. active_lists="${active_lists},\"${list}\":\"${cnt}\""
  416. fi
  417. done
  418. # restart the dns backend and write statistics to procd service instance
  419. #
  420. mv -f "${adb_tmpdir}/${adb_dnsprefix}"* "${adb_dnsdir}" 2>/dev/null
  421. chown "${adb_dns}":"${adb_dns}" "${adb_dnsdir}/${adb_dnsprefix}"* 2>/dev/null
  422. f_rmtemp
  423. f_dnsrestart
  424. if [ "${adb_dnsup}" = "true" ]
  425. then
  426. f_log "info " "block lists with overall ${sum_cnt} domains loaded successfully (${sysver})"
  427. ubus call service set "{\"name\":\"adblock_stats\",
  428. \"instances\":{\"statistics\":{\"command\":[\"\"],
  429. \"data\":{\"active_lists\":[{${active_lists}}],
  430. \"adblock_version\":\"${adb_ver}\",
  431. \"blocked_domains\":\"${sum_cnt}\",
  432. \"dns_backend\":\"${adb_dns}\",
  433. \"last_rundate\":\"$(/bin/date "+%d.%m.%Y %H:%M:%S")\",
  434. \"system\":\"${sysver}\"}}}}"
  435. return 0
  436. fi
  437. f_log "error" "dns backend restart with active block lists failed (${sysver})"
  438. }
  439. # handle different adblock actions
  440. #
  441. if [ "${adb_procd}" = "true" ]
  442. then
  443. f_envload
  444. case "${1}" in
  445. stop)
  446. f_rmtemp
  447. f_rmdns
  448. f_dnsrestart
  449. ;;
  450. restart)
  451. f_rmtemp
  452. f_rmdns
  453. f_envcheck
  454. f_main
  455. ;;
  456. suspend)
  457. f_switch suspend
  458. ;;
  459. resume)
  460. f_switch resume
  461. ;;
  462. query)
  463. f_query "${2}"
  464. ;;
  465. *)
  466. f_envcheck
  467. f_main
  468. ;;
  469. esac
  470. fi
  471. exit 0