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.

515 lines
16 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.5.1"
  12. adb_sysver="$(ubus -S call system board | jsonfilter -e '@.release.description')"
  13. adb_enabled=1
  14. adb_debug=0
  15. adb_backup=0
  16. adb_backupdir="/mnt"
  17. adb_whitelist="/etc/adblock/adblock.whitelist"
  18. adb_whitelist_rset="\$1 ~/^([A-Za-z0-9_-]+\.){1,}[A-Za-z]+/{print tolower(\"^\"\$1\"\\\|[.]\"\$1)}"
  19. adb_fetch="/usr/bin/wget"
  20. adb_fetchparm="--no-config --quiet --no-cache --no-cookies --max-redirect=0 --timeout=10 --no-check-certificate -O"
  21. adb_dnslist="dnsmasq unbound"
  22. adb_dnsprefix="adb_list"
  23. # f_envload: load adblock environment
  24. #
  25. f_envload()
  26. {
  27. local dns_up cnt=0
  28. # source in system library
  29. #
  30. if [ -r "/lib/functions.sh" ]
  31. then
  32. . "/lib/functions.sh"
  33. else
  34. f_log "error" "system library not found"
  35. fi
  36. # set dns backend environment
  37. #
  38. while [ ${cnt} -le 20 ]
  39. do
  40. for dns in ${adb_dnslist}
  41. do
  42. dns_up="$(ubus -S call service list "{\"name\":\"${dns}\"}" | jsonfilter -l1 -e "@.${dns}.instances.*.running")"
  43. if [ "${dns_up}" = "true" ]
  44. then
  45. case "${dns}" in
  46. dnsmasq)
  47. adb_dns="dnsmasq"
  48. adb_dnsdir="/tmp/dnsmasq.d"
  49. adb_dnshidedir="${adb_dnsdir}/.adb_hidden"
  50. adb_dnsformat="awk '{print \"local=/\"\$0\"/\"}'"
  51. break 2
  52. ;;
  53. unbound)
  54. adb_dns="unbound"
  55. adb_dnsdir="/var/lib/unbound"
  56. adb_dnshidedir="${adb_dnsdir}/.adb_hidden"
  57. adb_dnsformat="awk '{print \"local-zone: \042\"\$0\"\042 static\"}'"
  58. break 2
  59. ;;
  60. esac
  61. fi
  62. done
  63. sleep 1
  64. cnt=$((cnt+1))
  65. done
  66. if [ -z "${adb_dns}" ]
  67. then
  68. f_log "error" "no active/supported DNS backend found"
  69. fi
  70. # parse global section by callback
  71. #
  72. config_cb()
  73. {
  74. local type="${1}"
  75. if [ "${type}" = "adblock" ]
  76. then
  77. option_cb()
  78. {
  79. local option="${1}"
  80. local value="${2}"
  81. eval "${option}=\"${value}\""
  82. }
  83. else
  84. reset_cb
  85. fi
  86. }
  87. # parse 'source' section
  88. #
  89. parse_config()
  90. {
  91. local value opt section="${1}" options="enabled adb_src adb_src_rset adb_src_cat"
  92. eval "adb_sources=\"${adb_sources} ${section}\""
  93. for opt in ${options}
  94. do
  95. config_get value "${section}" "${opt}"
  96. if [ -n "${value}" ]
  97. then
  98. eval "${opt}_${section}=\"${value}\""
  99. fi
  100. done
  101. }
  102. # load adblock config
  103. #
  104. config_load adblock
  105. config_foreach parse_config source
  106. }
  107. # f_envcheck: check/set environment prerequisites
  108. #
  109. f_envcheck()
  110. {
  111. # check 'enabled' option
  112. #
  113. if [ ${adb_enabled} -ne 1 ]
  114. then
  115. if [ "$(ls -dA "${adb_dnsdir}/${adb_dnsprefix}"* >/dev/null 2>&1)" ]
  116. then
  117. f_rmdns
  118. f_dnsrestart
  119. fi
  120. f_log "info " "adblock is currently disabled, please set adb_enabled to '1' to use this service"
  121. exit 0
  122. fi
  123. # check fetch utility
  124. #
  125. if [ ! -x "${adb_fetch}" ] && [ "$(readlink -fn "/bin/wget")" = "/bin/uclient-fetch" ]
  126. then
  127. adb_fetch="/bin/uclient-fetch"
  128. adb_fetchparm="-q --timeout=10 --no-check-certificate -O"
  129. fi
  130. if [ -z "${adb_fetch}" ] || [ -z "${adb_fetchparm}" ] || [ ! -x "${adb_fetch}" ] || [ "$(readlink -fn "${adb_fetch}")" = "/bin/busybox" ]
  131. then
  132. f_log "error" "required download utility with ssl support not found, e.g. install full 'wget' package"
  133. fi
  134. # create dns hideout directory
  135. #
  136. if [ ! -d "${adb_dnshidedir}" ]
  137. then
  138. mkdir -p -m 660 "${adb_dnshidedir}"
  139. chown -R "${adb_dns}":"${adb_dns}" "${adb_dnshidedir}" 2>/dev/null
  140. else
  141. rm -f "${adb_dnshidedir}/${adb_dnsprefix}"*
  142. fi
  143. # create adblock temp file/directory
  144. #
  145. adb_tmpload="$(mktemp -tu)"
  146. adb_tmpfile="$(mktemp -tu)"
  147. adb_tmpdir="$(mktemp -p /tmp -d)"
  148. # prepare whitelist entries
  149. #
  150. if [ -s "${adb_whitelist}" ]
  151. then
  152. awk "${adb_whitelist_rset}" "${adb_whitelist}" > "${adb_tmpdir}/tmp.whitelist"
  153. fi
  154. }
  155. # f_rmtemp: remove temporary files & directories
  156. #
  157. f_rmtemp()
  158. {
  159. if [ -d "${adb_tmpdir}" ]
  160. then
  161. rm -f "${adb_tmpload}"
  162. rm -f "${adb_tmpfile}"
  163. rm -rf "${adb_tmpdir}"
  164. fi
  165. }
  166. # f_rmdns: remove dns related files & directories
  167. #
  168. f_rmdns()
  169. {
  170. if [ -n "${adb_dns}" ]
  171. then
  172. rm -f "${adb_dnsdir}/${adb_dnsprefix}"*
  173. rm -f "${adb_backupdir}/${adb_dnsprefix}"*.gz
  174. rm -rf "${adb_dnshidedir}"
  175. fi
  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. break
  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 'https://github.com/openwrt/packages/blob/master/net/adblock/files/README.md' (${adb_sysver})"
  301. f_rmtemp
  302. if [ "$(ls -dA "${adb_dnsdir}/${adb_dnsprefix}"* >/dev/null 2>&1)" ]
  303. then
  304. f_rmdns
  305. f_dnsrestart
  306. fi
  307. exit 255
  308. fi
  309. fi
  310. }
  311. # main function for block list processing
  312. #
  313. f_main()
  314. {
  315. local enabled url cnt sum_cnt=0 mem_total=0
  316. local src_name src_rset shalla_archive list active_lists active_triggers
  317. mem_total="$(awk '$1 ~ /^MemTotal/ {printf $2}' "/proc/meminfo" 2>/dev/null)"
  318. f_log "info " "start adblock processing ..."
  319. for src_name in ${adb_sources}
  320. do
  321. eval "enabled=\"\${enabled_${src_name}}\""
  322. eval "url=\"\${adb_src_${src_name}}\""
  323. eval "src_rset=\"\${adb_src_rset_${src_name}}\""
  324. adb_dnsfile="${adb_tmpdir}/${adb_dnsprefix}.${src_name}"
  325. > "${adb_tmpload}"
  326. > "${adb_tmpfile}"
  327. adb_rc=0
  328. # basic pre-checks
  329. #
  330. if [ "${enabled}" != "1" ] || [ -z "${url}" ] || [ -z "${src_rset}" ]
  331. then
  332. f_list remove
  333. continue
  334. fi
  335. # download block list
  336. #
  337. f_log "debug" "name: ${src_name}, enabled: ${enabled}, backup: ${adb_backup}, dns: ${adb_dns}, fetch: ${adb_fetch}, memory: ${mem_total}"
  338. if [ "${src_name}" = "blacklist" ]
  339. then
  340. cat "${url}" 2>/dev/null > "${adb_tmpload}"
  341. adb_rc=${?}
  342. elif [ "${src_name}" = "shalla" ]
  343. then
  344. shalla_archive="${adb_tmpdir}/shallalist.tar.gz"
  345. "${adb_fetch}" ${adb_fetchparm} "${shalla_archive}" "${url}" 2>/dev/null
  346. adb_rc=${?}
  347. if [ ${adb_rc} -eq 0 ]
  348. then
  349. for category in ${adb_src_cat_shalla}
  350. do
  351. tar -xOzf "${shalla_archive}" BL/${category}/domains >> "${adb_tmpload}"
  352. adb_rc=${?}
  353. if [ ${adb_rc} -ne 0 ]
  354. then
  355. break
  356. fi
  357. done
  358. fi
  359. rm -f "${shalla_archive}"
  360. rm -rf "${adb_tmpdir}/BL"
  361. else
  362. "${adb_fetch}" ${adb_fetchparm} "${adb_tmpload}" "${url}" 2>/dev/null
  363. adb_rc=${?}
  364. fi
  365. # check download result and prepare domain output (incl. tld compression, list backup & restore)
  366. #
  367. if [ ${adb_rc} -eq 0 ] && [ -s "${adb_tmpload}" ]
  368. then
  369. awk "${src_rset}" "${adb_tmpload}" 2>/dev/null > "${adb_tmpfile}"
  370. if [ -s "${adb_tmpfile}" ]
  371. then
  372. awk -F "." '{for(f=NF;f > 1;f--) printf "%s.", $f;print $1}' "${adb_tmpfile}" 2>/dev/null | sort -u > "${adb_tmpload}"
  373. awk '{if(NR==1){tld=$NF};while(getline){if($NF !~ tld"\\."){print tld;tld=$NF}}print tld}' "${adb_tmpload}" 2>/dev/null > "${adb_tmpfile}"
  374. awk -F "." '{for(f=NF;f > 1;f--) printf "%s.", $f;print $1}' "${adb_tmpfile}" 2>/dev/null > "${adb_tmpload}"
  375. mv -f "${adb_tmpload}" "${adb_tmpfile}"
  376. f_list backup
  377. else
  378. f_list restore
  379. fi
  380. else
  381. f_list restore
  382. fi
  383. # remove whitelist domains, final list preparation
  384. #
  385. if [ ${adb_rc} -eq 0 ] && [ -s "${adb_tmpfile}" ]
  386. then
  387. if [ -s "${adb_tmpdir}/tmp.whitelist" ]
  388. then
  389. grep -vf "${adb_tmpdir}/tmp.whitelist" "${adb_tmpfile}" 2>/dev/null | eval "${adb_dnsformat}" > "${adb_dnsfile}"
  390. else
  391. cat "${adb_tmpfile}" 2>/dev/null | eval "${adb_dnsformat}" > "${adb_dnsfile}"
  392. fi
  393. adb_rc=${?}
  394. if [ ${adb_rc} -ne 0 ]
  395. then
  396. f_list remove
  397. fi
  398. else
  399. f_list remove
  400. fi
  401. done
  402. # overall sort
  403. #
  404. for src_name in $(ls -dASr "${adb_tmpdir}/${adb_dnsprefix}"* 2>/dev/null)
  405. do
  406. if [ ${mem_total} -ge 64000 ]
  407. then
  408. if [ -s "${adb_tmpdir}/blocklist.overall" ]
  409. then
  410. sort "${adb_tmpdir}/blocklist.overall" "${adb_tmpdir}/blocklist.overall" "${src_name}" | uniq -u > "${adb_tmpdir}/tmp.blocklist"
  411. mv -f "${adb_tmpdir}/tmp.blocklist" "${src_name}"
  412. fi
  413. cat "${src_name}" >> "${adb_tmpdir}/blocklist.overall"
  414. fi
  415. cnt="$(wc -l < "${src_name}")"
  416. sum_cnt=$((sum_cnt + cnt))
  417. list="${src_name/*./}"
  418. if [ -z "${active_lists}" ]
  419. then
  420. active_lists="\"${list}\":\"${cnt}\""
  421. else
  422. active_lists="${active_lists},\"${list}\":\"${cnt}\""
  423. fi
  424. done
  425. # restart the dns backend and write statistics to procd service instance
  426. #
  427. mv -f "${adb_tmpdir}/${adb_dnsprefix}"* "${adb_dnsdir}" 2>/dev/null
  428. chown "${adb_dns}":"${adb_dns}" "${adb_dnsdir}/${adb_dnsprefix}"* 2>/dev/null
  429. f_rmtemp
  430. f_dnsrestart
  431. if [ "${adb_dnsup}" = "true" ]
  432. then
  433. f_log "info " "block lists with overall ${sum_cnt} domains loaded successfully (${adb_sysver})"
  434. for name in ${adb_iface}
  435. do
  436. active_triggers="${active_triggers}[\"interface.*.up\",[\"if\",[\"eq\",\"interface\",\"${name}\"],[\"run_script\",\"/etc/init.d/adblock\",\"start\"],1000]],"
  437. done
  438. active_triggers="${active_triggers}[\"config.change\",[\"if\",[\"eq\",\"package\",\"adblock\"],[\"run_script\",\"/etc/init.d/adblock\",\"start\"],1000]]"
  439. ubus call service set "{\"name\":\"adblock\",
  440. \"instances\":{\"adblock\":{\"command\":[\"/usr/bin/adblock.sh\"],
  441. \"data\":{\"active_lists\":[{${active_lists}}],
  442. \"adblock_version\":\"${adb_ver}\",
  443. \"blocked_domains\":\"${sum_cnt}\",
  444. \"dns_backend\":\"${adb_dns}\",
  445. \"last_rundate\":\"$(/bin/date "+%d.%m.%Y %H:%M:%S")\",
  446. \"system\":\"${adb_sysver}\"}}},
  447. \"triggers\":[${active_triggers}]}"
  448. else
  449. f_log "error" "dns backend restart with active block lists failed"
  450. fi
  451. }
  452. # handle different adblock actions
  453. #
  454. f_envload
  455. case "${1}" in
  456. stop)
  457. f_rmtemp
  458. f_rmdns
  459. f_dnsrestart
  460. ;;
  461. restart)
  462. f_rmtemp
  463. f_rmdns
  464. f_envcheck
  465. f_main
  466. ;;
  467. suspend)
  468. f_switch suspend
  469. ;;
  470. resume)
  471. f_switch resume
  472. ;;
  473. query)
  474. f_query "${2}"
  475. ;;
  476. *)
  477. f_envcheck
  478. f_main
  479. ;;
  480. esac
  481. exit 0