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.

487 lines
14 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.1"
  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 server 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}" ] || [ ! -f "${adb_fetch}" ]
  104. then
  105. f_log "error" "status ::: no download utility with ssl support found/configured"
  106. fi
  107. # create dns hideout directory
  108. #
  109. if [ ! -d "${adb_dnshidedir}" ]
  110. then
  111. mkdir -p -m 660 "${adb_dnshidedir}"
  112. chown -R "${adb_dns}":"${adb_dns}" "${adb_dnshidedir}"
  113. else
  114. rm -f "${adb_dnshidedir}/${adb_dnsprefix}"*
  115. fi
  116. # create adblock temp file/directory
  117. #
  118. adb_tmpload="$(mktemp -tu)"
  119. adb_tmpfile="$(mktemp -tu)"
  120. adb_tmpdir="$(mktemp -p /tmp -d)"
  121. # prepare whitelist entries
  122. #
  123. if [ -s "${adb_whitelist}" ]
  124. then
  125. awk "${adb_whitelist_rset}" "${adb_whitelist}" > "${adb_tmpdir}/tmp.whitelist"
  126. fi
  127. }
  128. # f_rmtemp: remove temporary files & directories
  129. #
  130. f_rmtemp()
  131. {
  132. rm -f "${adb_tmpload}"
  133. rm -f "${adb_tmpfile}"
  134. rm -rf "${adb_tmpdir}"
  135. }
  136. # f_rmdns: remove dns related files & directories
  137. #
  138. f_rmdns()
  139. {
  140. rm -f "${adb_dnsdir}/${adb_dnsprefix}"*
  141. rm -f "${adb_dir_backup}/${adb_dnsprefix}"*.gz
  142. rm -rf "${adb_dnshidedir}"
  143. ubus call service delete "{\"name\":\"adblock_stats\",\"instances\":\"stats\"}" 2>/dev/null
  144. }
  145. # f_dnsrestart: restart the dns server
  146. #
  147. f_dnsrestart()
  148. {
  149. local cnt=0
  150. dns_running="false"
  151. sync
  152. killall -q -TERM "${adb_dns}"
  153. while [ ${cnt} -le 10 ]
  154. do
  155. dns_running="$(ubus -S call service list "{\"name\":\"${adb_dns}\"}" | jsonfilter -l 1 -e "@.${adb_dns}.instances.*.running")"
  156. if [ "${dns_running}" = "true" ]
  157. then
  158. return 0
  159. fi
  160. cnt=$((cnt+1))
  161. sleep 1
  162. done
  163. /etc/init.d/"${adb_dns}" restart
  164. sleep 1
  165. }
  166. # f_list: backup/restore/remove block lists
  167. #
  168. f_list()
  169. {
  170. local mode="${1}"
  171. if [ "${enabled_backup}" = "1" ] && [ -d "${adb_dir_backup}" ]
  172. then
  173. case "${mode}" in
  174. backup)
  175. gzip -cf "${adb_tmpfile}" > "${adb_dir_backup}/${adb_dnsprefix}.${src_name}.gz"
  176. ;;
  177. restore)
  178. rm -f "${adb_dnsdir}/${adb_dnsprefix}.${src_name}"
  179. if [ -f "${adb_dir_backup}/${adb_dnsprefix}.${src_name}.gz" ]
  180. then
  181. gunzip -cf "${adb_dir_backup}/${adb_dnsprefix}.${src_name}.gz" > "${adb_tmpfile}"
  182. fi
  183. ;;
  184. remove)
  185. rm -f "${adb_dnsdir}/${adb_dnsprefix}.${src_name}"
  186. if [ -f "${adb_dir_backup}/${adb_dnsprefix}.${src_name}.gz" ]
  187. then
  188. rm -f "${adb_dir_backup}/${adb_dnsprefix}.${src_name}.gz"
  189. fi
  190. ;;
  191. esac
  192. fi
  193. }
  194. # f_switch: suspend/resume adblock processing
  195. #
  196. f_switch()
  197. {
  198. if [ -d "${adb_dnshidedir}" ]
  199. then
  200. local source target status mode="${1}"
  201. local dns_active="$(find "${adb_dnsdir}" -maxdepth 1 -type f -name "${adb_dnsprefix}*" -print)"
  202. local dns_passive="$(find "${adb_dnshidedir}" -maxdepth 1 -type f -name "${adb_dnsprefix}*" -print)"
  203. if [ -n "${dns_active}" ] && [ "${mode}" = "suspend" ]
  204. then
  205. source="${adb_dnsdir}/${adb_dnsprefix}"
  206. target="${adb_dnshidedir}"
  207. status="suspended"
  208. elif [ -n "${dns_passive}" ] && [ "${mode}" = "resume" ]
  209. then
  210. source="${adb_dnshidedir}/${adb_dnsprefix}"
  211. target="${adb_dnsdir}"
  212. status="resumed"
  213. fi
  214. if [ -n "${status}" ]
  215. then
  216. mv -f "${source}"* "${target}"
  217. f_dnsrestart
  218. f_log "info " "status ::: adblock processing ${status}"
  219. fi
  220. fi
  221. }
  222. # f_query: query block lists for certain (sub-)domains
  223. #
  224. f_query()
  225. {
  226. local search result cnt
  227. local domain="${1}"
  228. local tld="${domain#*.}"
  229. local dns_active="$(find "${adb_dnsdir}" -maxdepth 1 -type f -name "${adb_dnsprefix}*" -print)"
  230. if [ -z "${dns_active}" ]
  231. then
  232. printf "%s\n" "::: no active block lists found, please start adblock first"
  233. elif [ -z "${domain}" ] || [ "${domain}" = "${tld}" ]
  234. then
  235. printf "%s\n" "::: invalid domain input, please submit a specific (sub-)domain, i.e. 'www.abc.xyz'"
  236. else
  237. cd "${adb_dnsdir}"
  238. while [ "${domain}" != "${tld}" ]
  239. do
  240. search="${domain//./\.}"
  241. result="$(grep -Hm1 "[/\"\.]${search}[/\"]" "${adb_dnsprefix}"* | awk -F ':|=|/|\"' '{printf(" %-20s : %s\n",$1,$4)}')"
  242. printf "%s\n" "::: distinct results for domain '${domain}'"
  243. if [ -z "${result}" ]
  244. then
  245. printf "%s\n" " no match"
  246. else
  247. printf "%s\n" "${result}"
  248. fi
  249. domain="${tld}"
  250. tld="${domain#*.}"
  251. done
  252. fi
  253. }
  254. # f_log: write to syslog, exit on error
  255. #
  256. f_log()
  257. {
  258. local class="${1}"
  259. local log_msg="${2}"
  260. if [ -n "${log_msg}" ] && ([ "${class}" != "debug" ] || [ ${adb_debug} -eq 1 ])
  261. then
  262. logger -t "adblock-[${adb_ver}] ${class}" "${log_msg}"
  263. if [ "${class}" = "error" ]
  264. then
  265. f_rmtemp
  266. f_rmdns
  267. f_dnsrestart
  268. exit 255
  269. fi
  270. fi
  271. }
  272. # f_debug: gather memory & space information
  273. f_debug()
  274. {
  275. local mem_total=0 mem_free=0 mem_swap=0 tmp_space=0 backup_space=0
  276. if [ ${adb_debug} -eq 1 ]
  277. then
  278. mem_total="$(awk '$1 ~ /^MemTotal/ {printf $2}' "/proc/meminfo")"
  279. mem_free="$(awk '$1 ~ /^MemFree/ {printf $2}' "/proc/meminfo")"
  280. mem_swap="$(awk '$1 ~ /^SwapTotal/ {printf $2}' "/proc/meminfo")"
  281. f_log "debug" "memory ::: total: ${mem_total}, free: ${mem_free}, swap: ${mem_swap}"
  282. if [ -d "${adb_tmpdir}" ]
  283. then
  284. tmp_space="$(df "${adb_tmpdir}" 2>/dev/null | tail -n1 | awk '{printf $4}')"
  285. fi
  286. if [ -d "${adb_dir_backup}" ]
  287. then
  288. backup_space="$(df "${adb_dir_backup}" 2>/dev/null | tail -n1 | awk '{printf $4}')"
  289. fi
  290. f_log "debug" "space ::: tmp_dir: ${adb_tmpdir}, tmp_kb: ${tmp_space}, backup: ${enabled_backup}, backup_dir: ${adb_dir_backup}, backup_kb: ${backup_space}"
  291. fi
  292. }
  293. # main function for block list processing
  294. #
  295. f_main()
  296. {
  297. local enabled url rc cnt sum_cnt=0
  298. local src_name src_rset shalla_file shalla_archive list active_lists
  299. local sysver="$(ubus -S call system board | jsonfilter -e '@.release.description')"
  300. f_debug
  301. f_log "debug" "main ::: dns-backend: ${adb_dns}, fetch-tool: ${adb_fetch}, parm: ${adb_fetchparm}"
  302. for src_name in ${adb_sources}
  303. do
  304. eval "enabled=\"\${enabled_${src_name}}\""
  305. eval "url=\"\${adb_src_${src_name}}\""
  306. eval "src_rset=\"\${adb_src_rset_${src_name}}\""
  307. adb_dnsfile="${adb_dnsdir}/${adb_dnsprefix}.${src_name}"
  308. > "${adb_tmpload}"
  309. > "${adb_tmpfile}"
  310. # basic pre-checks
  311. #
  312. if [ "${enabled}" = "0" ] || [ -z "${url}" ] || [ -z "${src_rset}" ]
  313. then
  314. f_list remove
  315. continue
  316. fi
  317. # download block list
  318. #
  319. f_log "debug" "loop ::: name: ${src_name}, enabled: ${enabled}, dnsfile: ${adb_dnsfile}"
  320. if [ "${src_name}" = "blacklist" ]
  321. then
  322. cat "${url}" > "${adb_tmpload}"
  323. rc=${?}
  324. elif [ "${src_name}" = "shalla" ]
  325. then
  326. shalla_archive="${adb_tmpdir}/shallalist.tar.gz"
  327. shalla_file="${adb_tmpdir}/shallalist.txt"
  328. "${adb_fetch}" ${adb_fetchparm} "${shalla_archive}" "${url}"
  329. rc=${?}
  330. if [ ${rc} -eq 0 ]
  331. then
  332. > "${shalla_file}"
  333. for category in ${adb_src_cat_shalla}
  334. do
  335. tar -xOzf "${shalla_archive}" BL/${category}/domains >> "${shalla_file}"
  336. rc=${?}
  337. if [ ${rc} -ne 0 ]
  338. then
  339. break
  340. fi
  341. done
  342. cat "${shalla_file}" > "${adb_tmpload}"
  343. rm -f "${shalla_file}"
  344. fi
  345. rm -f "${shalla_archive}"
  346. rm -rf "${adb_tmpdir}/BL"
  347. else
  348. "${adb_fetch}" ${adb_fetchparm} "${adb_tmpload}" "${url}"
  349. rc=${?}
  350. fi
  351. # check download result and prepare domain output (incl. list backup/restore)
  352. #
  353. f_log "debug" "loop ::: name: ${src_name}, load-rc: ${rc}"
  354. if [ ${rc} -eq 0 ] && [ -s "${adb_tmpload}" ]
  355. then
  356. awk "${src_rset}" "${adb_tmpload}" > "${adb_tmpfile}"
  357. if [ -s "${adb_tmpfile}" ]
  358. then
  359. f_list backup
  360. else
  361. f_list restore
  362. fi
  363. else
  364. f_list restore
  365. fi
  366. # remove whitelist domains, sort and make them unique, final list preparation
  367. #
  368. if [ -s "${adb_tmpfile}" ]
  369. then
  370. if [ -s "${adb_tmpdir}/tmp.whitelist" ]
  371. then
  372. grep -vf "${adb_tmpdir}/tmp.whitelist" "${adb_tmpfile}" | sort -u | eval "${adb_dnsformat}" > "${adb_dnsfile}"
  373. else
  374. sort -u "${adb_tmpfile}" | eval "${adb_dnsformat}" > "${adb_dnsfile}"
  375. fi
  376. rc=${?}
  377. if [ ${rc} -ne 0 ]
  378. then
  379. f_list remove
  380. fi
  381. fi
  382. f_log "debug" "loop ::: name: ${src_name}, list-rc: ${rc}"
  383. done
  384. # sort block lists
  385. #
  386. for src_name in $(ls -dASr "${adb_dnsdir}/${adb_dnsprefix}"* 2>/dev/null)
  387. do
  388. if [ -s "${adb_tmpdir}/blocklist.overall" ]
  389. then
  390. sort "${adb_tmpdir}/blocklist.overall" "${adb_tmpdir}/blocklist.overall" "${src_name}" | uniq -u > "${adb_tmpdir}/tmp.blocklist"
  391. cat "${adb_tmpdir}/tmp.blocklist" > "${src_name}"
  392. fi
  393. cat "${src_name}" >> "${adb_tmpdir}/blocklist.overall"
  394. cnt="$(wc -l < "${src_name}")"
  395. sum_cnt=$((sum_cnt + cnt))
  396. list="${src_name/*./}"
  397. if [ -z "${active_lists}" ]
  398. then
  399. active_lists="\"${list}\":\"${cnt}\""
  400. else
  401. active_lists="${active_lists},\"${list}\":\"${cnt}\""
  402. fi
  403. done
  404. # restart dns server and write statistics
  405. #
  406. chown "${adb_dns}":"${adb_dns}" "${adb_dnsdir}/${adb_dnsprefix}"* 2>/dev/null
  407. f_dnsrestart
  408. if [ "${dns_running}" = "true" ]
  409. then
  410. f_debug
  411. f_rmtemp
  412. f_log "info " "status ::: block lists with overall ${sum_cnt} domains loaded (${sysver})"
  413. ubus call service add "{\"name\":\"adblock_stats\",
  414. \"instances\":{\"stats\":{\"command\":[\"\"],
  415. \"data\":{\"active_lists\":[{${active_lists}}],
  416. \"adblock_version\":\"${adb_ver}\",
  417. \"blocked_domains\":\"${sum_cnt}\",
  418. \"dns_backend\":\"${adb_dns}\",
  419. \"last_rundate\":\"$(/bin/date "+%d.%m.%Y %H:%M:%S")\",
  420. \"system\":\"${sysver}\"}}}}"
  421. return 0
  422. fi
  423. f_debug
  424. f_log "error" "status ::: dns server restart with active block lists failed (${sysver})"
  425. }
  426. # handle different adblock actions
  427. #
  428. if [ "${adb_procd}" = "true" ]
  429. then
  430. f_envload
  431. case "${1}" in
  432. stop)
  433. f_rmtemp
  434. f_rmdns
  435. f_dnsrestart
  436. ;;
  437. suspend)
  438. f_switch suspend
  439. ;;
  440. resume)
  441. f_switch resume
  442. ;;
  443. query)
  444. f_query "${2}"
  445. ;;
  446. *)
  447. f_envcheck
  448. f_main
  449. ;;
  450. esac
  451. fi
  452. exit 0