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.

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