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.

1247 lines
49 KiB

  1. #!/bin/sh /etc/rc.common
  2. # Copyright 2017-2020 Stan Grishin (stangri@melmac.net)
  3. # shellcheck disable=SC2039,SC1091,SC2018,SC2019
  4. PKG_VERSION='dev-test'
  5. # sysctl net.ipv4.conf.default.rp_filter=1
  6. # sysctl net.ipv4.conf.all.rp_filter=1
  7. # shellcheck disable=SC2034
  8. START=94
  9. # shellcheck disable=SC2034
  10. USE_PROCD=1
  11. if type extra_command 1>/dev/null 2>&1; then
  12. extra_command 'support' "Generates output required to troubleshoot routing issues
  13. Use '-d' option for more detailed output
  14. Use '-p' option to automatically upload data under VPR paste.ee account
  15. WARNING: while paste.ee uploads are unlisted, they are still publicly available
  16. List domain names after options to include their lookup in report"
  17. extra_command 'version' 'Show version information'
  18. else
  19. # shellcheck disable=SC2034
  20. EXTRA_COMMANDS='support version'
  21. # shellcheck disable=SC2034
  22. EXTRA_HELP=" support Generates output required to troubleshoot routing issues
  23. Use '-d' option for more detailed output
  24. Use '-p' option to automatically upload data under VPR paste.ee account
  25. WARNING: while paste.ee uploads are unlisted, they are still publicly available
  26. List domain names after options to include their lookup in report"
  27. fi
  28. readonly packageName='vpn-policy-routing'
  29. readonly serviceName="$packageName $PKG_VERSION"
  30. readonly PIDFile="/var/run/${packageName}.pid"
  31. readonly jsonFile="/var/run/${packageName}.json"
  32. readonly dnsmasqFile="/var/dnsmasq.d/${packageName}"
  33. readonly sharedMemoryOutput="/dev/shm/$packageName-output"
  34. readonly _OK_='\033[0;32m\xe2\x9c\x93\033[0m'
  35. readonly _FAIL_='\033[0;31m\xe2\x9c\x97\033[0m'
  36. readonly __OK__='\033[0;32m[\xe2\x9c\x93]\033[0m'
  37. readonly __FAIL__='\033[0;31m[\xe2\x9c\x97]\033[0m'
  38. readonly _ERROR_='\033[0;31mERROR\033[0m'
  39. readonly _WARNING_='\033[0;33mWARNING\033[0m'
  40. gatewaySummary=''; errorSummary=''; warningSummary='';
  41. serviceEnabled=''; verbosity=''; strictMode='';
  42. wanTableID=''; wanMark=''; fwMask='';
  43. ipv6Enabled=''; srcIpset=''; destIpset=''; resolverIpset='';
  44. wanIface4=''; wanIface6=''; ifaceMark=''; ifaceTableID='';
  45. ifAll=''; ifSupported=''; ignoredIfaces=''; supportedIfaces=''; icmpIface='';
  46. wanGW4=''; wanGW6=''; bootTimeout=''; insertOption='';
  47. webuiChainColumn=''; webuiShowIgnore=''; dnsmasqIpsetSupported='';
  48. procdReloadDelay='';
  49. usedChainsList='PREROUTING'
  50. ipsetSupported='true'
  51. configLoaded='false'
  52. version() { echo "$PKG_VERSION"; }
  53. create_lock() { [ -e "$PIDFile" ] && return 1; touch "$PIDFile"; }
  54. remove_lock() { [ -e "$PIDFile" ] && rm -f "$PIDFile"; }
  55. trap remove_lock EXIT
  56. output_ok() { output 1 "$_OK_"; output 2 "$__OK__\\n"; }
  57. output_okn() { output 1 "$_OK_\\n"; output 2 "$__OK__\\n"; }
  58. output_fail() { s=1; output 1 "$_FAIL_"; output 2 "$__FAIL__\\n"; }
  59. output_failn() { output 1 "$_FAIL_\\n"; output 2 "$__FAIL__\\n"; }
  60. str_replace() { printf "%b" "$1" | sed -e "s/$(printf "%b" "$2")/$(printf "%b" "$3")/g"; }
  61. str_replace() { echo "${1//$2/$3}"; }
  62. str_contains() { [ -n "$2" ] && [ "${1//$2}" != "$1" ]; }
  63. str_contains_word() { echo "$1" | grep -q -w "$2"; }
  64. str_to_lower() { echo "$1" | tr 'A-Z' 'a-z'; }
  65. str_extras_to_underscore() { echo "$1" | tr '[\. ~`!@#$%^&*()\+/,<>?//;:]' '_'; }
  66. str_extras_to_space() { echo "$1" | tr ';{}' ' '; }
  67. output() {
  68. # Can take a single parameter (text) to be output at any verbosity
  69. # Or target verbosity level and text to be output at specifc verbosity
  70. local msg memmsg logmsg
  71. if [ $# -ne 1 ]; then
  72. if [ $((verbosity & $1)) -gt 0 ] || [ "$verbosity" = "$1" ]; then shift; else return 0; fi
  73. fi
  74. [ -t 1 ] && printf "%b" "$1"
  75. msg="${1//$serviceName /service }";
  76. if [ "$(printf "%b" "$msg" | wc -l)" -gt 0 ]; then
  77. [ -s "$sharedMemoryOutput" ] && memmsg="$(cat "$sharedMemoryOutput")"
  78. logmsg="$(printf "%b" "${memmsg}${msg}" | sed 's/\x1b\[[0-9;]*m//g')"
  79. logger -t "${packageName:-service} [$$]" "$(printf "%b" "$logmsg")"
  80. rm -f "$sharedMemoryOutput"
  81. else
  82. printf "%b" "$msg" >> "$sharedMemoryOutput"
  83. fi
  84. }
  85. is_present() { command -v "$1" >/dev/null 2>&1; }
  86. is_installed() { [ -s "/usr/lib/opkg/info/${1}.control" ]; }
  87. is_variant_installed() { [ "$(echo /usr/lib/opkg/info/"${1}"*.control)" != "/usr/lib/opkg/info/${1}*.control" ]; }
  88. build_ifAll() { ifAll="${ifAll}${1} "; }
  89. build_ifSupported() { is_supported_interface "$1" && ifSupported="${ifSupported}${1} "; }
  90. vpr_find_iface() {
  91. local iface i param="$2"
  92. [ "$param" = 'wan6' ] || param='wan'
  93. "network_find_${param}" iface
  94. is_tunnel "$iface" && unset iface
  95. if [ -z "$iface" ]; then
  96. for i in $ifAll; do
  97. if "is_${param}" "$i"; then break; else unset i; fi
  98. done
  99. fi
  100. eval "$1"='${iface:-$i}'
  101. }
  102. vpr_get_gateway() {
  103. local iface="$2" dev="$3" gw
  104. network_get_gateway gw "$iface"
  105. if [ -z "$gw" ] || [ "$gw" = '0.0.0.0' ]; then
  106. gw="$(ip -4 a list dev "$dev" 2>/dev/null | grep inet | awk '{print $2}' | awk -F "/" '{print $1}')"
  107. fi
  108. eval "$1"='$gw'
  109. }
  110. vpr_get_gateway6() {
  111. local iface="$2" dev="$3" gw
  112. network_get_gateway6 gw "$iface"
  113. if [ -z "$gw" ] || [ "$gw" = '::/0' ] || [ "$gw" = '::0/0' ] || [ "$gw" = '::' ]; then
  114. gw="$(ip -6 a list dev "$dev" 2>/dev/null | grep inet6 | awk '{print $2}')"
  115. fi
  116. eval "$1"='$gw'
  117. }
  118. is_l2tp() { local proto; proto=$(uci -q get network."$1".proto); [ "${proto:0:4}" = "l2tp" ]; }
  119. is_oc() { local proto; proto=$(uci -q get network."$1".proto); [ "${proto:0:11}" = "openconnect" ]; }
  120. is_ovpn() { local dev; dev=$(uci -q get network."$1".ifname); [ "${dev:0:3}" = "tun" ] || [ "${dev:0:3}" = "tap" ] || [ -f "/sys/devices/virtual/net/${dev}/tun_flags" ]; }
  121. is_pptp() { local proto; proto=$(uci -q get network."$1".proto); [ "${proto:0:4}" = "pptp" ]; }
  122. is_tor() { [ "$(str_to_lower "$1")" = "tor" ]; }
  123. is_tor_running() {
  124. local ret=0
  125. if [ -s "/etc/tor/torrc" ]; then
  126. json_load "$(ubus call service list "{ 'name': 'tor' }")"
  127. json_select 'tor'; json_select 'instances'; json_select 'instance1';
  128. json_get_var ret 'running'; json_cleanup
  129. fi
  130. if [ "$ret" = "0" ]; then return 1; else return 0; fi
  131. }
  132. is_wg() { local proto; proto=$(uci -q get network."$1".proto); [ "${proto:0:9}" = "wireguard" ]; }
  133. is_tunnel() { is_l2tp "$1" || is_oc "$1" || is_ovpn "$1" || is_pptp "$1" || is_tor "$1" || is_wg "$1"; }
  134. is_wan() { [ "$1" = "$wanIface4" ] || { [ "${1##wan}" != "$1" ] && [ "${1##wan6}" = "$1" ]; } || [ "${1%%wan}" != "$1" ]; }
  135. is_wan6() { [ -n "$wanIface6" ] && [ "$1" = "$wanIface6" ] || [ "${1/#wan6}" != "$1" ] || [ "${1/%wan6}" != "$1" ]; }
  136. is_ignored_interface() { str_contains_word "$ignoredIfaces" "$1"; }
  137. is_supported_interface() { str_contains_word "$supportedIfaces" "$1" || { ! is_ignored_interface "$1" && { is_wan "$1" || is_wan6 "$1" || is_tunnel "$1"; }; }; }
  138. is_mac_address() { expr "$1" : '[0-9A-F][0-9A-F]:[0-9A-F][0-9A-F]:[0-9A-F][0-9A-F]:[0-9A-F][0-9A-F]:[0-9A-F][0-9A-F]:[0-9A-F][0-9A-F]$' >/dev/null; }
  139. is_ipv4() { expr "$1" : '[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*$' >/dev/null; }
  140. is_ipv6() { ! is_mac_address "$1" && str_contains "$1" ":"; }
  141. is_family_mismatch() { ( is_netmask "${1//!}" && is_ipv6 "${2//!}" ) || ( is_ipv6 "${1//!}" && is_netmask "${2//!}" ); }
  142. is_ipv6_link_local() { [ "${1:0:4}" = "fe80" ]; }
  143. is_ipv6_unique_local() { [ "${1:0:2}" = "fc" ] || [ "${1:0:2}" = "fd" ]; }
  144. is_ipv6_global() { [ "${1:0:4}" = "2001" ]; }
  145. # is_ipv6_global() { is_ipv6 "$1" && ! is_ipv6_link_local "$1" && ! is_ipv6_link_local "$1"; }
  146. is_netmask() { local ip="${1%/*}"; [ "$ip" != "$1" ] && is_ipv4 "$ip"; }
  147. is_domain() { str_contains "$1" '[a-zA-Z]'; }
  148. is_phys_dev() { [ "${1:0:1}" = "@" ] && ip l show | grep -E -q "^\\d+\\W+${1:1}"; }
  149. is_turris() { /bin/ubus -S call system board | /bin/grep 'Turris' | /bin/grep -q '15.05'; }
  150. is_chaos_calmer() { ubus -S call system board | grep -q 'Chaos Calmer'; }
  151. dnsmasq_kill() { killall -q -HUP dnsmasq; }
  152. dnsmasq_restart() { output 3 'Restarting DNSMASQ '; if /etc/init.d/dnsmasq restart >/dev/null 2>&1; then output_okn; else output_failn; fi; }
  153. is_default_dev() { [ "$1" = "$(ip -4 r | grep -m1 'dev' | grep -Eso 'dev [^ ]*' | awk '{print $2}')" ]; }
  154. is_supported_iface_dev() {
  155. for n in $ifSupported; do
  156. if [ "$1" = "$(uci -q get "network.${n}.ifname" || echo "$n")" ] || \
  157. [ "$1" = "$(uci -q get "network.${n}.proto")-${n}" ] ; then return 0; fi
  158. done
  159. return 1
  160. }
  161. is_supported_protocol () { grep -o '^[^#]*' /etc/protocols | grep -w -v '0' | grep . | awk '{print $1}' | grep -q "$1"; }
  162. append_chains_targets() {
  163. local chain iface name
  164. config_get name "$1" 'name' 'blank'
  165. config_get chain "$1" 'chain' 'PREROUTING'
  166. config_get iface "$1" 'interface'
  167. if ! str_contains_word "$usedChainsList" "$chain"; then
  168. usedChainsList="$usedChainsList $chain"
  169. if [ "$chain" != 'PREROUTING' ] && [ "$webuiChainColumn" != '1' ]; then
  170. warningSummary="${warningSummary}$_WARNING_: Chain '$chain' is used by a policy '$name', but a WebUI setting to show chains column (webui_chain_column) is disabled!\\n"
  171. fi
  172. fi
  173. if [ "$iface" = 'ignore' ] && ! str_contains_word "$supportedIfaces" 'ignore'; then
  174. supportedIfaces="$supportedIfaces ignore"
  175. if [ "$webuiShowIgnore" != '1' ]; then
  176. warningSummary="${warningSummary}$_WARNING_: The 'ignore' target is used by a policy '$name', but a WebUI setting to show 'ignore' target (webui_show_ignore_target) is disabled!\\n"
  177. fi
  178. fi
  179. }
  180. load_package_config() {
  181. [ "$configLoaded" = 'false' ] || return 0
  182. config_load "$packageName"
  183. config_get_bool serviceEnabled 'config' 'enabled' 0
  184. config_get_bool strictMode 'config' 'strict_enforcement' 1
  185. config_get_bool ipv6Enabled 'config' 'ipv6_enabled' 0
  186. config_get_bool srcIpset 'config' 'src_ipset' 0
  187. config_get_bool destIpset 'config' 'dest_ipset' 0
  188. config_get resolverIpset 'config' 'resolver_ipset' 'dnsmasq.ipset'
  189. config_get verbosity 'config' 'verbosity' '2'
  190. config_get wanTableID 'config' 'wan_tid' '201'
  191. config_get wanMark 'config' 'wan_mark' '0x010000'
  192. config_get fwMask 'config' 'fw_mask' '0xff0000'
  193. config_get icmpIface 'config' 'icmp_interface'
  194. config_get ignoredIfaces 'config' 'ignored_interface'
  195. config_get supportedIfaces 'config' 'supported_interface'
  196. config_get bootTimeout 'config' 'boot_timeout' '30'
  197. config_get insertOption 'config' 'iptables_rule_option' 'append'
  198. config_get procdReloadDelay 'config' 'procd_reload_delay' '0'
  199. config_get_bool webuiChainColumn 'config' 'webui_chain_column' '0'
  200. config_get_bool webuiShowIgnore 'config' 'webui_show_ignore_target' '0'
  201. config_foreach append_chains_targets 'policy'
  202. if [ -z "${verbosity##*[!0-9]*}" ] || [ "$verbosity" -lt 0 ] || [ "$verbosity" -gt 2 ]; then
  203. verbosity=2
  204. fi
  205. . /lib/functions/network.sh
  206. . /usr/share/libubox/jshn.sh
  207. mkdir -p "${PIDFile%/*}"
  208. mkdir -p "${jsonFile%/*}"
  209. mkdir -p "${dnsmasqFile%/*}"
  210. if [ -n "$icmpIface" ] && ! str_contains_word "$usedChainsList" 'OUTPUT'; then
  211. usedChainsList="$usedChainsList OUTPUT"
  212. fi
  213. case $insertOption in
  214. insert|-i|-I) insertOption='-I';;
  215. append|-a|-A|*) insertOption='-A';;
  216. esac
  217. [ "$resolverIpset" = 'dnsmasq.ipset' ] && dnsmasqIpsetSupported='true'
  218. if dnsmasq -v 2>/dev/null | grep -q 'no-ipset' || ! dnsmasq -v 2>/dev/null | grep -q -w 'ipset'; then
  219. unset dnsmasqIpsetSupported
  220. if [ -n "$dnsmasqIpsetSupported" ]; then
  221. errorSummary="${errorSummary}${_ERROR_}: Resolver ipset support (dnsmasq.ipset) is enabled in $packageName, but DNSMASQ ipsets are not supported on this system!\\n"
  222. fi
  223. fi
  224. if ! ipset help hash:net >/dev/null 2>&1; then
  225. unset ipsetSupported
  226. if [ -n "$dnsmasqIpsetSupported" ]; then
  227. errorSummary="${errorSummary}${_ERROR_}: DNSMASQ ipsets are supported, but ipset is either not installed or installed ipset does not support 'hash:net' type!\\n"
  228. unset dnsmasqIpsetSupported
  229. fi
  230. if [ "$destIpset" -ne 0 ]; then
  231. errorSummary="${errorSummary}${_ERROR_}: Destination ipset support is enabled in $packageName, but ipset is either not installed or installed ipset does not support 'hash:net' type!\\n"
  232. destIpset=0
  233. fi
  234. if [ "$srcIpset" -ne 0 ]; then
  235. errorSummary="${errorSummary}${_ERROR_}: Source ipset support is enabled in $packageName, but ipset is either not installed or installed ipset does not support 'hash:net' type!\\n"
  236. srcIpset=0
  237. fi
  238. fi
  239. if ! ipset help hash:mac >/dev/null 2>&1; then
  240. if [ "$srcIpset" -ne 0 ]; then
  241. errorSummary="${errorSummary}${_ERROR_}: Source ipset support is enabled in $packageName, but ipset is either not installed or installed ipset does not support 'hash:mac' type!\\n"
  242. srcIpset=0
  243. fi
  244. fi
  245. configLoaded='true'
  246. }
  247. is_enabled() {
  248. load_package_config
  249. if [ "$serviceEnabled" -eq 0 ]; then
  250. if [ "$1" = 'on_start' ]; then
  251. errorSummary="${errorSummary}${_ERROR_}: ${packageName} is currently disabled.\\n"
  252. errorSummary="${errorSummary}Enable ${packageName} from WebUI or run the following commands:\\n"
  253. errorSummary="${errorSummary}uci set $packageName.config.enabled='1'; uci commit $packageName;\\n"
  254. fi
  255. return 1
  256. fi
  257. }
  258. load_network() {
  259. if [ -z "$ifAll" ]; then
  260. config_load 'network'
  261. config_foreach build_ifAll 'interface'
  262. fi
  263. vpr_find_iface wanIface4 'wan'
  264. [ "$ipv6Enabled" -ne 0 ] && vpr_find_iface wanIface6 'wan6'
  265. [ -n "$wanIface4" ] && network_get_gateway wanGW4 "$wanIface4"
  266. [ -n "$wanIface6" ] && network_get_gateway6 wanGW6 "$wanIface6"
  267. wanGW="${wanGW4:-$wanGW6}"
  268. unset ifSupported
  269. config_load 'network'
  270. config_foreach build_ifSupported 'interface'
  271. }
  272. is_wan_up() {
  273. local sleepCount=1
  274. load_network
  275. while [ -z "$wanGW" ] ; do
  276. load_network
  277. if [ $((sleepCount)) -gt $((bootTimeout)) ] || [ -n "$wanGW" ]; then break; fi
  278. output "$serviceName waiting for wan gateway...\\n"
  279. sleep 1
  280. network_flush_cache
  281. sleepCount=$((sleepCount+1))
  282. done
  283. if [ -n "$wanGW" ]; then
  284. return 0
  285. else
  286. errorSummary="${errorSummary}${_ERROR_}: ${serviceName} failed to discover WAN gateway!\\n"
  287. return 1
  288. fi
  289. }
  290. ipt_cleanup() {
  291. local i
  292. for i in PREROUTING FORWARD INPUT OUTPUT; do
  293. while iptables -t mangle -D $i -m mark --mark 0x0/0xff0000 -j VPR_${i} >/dev/null 2>&1; do : ; done
  294. done
  295. for i in PREROUTING FORWARD INPUT OUTPUT; do
  296. while iptables -t mangle -D $i -j VPR_${i} >/dev/null 2>&1; do : ; done
  297. done
  298. }
  299. # shellcheck disable=SC2086
  300. ipt() {
  301. local d failFlagIpv4=1 failFlagIpv6=1
  302. for d in "${*//-A/-D}" "${*//-I/-D}" "${*//-N/-F}" "${*//-N/-X}"; do
  303. [ "$d" != "$*" ] && { iptables $d >/dev/null 2>&1; ip6tables $d >/dev/null 2>&1; }
  304. done
  305. d="$*"; iptables $d >/dev/null 2>&1 && failFlagIpv4=0;
  306. if [ "$ipv6Enabled" -gt 0 ]; then ip6tables $d >/dev/null 2>&1 && failFlagIpv6=0; fi
  307. [ "$failFlagIpv4" -eq 0 ] || [ "$failFlagIpv6" -eq 0 ]
  308. }
  309. # shellcheck disable=SC2086
  310. ips() {
  311. local command="$1" ipset="${2//-/_}" param="$3" comment="$4" appendix failFlag=0
  312. if str_contains "$ipset" '_ip'; then
  313. ipset="${ipset//_ip}"; appendix='_ip';
  314. elif str_contains "$ipset" '_mac'; then
  315. ipset="${ipset//_mac}"; appendix='_mac';
  316. fi
  317. case "$command" in
  318. add_dnsmasq)
  319. [ "$resolverIpset" = "dnsmasq.ipset" ] || return 1
  320. if [ -z "$dnsmasqIpsetSupported" ]; then
  321. warningSummary="${warningSummary}${_WARNING_}: The 'resolver_ipset' is set to 'dnsmasq.ipset', but DNSMASQ ipsets are not supported on this system!\\n"
  322. failFlag=1
  323. elif [ "$ipv6Enabled" -ne 0 ]; then
  324. echo "ipset=/${param}/${ipset},${ipset}6 # $comment" >> "$dnsmasqFile" || failFlag=1
  325. else
  326. echo "ipset=/${param}/${ipset} # $comment" >> "$dnsmasqFile" || failFlag=1
  327. fi
  328. ;;
  329. add)
  330. if [ -z "$appendix" ] && [ "$destIpset" -eq 0 ]; then return 1; fi
  331. if [ -n "$appendix" ] && [ "$srcIpset" -eq 0 ]; then return 1; fi
  332. if [ "$ipv6Enabled" -ne 0 ] && [ "$appendix" != "_mac" ]; then
  333. ipset -q -! $command "${ipset}6${appendix}" $param comment "$comment" || failFlag=1
  334. fi
  335. ipset -q -! $command "${ipset}${appendix}" $param comment "$comment" || failFlag=1
  336. ;;
  337. create)
  338. if [ "$ipv6Enabled" -ne 0 ] && [ "$appendix" != "_mac" ]; then
  339. ipset -q -! "$command" "${ipset}6${appendix}" $param family inet6 || failFlag=1
  340. fi
  341. ipset -q -! "$command" "${ipset}${appendix}" $param || failFlag=1
  342. ;;
  343. destroy|flush)
  344. ipset -q -! "$command" "${ipset}6${appendix}" 2>/dev/null || failFlag=1
  345. ipset -q -! "$command" "${ipset}${appendix}" 2>/dev/null || failFlag=1
  346. return 0
  347. ;;
  348. esac
  349. return $failFlag
  350. }
  351. insert_tor_policy() {
  352. local comment="$1" iface="$2" laddr="$3" lport="$4" raddr="$5" rport="$6" proto chain
  353. proto="$(str_to_lower "$7")"
  354. chain="${8:-PREROUTING}"
  355. if [ -n "${laddr}${lport}${rport}" ]; then
  356. processPolicyWarning="${processPolicyWarning}${_WARNING_}: Please unset 'src_addr', 'src_port' and 'dest_port' for policy '$comment'\\n"
  357. fi
  358. if [ -n "$proto" ] && [ "$proto" != "all" ]; then
  359. processPolicyWarning="${processPolicyWarning}${_WARNING_}: Please unset 'proto' or set 'proto' to 'all' for policy '$comment'\\n"
  360. fi
  361. if [ "$chain" != "PREROUTING" ]; then
  362. processPolicyWarning="${processPolicyWarning}${_WARNING_}: Please unset 'chain' or set 'chain' to 'PREROUTING' for policy '$comment'\\n"
  363. fi
  364. ips 'add' "${iface}" "$raddr" "${comment}: $raddr" || processPolicyError="${processPolicyError}${_ERROR_}: ipset 'add' $iface $raddr\\n"
  365. return 0
  366. }
  367. insert_policy() {
  368. local comment="$1" iface="$2" laddr="$3" lport="$4" raddr="$5" rport="$6" proto chain
  369. local mark param i valueNeg value dest ipInsertOption="-A"
  370. proto="$(str_to_lower "$7")"
  371. chain="${8:-PREROUTING}"
  372. mark=$(eval echo "\$mark_${iface//-/_}")
  373. if [ "$ipv6Enabled" -eq 0 ] && ( is_ipv6 "$laddr" || is_ipv6 "$raddr" ); then
  374. processPolicyError="${processPolicyError}${_ERROR_}: Skipping IPv6 policy '$comment' as IPv6 support is disabled\\n"
  375. return 1
  376. fi
  377. if [ -n "$mark" ]; then
  378. dest="-g VPR_MARK${mark}"
  379. elif [ "$iface" = "ignore" ]; then
  380. dest="-j RETURN"
  381. else
  382. processPolicyError="${processPolicyError}${_ERROR_}: Unknown fw_mark for ${iface}\\n"
  383. return 0
  384. fi
  385. if [ -z "$proto" ]; then
  386. if [ -n "$lport" ] || [ -n "$rport" ]; then
  387. proto='tcp udp'
  388. else
  389. proto='all'
  390. fi
  391. fi
  392. if is_family_mismatch "$laddr" "$raddr"; then
  393. processPolicyError="${processPolicyError}${_ERROR_}: Mismatched IP family between '$laddr' and '$raddr' in policy '$comment'\\n"
  394. return 0
  395. fi
  396. for i in $proto; do
  397. if [ "$i" = 'all' ]; then
  398. param="-t mangle ${ipInsertOption} VPR_${chain} $dest"
  399. elif ! is_supported_protocol "$i"; then
  400. processPolicyError="${processPolicyError}${_ERROR_}: Unknown protocol '$i' in policy '$comment'\\n"
  401. return 0
  402. else
  403. param="-t mangle ${ipInsertOption} VPR_${chain} $dest -p $i"
  404. fi
  405. if [ -n "$laddr" ]; then
  406. if [ "${laddr:0:1}" = "!" ]; then
  407. valueNeg='!'; value="${laddr:1}"
  408. else
  409. unset valueNeg; value="$laddr";
  410. fi
  411. if is_phys_dev "$value"; then
  412. param="$param $valueNeg -m physdev --physdev-in ${value:1}"
  413. elif is_mac_address "$value"; then
  414. param="$param -m mac $valueNeg --mac-source $value"
  415. else
  416. param="$param $valueNeg -s $value"
  417. fi
  418. fi
  419. if [ -n "$lport" ]; then
  420. if [ "${lport:0:1}" = "!" ]; then
  421. valueNeg='!'; value="${lport:1}"
  422. else
  423. unset valueNeg; value="$lport";
  424. fi
  425. param="$param -m multiport $valueNeg --sport ${value//-/:}"
  426. fi
  427. if [ -n "$raddr" ]; then
  428. if [ "${raddr:0:1}" = "!" ]; then
  429. valueNeg='!'; value="${raddr:1}"
  430. else
  431. unset valueNeg; value="$raddr";
  432. fi
  433. param="$param $valueNeg -d $value"
  434. fi
  435. if [ -n "$rport" ]; then
  436. if [ "${rport:0:1}" = "!" ]; then
  437. valueNeg='!'; value="${rport:1}"
  438. else
  439. unset valueNeg; value="$rport";
  440. fi
  441. param="$param -m multiport $valueNeg --dport ${value//-/:}"
  442. fi
  443. [ -n "$comment" ] && param="$param -m comment --comment $(str_extras_to_underscore "$comment")"
  444. ipt "$param" || processPolicyError="${processPolicyError}${_ERROR_}: iptables $param\\n"
  445. done
  446. return 0
  447. }
  448. r_process_policy(){
  449. local comment="$1" iface="$2" laddr="$3" lport="$4" raddr="$5" rport="$6" proto="$7" chain="$8" resolved_laddr resolved_raddr i ipsFailFlag
  450. if str_contains "$laddr" '[ ;\{\}]'; then
  451. for i in $(str_extras_to_space "$laddr"); do [ -n "$i" ] && r_process_policy "$comment" "$iface" "$i" "$lport" "$raddr" "$rport" "$proto" "$chain"; done
  452. return 0
  453. elif str_contains "$lport" '[ ;\{\}]'; then
  454. for i in $(str_extras_to_space "$lport"); do [ -n "$i" ] && r_process_policy "$comment" "$iface" "$laddr" "$i" "$raddr" "$rport" "$proto" "$chain"; done
  455. return 0
  456. elif str_contains "$raddr" '[ ;\{\}]'; then
  457. for i in $(str_extras_to_space "$raddr"); do [ -n "$i" ] && r_process_policy "$comment" "$iface" "$laddr" "$lport" "$i" "$rport" "$proto" "$chain"; done
  458. return 0
  459. elif str_contains "$rport" '[ ;\{\}]'; then
  460. for i in $(str_extras_to_space "$rport"); do [ -n "$i" ] && r_process_policy "$comment" "$iface" "$laddr" "$lport" "$raddr" "$i" "$proto" "$chain"; done
  461. return 0
  462. fi
  463. # start non-recursive processing
  464. # process TOR, netmask, physical device and mac-address separately, so we don't send them to resolveip
  465. if is_tor "$iface"; then
  466. insert_tor_policy "$comment" "$iface" "$laddr" "$lport" "$raddr" "$rport" "$proto" "$chain"
  467. elif is_phys_dev "$laddr"; then
  468. insert_policy "$comment" "$iface" "$laddr" "$lport" "$raddr" "$rport" "$proto" "$chain"
  469. elif [ -n "$laddr" ] && [ -z "${lport}${raddr}${rport}" ] && [ "$chain" = 'PREROUTING' ]; then
  470. if is_mac_address "$laddr"; then
  471. if [ -n "$proto" ] && [ "$proto" != 'all' ] && [ "$srcIpset" -ne 0 ]; then
  472. processPolicyWarning="${processPolicyWarning}${_WARNING_}: Please unset 'proto' or set 'proto' to 'all' for policy: '$comment', mac-address: '$laddr'\\n"
  473. fi
  474. ips 'add' "${iface}_mac" "$laddr" "${comment}: $laddr" || ipsFailFlag=1
  475. else
  476. if [ -n "$proto" ] && [ "$proto" != "all" ] && [ "$srcIpset" -ne 0 ]; then
  477. processPolicyWarning="${processPolicyWarning}${_WARNING_}: Please unset 'proto' or set 'proto' to 'all' for policy: '$comment', source: '$laddr'\\n"
  478. fi
  479. ips 'add' "${iface}_ip" "$laddr" "${comment}: $laddr" || ipsFailFlag=1
  480. fi
  481. elif [ -n "$raddr" ] && [ -z "${laddr}${lport}${rport}" ] && [ "$chain" = 'PREROUTING' ]; then
  482. if [ -n "$proto" ] && [ "$proto" != 'all' ]; then
  483. processPolicyWarning="${processPolicyWarning}${_WARNING_}: Please unset 'proto' or set 'proto' to 'all' for policy: '$comment', destination: '$raddr'\\n"
  484. fi
  485. if is_domain "$raddr"; then
  486. ips 'add_dnsmasq' "${iface}" "$raddr" "${comment}" || ipsFailFlag=1
  487. else
  488. ips 'add' "${iface}" "$raddr" "${comment}: $raddr" || ipsFailFlag=1
  489. fi
  490. else
  491. ipsFailFlag=1
  492. fi
  493. [ -n "$ipsFailFlag" ] || return 0;
  494. if is_mac_address "$laddr"; then
  495. insert_policy "$comment" "$iface" "$laddr" "$lport" "$raddr" "$rport" "$proto" "$chain"
  496. elif is_netmask "$laddr" || is_netmask "$raddr"; then
  497. insert_policy "$comment" "$iface" "$laddr" "$lport" "$raddr" "$rport" "$proto" "$chain"
  498. else
  499. [ -n "$laddr" ] && resolved_laddr="$(resolveip "$laddr")"
  500. [ -n "$raddr" ] && resolved_raddr="$(resolveip "$raddr")"
  501. if [ -n "$resolved_laddr" ] && [ "$resolved_laddr" != "$laddr" ]; then
  502. for i in $resolved_laddr; do [ -n "$i" ] && r_process_policy "$comment $laddr" "$iface" "$i" "$lport" "$raddr" "$rport" "$proto" "$chain"; done
  503. elif [ -n "$resolved_raddr" ] && [ "$resolved_raddr" != "$raddr" ]; then
  504. for i in $resolved_raddr; do [ -n "$i" ] && r_process_policy "$comment $raddr" "$iface" "$laddr" "$lport" "$i" "$rport" "$proto" "$chain"; done
  505. else
  506. insert_policy "$comment" "$iface" "$laddr" "$lport" "$raddr" "$rport" "$proto" "$chain"
  507. fi
  508. fi
  509. }
  510. process_policy(){
  511. local name comment iface laddr lport raddr rport param mark processPolicyError processPolicyWarning proto chain enabled
  512. config_get comment "$1" 'comment'
  513. config_get name "$1" 'name' 'blank'
  514. config_get iface "$1" 'interface'
  515. config_get laddr "$1" 'src_addr'
  516. config_get lport "$1" 'src_port'
  517. config_get raddr "$1" 'dest_addr'
  518. config_get rport "$1" 'dest_port'
  519. config_get proto "$1" 'proto'
  520. config_get chain "$1" 'chain' 'PREROUTING'
  521. config_get_bool enabled "$1" 'enabled' 1
  522. [ "$enabled" -gt 0 ] || return 0
  523. proto="$(str_to_lower "$proto")"
  524. [ "$proto" = 'auto' ] && unset proto
  525. comment="${comment:-$name}"
  526. output 2 "Routing '$comment' via $iface "
  527. if [ -z "$comment" ]; then
  528. errorSummary="${errorSummary}${_ERROR_}: Policy name is empty\\n"
  529. output_fail; return 1;
  530. fi
  531. if [ -z "${laddr}${lport}${raddr}${rport}" ]; then
  532. errorSummary="${errorSummary}${_ERROR_}: Policy '$comment' missing all IPs/ports\\n"
  533. output_fail; return 1;
  534. fi
  535. if [ -z "$iface" ]; then
  536. errorSummary="${errorSummary}${_ERROR_}: Policy '$comment' has no assigned interface\\n"
  537. output_fail; return 1;
  538. fi
  539. if ! is_supported_interface "$iface"; then
  540. errorSummary="${errorSummary}${_ERROR_}: Policy '$comment' has unknown interface: '${iface}'\\n"
  541. output_fail; return 1;
  542. fi
  543. lport="${lport// / }"; lport="${lport// /,}"; lport="${lport//,\!/ !}";
  544. rport="${rport// / }"; rport="${rport// /,}"; rport="${rport//,\!/ !}";
  545. r_process_policy "$comment" "$iface" "$laddr" "$lport" "$raddr" "$rport" "$proto" "$chain"
  546. if [ -n "$processPolicyWarning" ]; then
  547. warningSummary="${warningSummary}${processPolicyWarning}\\n"
  548. fi
  549. if [ -n "$processPolicyError" ]; then
  550. output_fail
  551. errorSummary="${errorSummary}${processPolicyError}\\n"
  552. else
  553. output_ok
  554. fi
  555. }
  556. table_destroy(){
  557. local tid="$1" iface="$2" mark="$3"
  558. if [ -n "$tid" ] && [ -n "$iface" ] && [ -n "$mark" ]; then
  559. ipt -t mangle -F "VPR_MARK${mark}"
  560. ipt -t mangle -X "VPR_MARK${mark}"
  561. ip -4 rule del fwmark "$mark" table "$tid" >/dev/null 2>&1
  562. ip -6 rule del fwmark "$mark" table "$tid" >/dev/null 2>&1
  563. ip -4 rule del table "$tid" >/dev/null 2>&1
  564. ip -6 rule del table "$tid" >/dev/null 2>&1
  565. ip -4 route flush table "$tid" >/dev/null 2>&1
  566. ip -6 route flush table "$tid" >/dev/null 2>&1
  567. ips 'flush' "${iface}"; ips 'destroy' "${iface}";
  568. ips 'flush' "${iface}_ip"; ips 'destroy' "${iface}_ip";
  569. ips 'flush' "${iface}_mac"; ips 'destroy' "${iface}_mac";
  570. ip -4 route flush cache
  571. ip -6 route flush cache
  572. sed -i "/$iface/d" /etc/iproute2/rt_tables
  573. return 0
  574. else
  575. return 1
  576. fi
  577. }
  578. # shellcheck disable=SC2086
  579. table_create(){
  580. local tid="$1" mark="$2" iface="$3" gw4="$4" dev="$5" gw6="$6" dev6="$7" dscp s=0 i ipv4_error=0 ipv6_error=1
  581. if [ -z "$tid" ] || [ -z "$mark" ] || [ -z "$iface" ]; then
  582. return 1
  583. fi
  584. table_destroy "$tid" "$iface" "$mark"
  585. if [ -n "$gw4" ] || [ "$strictMode" -ne 0 ]; then
  586. echo "$tid" "$iface" >> /etc/iproute2/rt_tables
  587. if [ -z "$gw4" ]; then
  588. ip -4 route add unreachable default table "$tid" >/dev/null 2>&1 || ipv4_error=1
  589. else
  590. ip -4 route add default via "$gw4" dev "$dev" table "$tid" >/dev/null 2>&1 || ipv4_error=1
  591. fi
  592. # ip -4 route list table main | grep -v 'br-lan' | while read -r i; do
  593. ip -4 route list table main | while read -r i; do
  594. idev="$(echo "$i" | grep -Eso 'dev [^ ]*' | awk '{print $2}')"
  595. if ! is_supported_iface_dev "$idev"; then
  596. ip -4 route add $i table "$tid" >/dev/null 2>&1 || ipv4_error=1
  597. fi
  598. done
  599. ip -4 route flush cache || ipv4_error=1
  600. ip -4 rule add fwmark "${mark}/${fwMask}" table "$tid" || ipv4_error=1
  601. ipt -t mangle -N "VPR_MARK${mark}" || ipv4_error=1
  602. ipt -t mangle -A "VPR_MARK${mark}" -j MARK --set-xmark "${mark}/${fwMask}" || ipv4_error=1
  603. ipt -t mangle -A "VPR_MARK${mark}" -j RETURN || ipv4_error=1
  604. fi
  605. if [ "$ipv6Enabled" -ne 0 ]; then
  606. ipv6_error=0
  607. if { [ -n "$gw6" ] && [ "$gw6" != "::/0" ]; } || [ "$strictMode" -ne 0 ]; then
  608. if [ -z "$gw6" ] || [ "$gw6" = "::/0" ]; then
  609. ip -6 route add unreachable default table "$tid" || ipv6_error=1
  610. else
  611. ip -6 route list table main | grep " dev $dev6 " | while read -r i; do
  612. ip -6 route add $i table "$tid" >/dev/null 2>&1 || ipv6_error=1
  613. done
  614. fi
  615. ip -6 route flush cache || ipv6_error=1
  616. ip -6 rule add fwmark "${mark}/${fwMask}" table "$tid" || ipv6_error=1
  617. fi
  618. fi
  619. if [ $ipv4_error -eq 0 ] || [ $ipv6_error -eq 0 ]; then
  620. dscp="$(uci -q get "${packageName}".config."${iface}"_dscp)"
  621. if [ "${dscp:-0}" -ge 1 ] && [ "${dscp:-0}" -le 63 ]; then
  622. ipt -t mangle -I VPR_PREROUTING -m dscp --dscp "${dscp}" -g "VPR_MARK${mark}" || s=1
  623. fi
  624. if [ -n "$ipsetSupported" ] && { [ -n "$dnsmasqIpsetSupported" ] || [ "$destIpset" -ne 0 ]; }; then
  625. if ips 'create' "${iface}" 'hash:net comment' && ips 'flush' "${iface}"; then
  626. for i in $usedChainsList; do
  627. ipt -t mangle -I VPR_${i} -m set --match-set "${iface}" dst -g "VPR_MARK${mark}" || s=1
  628. if [ "$ipv6Enabled" -ne 0 ]; then ipt -t mangle -I VPR_${i} -m set --match-set "${iface}6" dst -g "VPR_MARK${mark}" || s=1; fi
  629. done
  630. else
  631. s=1
  632. fi
  633. fi
  634. if [ -n "$ipsetSupported" ] && [ "$srcIpset" -ne 0 ]; then
  635. if ips 'create' "${iface}_ip" 'hash:net comment' && ips 'flush' "${iface}_ip"; then
  636. ipt -t mangle -I VPR_PREROUTING -m set --match-set "${iface}_ip" src -g "VPR_MARK${mark}" || s=1
  637. if [ "$ipv6Enabled" -ne 0 ]; then ipt -t mangle -I VPR_PREROUTING -m set --match-set "${iface}6_ip" src -g "VPR_MARK${mark}" || s=1; fi
  638. else
  639. s=1
  640. fi
  641. if ips 'create' "${iface}_mac" 'hash:mac comment' && ips 'flush' "${iface}_mac"; then
  642. ipt -t mangle -I VPR_PREROUTING -m set --match-set "${iface}_mac" src -g "VPR_MARK${mark}" || s=1
  643. else
  644. s=1
  645. fi
  646. fi
  647. if [ "$iface" = "$icmpIface" ]; then
  648. ipt -t mangle -I VPR_OUTPUT -p icmp -g "VPR_MARK${mark}" || s=1
  649. fi
  650. else
  651. s=1
  652. fi
  653. return $s
  654. }
  655. process_interface(){
  656. local gw4 gw6 dev dev6 s=0 dscp iface="$1" action="$2" displayText
  657. is_supported_interface "$iface" || return 0
  658. is_wan6 "$iface" && return 0
  659. [ $((ifaceMark)) -gt $((fwMask)) ] && return 1
  660. network_get_device dev "$iface"
  661. [ -z "$dev" ] && config_get dev "$iface" 'ifname'
  662. if is_wan "$iface" && [ -n "$wanIface6" ]; then
  663. network_get_device dev6 "$wanIface6"
  664. [ -z "$dev6" ] && config_get dev6 "$wanIface6" 'ifname'
  665. fi
  666. [ -z "$dev6" ] && dev6="$dev"
  667. [ -z "$ifaceTableID" ] && ifaceTableID="$wanTableID"; [ -z "$ifaceMark" ] && ifaceMark="$wanMark";
  668. case "$action" in
  669. destroy)
  670. table_destroy "${ifaceTableID}" "${iface}" "${ifaceMark}"
  671. ifaceTableID="$((ifaceTableID + 1))"; ifaceMark="$(printf '0x%06x' $((ifaceMark + wanMark)))";
  672. ;;
  673. create)
  674. eval "mark_${iface//-/_}"='$ifaceMark'
  675. eval "tid_${iface//-/_}"='$ifaceTableID'
  676. table_destroy "${ifaceTableID}" "${iface}"
  677. vpr_get_gateway gw4 "$iface" "$dev"
  678. vpr_get_gateway6 gw6 "$iface" "$dev6"
  679. if [ "$iface" = "$dev" ]; then
  680. displayText="${iface}/${gw4:-0.0.0.0}"
  681. else
  682. displayText="${iface}/${dev}/${gw4:-0.0.0.0}"
  683. fi
  684. [ "$ipv6Enabled" -ne 0 ] && displayText="${displayText}/${gw6:-::/0}"
  685. output 2 "Creating table '$displayText' "
  686. is_default_dev "$dev" && displayText="${displayText} ${__OK__}"
  687. if table_create "$ifaceTableID" "$ifaceMark" "$iface" "$gw4" "$dev" "$gw6" "$dev6"; then
  688. gatewaySummary="${gatewaySummary}${displayText}\\n"
  689. output_ok
  690. else
  691. errorSummary="${errorSummary}${_ERROR_}: Failed to set up '$displayText'\\n"
  692. output_fail
  693. fi
  694. ifaceTableID="$((ifaceTableID + 1))"; ifaceMark="$(printf '0x%06x' $((ifaceMark + wanMark)))";
  695. ;;
  696. esac
  697. return $s
  698. }
  699. process_tor_interface(){
  700. local s=0 iface="$1" action="$2" displayText
  701. case "$action" in
  702. destroy)
  703. for i in PREROUTING FORWARD INPUT OUTPUT; do
  704. ipt -t nat -D "${i}" -m mark --mark "0x0/${fwMask}" -j "VPR_${i}"
  705. ipt -t nat -F "VPR_${i}"; ipt -t nat -X "VPR_${i}";
  706. done
  707. ;;
  708. create)
  709. output 2 "Creating TOR redirects "
  710. dnsPort="$(grep -m1 DNSPort /etc/tor/torrc | awk -F: '{print $2}')"
  711. transPort="$(grep -m1 TransPort /etc/tor/torrc | awk -F: '{print $2}')"
  712. dnsPort="${dnsPort:-9053}"; transPort="${transPort:-9040}";
  713. for i in $usedChainsList; do
  714. ipt -t nat -N "VPR_${i}"
  715. ipt -t nat "$insertOption" "$i" -m mark --mark "0x0/${fwMask}" -j "VPR_${i}"
  716. done
  717. if ips 'create' "${iface}" 'hash:net comment' && ips 'flush' "${iface}"; then
  718. for i in $usedChainsList; do
  719. ipt -t nat -I "VPR_${i}" -p udp -m udp --dport 53 -m set --match-set "${iface}" dst -j REDIRECT --to-ports "$dnsPort" -m comment --comment "TorDNS-UDP" || s=1
  720. ipt -t nat -I "VPR_${i}" -p tcp -m tcp --dport 80 -m set --match-set "${iface}" dst -j REDIRECT --to-ports "$transPort" -m comment --comment "TorHTTP-TCP" || s=1
  721. ipt -t nat -I "VPR_${i}" -p udp -m udp --dport 80 -m set --match-set "${iface}" dst -j REDIRECT --to-ports "$transPort" -m comment --comment "TorHTTP-UDP" || s=1
  722. ipt -t nat -I "VPR_${i}" -p tcp -m tcp --dport 443 -m set --match-set "${iface}" dst -j REDIRECT --to-ports "$transPort" -m comment --comment "TorHTTPS-TCP" || s=1
  723. ipt -t nat -I "VPR_${i}" -p udp -m udp --dport 443 -m set --match-set "${iface}" dst -j REDIRECT --to-ports "$transPort" -m comment --comment "TorHTTPS-UDP" || s=1
  724. done
  725. else
  726. s=1
  727. fi
  728. displayText="${iface}/53->${dnsPort}/80,443->${transPort}"
  729. if [ "$s" -eq "0" ]; then
  730. gatewaySummary="${gatewaySummary}${displayText}\\n"
  731. output_ok
  732. else
  733. errorSummary="${errorSummary}${_ERROR_}: Failed to set up '$displayText'\\n"
  734. output_fail
  735. fi
  736. ;;
  737. esac
  738. return $s
  739. }
  740. convert_config(){
  741. local i src_ipset dest_ipset resolver_ipset
  742. [ -s "/etc/config/${packageName}" ] || return 0
  743. grep -q "ignored_interfaces" "/etc/config/${packageName}" && sed -i 's/ignored_interfaces/ignored_interface/g' "/etc/config/${packageName}"
  744. grep -q "supported_interfaces" "/etc/config/${packageName}" && sed -i 's/supported_interfaces/supported_interface/g' "/etc/config/${packageName}"
  745. grep -q "local_addresses" "/etc/config/${packageName}" && sed -i 's/local_addresses/local_address/g' "/etc/config/${packageName}"
  746. grep -q "local_ports" "/etc/config/${packageName}" && sed -i 's/local_ports/local_port/g' "/etc/config/${packageName}"
  747. grep -q "remote_addresses" "/etc/config/${packageName}" && sed -i 's/remote_addresses/remote_address/g' "/etc/config/${packageName}"
  748. grep -q "remote_ports" "/etc/config/${packageName}" && sed -i 's/remote_ports/remote_port/g' "/etc/config/${packageName}"
  749. grep -q "ipset_enabled" "/etc/config/${packageName}" && sed -i 's/ipset_enabled/dest_ipset/g' "/etc/config/${packageName}"
  750. grep -q "dnsmasq_enabled" "/etc/config/${packageName}" && sed -i 's/dnsmasq_enabled/resolver_ipset/g' "/etc/config/${packageName}"
  751. grep -q "enable_control" "/etc/config/${packageName}" && sed -i 's/enable_control/webui_enable_column/g' "/etc/config/${packageName}"
  752. grep -q "proto_control" "/etc/config/${packageName}" && sed -i 's/proto_control/webui_protocol_column/g' "/etc/config/${packageName}"
  753. grep -q "chain_control" "/etc/config/${packageName}" && sed -i 's/chain_control/webui_chain_column/g' "/etc/config/${packageName}"
  754. grep -q "sort_control" "/etc/config/${packageName}" && sed -i 's/sort_control/webui_sorting/g' "/etc/config/${packageName}"
  755. grep -q "local_address" "/etc/config/${packageName}" && sed -i 's/local_address/src_addr/g' "/etc/config/${packageName}"
  756. grep -q "local_port" "/etc/config/${packageName}" && sed -i 's/local_port/src_port/g' "/etc/config/${packageName}"
  757. grep -q "remote_address" "/etc/config/${packageName}" && sed -i 's/remote_address/dest_addr/g' "/etc/config/${packageName}"
  758. grep -q "remote_port" "/etc/config/${packageName}" && sed -i 's/remote_port/dest_port/g' "/etc/config/${packageName}"
  759. grep -q "local_ipset" "/etc/config/${packageName}" && sed -i 's/local_ipset/src_ipset/g' "/etc/config/${packageName}"
  760. grep -q "remote_ipset" "/etc/config/${packageName}" && sed -i 's/remote_ipset/dest_ipset/g' "/etc/config/${packageName}"
  761. dest_ipset="$(uci -q get $packageName.config.dest_ipset)"
  762. src_ipset="$(uci -q get $packageName.config.src_ipset)"
  763. resolver_ipset="$(uci -q get $packageName.config.resolver_ipset)"
  764. if [ -n "$dest_ipset" ] && [ "$dest_ipset" != "0" ] && [ "$dest_ipset" != "1" ]; then
  765. uci set "$packageName".config.dest_ipset='0'
  766. if [ -z "$resolver_ipset" ]; then
  767. uci set "$packageName".config.resolver_ipset='dnsmasq.ipset'
  768. fi
  769. uci commit "$packageName"
  770. fi
  771. if [ -n "$src_ipset" ] && [ "$src_ipset" != "0" ] && [ "$src_ipset" != "1" ]; then
  772. uci set "$packageName".config.src_ipset='1'
  773. uci commit "$packageName"
  774. fi
  775. if [ -z "$(uci -q get $packageName.config.webui_supported_protocol)" ]; then
  776. uci add_list "$packageName".config.webui_supported_protocol='tcp'
  777. uci add_list "$packageName".config.webui_supported_protocol='udp'
  778. uci add_list "$packageName".config.webui_supported_protocol='tcp udp'
  779. uci add_list "$packageName".config.webui_supported_protocol='icmp'
  780. uci add_list "$packageName".config.webui_supported_protocol='all'
  781. uci commit "$packageName"
  782. fi
  783. for i in append_local_rules append_src_rules \
  784. append_remote_rules append_dest_rules; do
  785. if [ -n "$(uci -q get $packageName.config.$i)" ]; then
  786. warningSummary="${warningSummary}$_WARNING_: $i setting is not supported in ${serviceName}.\\n"
  787. fi
  788. done
  789. for i in udp_proto_enabled forward_chain_enabled input_chain_enabled \
  790. output_chain_enabled iprule_enabled; do
  791. if [ "$(uci -q get $packageName.config.$i)" = "1" ]; then
  792. warningSummary="${warningSummary}$_WARNING_: $i setting is not supported in ${serviceName}.\\n"
  793. fi
  794. done
  795. }
  796. check_config(){ local en; config_get_bool en "$1" 'enabled' 1; [ "$en" -gt 0 ] && _cfg_enabled=0; }
  797. is_config_enabled(){
  798. local cfg="$1" _cfg_enabled=1
  799. [ -n "$1" ] || return 1
  800. config_load "$packageName"
  801. config_foreach check_config "$cfg"
  802. return "$_cfg_enabled"
  803. }
  804. process_user_file(){
  805. local path enabled shellBin="${SHELL:-/bin/ash}"
  806. config_get_bool enabled "$1" 'enabled' 1
  807. config_get path "$1" 'path'
  808. [ "$enabled" -gt 0 ] || return 0
  809. if [ ! -s "$path" ]; then
  810. errorSummary="${errorSummary}${_ERROR_}: Custom user file '$path' not found or empty!\\n"
  811. output_fail
  812. return 1
  813. fi
  814. if ! $shellBin -n "$path"; then
  815. errorSummary="${errorSummary}${_ERROR_}: Syntax error in custom user file '$path'!\\n"
  816. output_fail
  817. return 1
  818. fi
  819. output 2 "Running $path "
  820. # shellcheck disable=SC1090
  821. if ! . "$path"; then
  822. errorSummary="${errorSummary}${_ERROR_}: Error running custom user file '$path'!\\n"
  823. if grep -q -w 'curl' "$path" && ! is_present 'curl'; then
  824. errorSummary="${errorSummary}${_ERROR_}: Use of 'curl' is detected in custom user file '$path', but 'curl' isn't installed!\\n"
  825. errorSummary="${errorSummary}${_ERROR_}: If 'curl' is needed, install it with 'opkg update; opkg install curl;' command in CLI.\\n"
  826. fi
  827. output_fail
  828. return 1
  829. else
  830. output_ok
  831. return 0
  832. fi
  833. }
  834. start_service() {
  835. local dnsmasqStoredHash dnsmasqNewHash i modprobeStatus=0
  836. convert_config
  837. is_enabled 'on_start' || return 1
  838. is_wan_up || return 1
  839. if create_lock; then
  840. if [ -s "$dnsmasqFile" ]; then
  841. dnsmasqStoredHash="$(md5sum $dnsmasqFile | awk '{ print $1; }')"
  842. rm -f "$dnsmasqFile"
  843. fi
  844. for i in xt_set ip_set ip_set_hash_ip; do
  845. modprobe "$i" >/dev/null 2>/dev/null || modprobeStatus=$((modprobeStatus + 1))
  846. done
  847. if [ "$modprobeStatus" -gt 0 ] && ! is_chaos_calmer; then
  848. errorSummary="${errorSummary}${_ERROR_}: Failed to load kernel modules\\n"
  849. fi
  850. for i in $usedChainsList; do
  851. ipt -t mangle -N "VPR_${i}"
  852. ipt -t mangle "$insertOption" "$i" -m mark --mark "0x0/${fwMask}" -j "VPR_${i}"
  853. done
  854. output 1 'Processing Interfaces '
  855. config_load 'network'; config_foreach process_interface 'interface' 'create';
  856. process_tor_interface 'tor' 'destroy'; is_tor_running && process_tor_interface 'tor' 'create';
  857. output 1 '\n'
  858. if is_config_enabled 'policy'; then
  859. output 1 'Processing Policies '
  860. config_load "$packageName"; config_foreach process_policy 'policy';
  861. output 1 '\n'
  862. fi
  863. if is_config_enabled 'include'; then
  864. output 1 'Processing User File(s) '
  865. config_load "$packageName"; config_foreach process_user_file 'include';
  866. output 1 '\n'
  867. fi
  868. if [ -s "$dnsmasqFile" ]; then
  869. dnsmasqNewHash="$(md5sum $dnsmasqFile | awk '{ print $1; }')"
  870. fi
  871. [ "$dnsmasqNewHash" != "$dnsmasqStoredHash" ] && dnsmasq_restart
  872. if [ -z "$gatewaySummary" ]; then
  873. errorSummary="${errorSummary}${_ERROR_}: failed to set up any gateway!\\n"
  874. fi
  875. procd_open_instance "main"
  876. procd_set_param command /bin/true
  877. procd_set_param stdout 1
  878. procd_set_param stderr 1
  879. procd_open_data
  880. json_add_array 'status'
  881. json_add_object ''
  882. [ -n "$gatewaySummary" ] && json_add_string gateway "$gatewaySummary"
  883. [ -n "$errorSummary" ] && json_add_string error "$errorSummary"
  884. [ -n "$warningSummary" ] && json_add_string warning "$warningSummary"
  885. if [ "$strictMode" -ne 0 ] && str_contains "$gatewaySummary" '0.0.0.0'; then
  886. json_add_string mode "strict"
  887. fi
  888. json_close_object
  889. json_close_array
  890. procd_close_data
  891. procd_close_instance
  892. remove_lock
  893. else
  894. output "$serviceName: another instance of ${packageName} is currently running "
  895. output_failn
  896. return 1
  897. fi
  898. }
  899. tmpfs() {
  900. local action="$1" param="$2" value="$3"
  901. # shellcheck disable=SC2034
  902. local gateway error warning mode i
  903. if [ -s "$jsonFile" ]; then
  904. json_load_file "$jsonFile" 2>/dev/null
  905. json_select 'status' 2>/dev/null
  906. for i in gateway error warning mode; do
  907. json_get_var $i "$i" 2>/dev/null
  908. done
  909. fi
  910. case "$action" in
  911. get)
  912. printf "%b" "$(eval echo "\$$param")"; return;;
  913. add)
  914. eval "$param"='$(eval echo "\$$param")${value}';;
  915. del)
  916. case "$param" in
  917. all)
  918. unset gateway error warning mode;;
  919. *)
  920. unset "$param";;
  921. esac
  922. ;;
  923. set)
  924. eval "$param"='$value';;
  925. esac
  926. json_init
  927. json_add_object 'status'
  928. json_add_string version "$PKG_VERSION"
  929. for i in gateway error warning mode; do
  930. json_add_string "$i" "$(eval echo "\$$i")"
  931. done
  932. json_close_object
  933. json_dump > "$jsonFile"
  934. sync
  935. }
  936. service_started() {
  937. tmpfs set 'gateway' "$gatewaySummary"
  938. tmpfs set 'error' "$errorSummary"
  939. tmpfs set 'warning' "$warningSummary"
  940. if [ "$strictMode" -ne 0 ] && str_contains "$gatewaySummary" '0.0.0.0'; then
  941. tmpfs set 'mode' 'strict'
  942. fi
  943. [ -n "$gatewaySummary" ] && output "$serviceName started with gateways:\\n${gatewaySummary}"
  944. [ -n "$errorSummary" ] && output "${errorSummary}"
  945. [ -n "$warningSummary" ] && output "${warningSummary}"
  946. if [ -n "$errorSummary" ]; then
  947. return 2
  948. elif [ -n "$warningSummary" ]; then
  949. return 1
  950. else
  951. return 0
  952. fi
  953. }
  954. stop_service() {
  955. local i
  956. iptables -t mangle -L | grep -q VPR_PREROUTING || return 0
  957. if create_lock; then
  958. load_package_config
  959. for i in PREROUTING FORWARD INPUT OUTPUT; do
  960. ipt -t mangle -D "${i}" -m mark --mark "0x0/${fwMask}" -j "VPR_${i}"
  961. ipt -t mangle -F "VPR_${i}"; ipt -t mangle -X "VPR_${i}";
  962. done
  963. config_load 'network'; config_foreach process_interface 'interface' 'destroy';
  964. process_tor_interface 'tor' 'destroy'
  965. unset ifaceTableID; unset ifaceMark;
  966. if [ -s "$dnsmasqFile" ]; then
  967. rm -f "$dnsmasqFile"
  968. dnsmasq_restart
  969. fi
  970. if [ "$serviceEnabled" -ne 0 ]; then
  971. output "$serviceName stopped "; output_okn;
  972. fi
  973. remove_lock
  974. else
  975. output "$serviceName: another instance of ${packageName} is currently running "; output_failn;
  976. return 1
  977. fi
  978. }
  979. # shellcheck disable=SC2119
  980. service_triggers() {
  981. local n
  982. is_enabled || return 1
  983. if [ "$procdReloadDelay" -gt 0 ] && [ "$procdReloadDelay" -lt 100 ]; then
  984. # shellcheck disable=SC2034
  985. PROCD_RELOAD_DELAY=$(( procdReloadDelay * 1000 ))
  986. fi
  987. procd_open_validate
  988. validate_config
  989. validate_policy
  990. validate_include
  991. procd_close_validate
  992. procd_open_trigger
  993. procd_add_reload_trigger 'openvpn'
  994. if type procd_add_service_trigger 1>/dev/null 2>&1; then
  995. procd_add_service_trigger "service.restart" "firewall" /etc/init.d/${packageName} reload
  996. fi
  997. procd_add_config_trigger "config.change" "${packageName}" /etc/init.d/${packageName} reload
  998. for n in $ifSupported; do procd_add_reload_interface_trigger "$n"; procd_add_interface_trigger "interface.*" "$n" /etc/init.d/${packageName} reload; done;
  999. procd_close_trigger
  1000. output 3 "$serviceName monitoring interfaces: $ifSupported"; output_okn;
  1001. }
  1002. status_service() { support "$@"; }
  1003. support() {
  1004. local dist vers out id s param status set_d set_p tableCount i=0 dev dev6 j
  1005. readonly _SEPARATOR_='============================================================'
  1006. is_enabled
  1007. json_load "$(ubus call system board)"; json_select release; json_get_var dist distribution; json_get_var vers version
  1008. if [ -n "$wanIface4" ]; then
  1009. network_get_gateway wanGW4 "$wanIface4"
  1010. dev="$(uci -q get network."${wanIface4}".ifname)"
  1011. fi
  1012. if [ -n "$wanIface6" ]; then
  1013. dev6="$(uci -q get network."${wanIface6}".ifname)"
  1014. wanGW6=$(ip -6 route show | grep -m1 " dev $dev6 " | awk '{print $1}')
  1015. [ "$wanGW6" = "default" ] && wanGW6=$(ip -6 route show | grep -m1 " dev $dev6 " | awk '{print $3}')
  1016. fi
  1017. while [ "${1:0:1}" = "-" ]; do param="${1//-/}"; eval "set_$param=1"; shift; done
  1018. [ -e "/var/${packageName}-support" ] && rm -f "/var/${packageName}-support"
  1019. status="$serviceName running on $dist $vers."
  1020. [ -n "$wanIface4" ] && status="$status WAN (IPv4): ${wanIface4}/${dev}/${wanGW4:-0.0.0.0}."
  1021. [ -n "$wanIface6" ] && status="$status WAN (IPv6): ${wanIface6}/${dev6}/${wanGW6:-::/0}."
  1022. {
  1023. echo "$status"
  1024. echo "$_SEPARATOR_"
  1025. dnsmasq --version 2>/dev/null | sed '/^$/,$d'
  1026. if [ -n "$1" ]; then
  1027. echo "$_SEPARATOR_"
  1028. echo "Resolving domains"
  1029. for i in $1; do
  1030. echo "$i: $(resolveip "$i" | tr '\n' ' ')"
  1031. done
  1032. fi
  1033. echo "$_SEPARATOR_"
  1034. echo "Routes/IP Rules"
  1035. tableCount=$(ip rule list | grep -c 'fwmark') || tableCount=0
  1036. if [ -n "$set_d" ]; then route; else route | grep '^default'; fi
  1037. if [ -n "$set_d" ]; then ip rule list; fi
  1038. i=0; while [ $i -lt $tableCount ]; do
  1039. echo ""
  1040. echo "IPv4 Table $((wanTableID + i)): $(ip -4 route show table $((wanTableID + i)))"
  1041. echo "IPv4 Table $((wanTableID + i)) Rules:"
  1042. ip -4 rule list table "$((wanTableID + i))"
  1043. i=$((i + 1))
  1044. done
  1045. if [ "$ipv6Enabled" -ne 0 ]; then
  1046. i=0; while [ $i -lt $tableCount ]; do
  1047. ip -6 route show table $((wanTableID + i)) | while read -r param; do
  1048. echo "IPv6 Table $((wanTableID + i)): $param"
  1049. done
  1050. i=$((i + 1))
  1051. done
  1052. fi
  1053. for j in Mangle NAT; do
  1054. if [ -z "$set_d" ]; then
  1055. for i in $usedChainsList; do
  1056. if iptables -v -t "$(str_to_lower $j)" -S "VPR_${i}" 1>/dev/null 2>&1; then
  1057. echo "$_SEPARATOR_"
  1058. echo "$j IP Table: $i"
  1059. iptables -v -t "$(str_to_lower $j)" -S "VPR_${i}"
  1060. if [ "$ipv6Enabled" -ne 0 ]; then
  1061. echo "$_SEPARATOR_"
  1062. echo "$j IPv6 Table: $i"
  1063. ip6tables -v -t "$(str_to_lower $j)" -S "VPR_${i}"
  1064. fi
  1065. fi
  1066. done
  1067. else
  1068. echo "$_SEPARATOR_"
  1069. echo "$j IP Table"
  1070. iptables -L -t "$(str_to_lower $j)"
  1071. if [ "$ipv6Enabled" -ne 0 ]; then
  1072. echo "$_SEPARATOR_"
  1073. echo "$j IPv6 Table"
  1074. ip6tables -L -t "$(str_to_lower $j)"
  1075. fi
  1076. fi
  1077. i=0; ifaceMark="$wanMark";
  1078. while [ $i -lt $tableCount ]; do
  1079. if iptables -v -t "$(str_to_lower $j)" -S "VPR_MARK${ifaceMark}" 1>/dev/null 2>&1; then
  1080. echo "$_SEPARATOR_"
  1081. echo "$j IP Table MARK Chain: VPR_MARK${ifaceMark}"
  1082. iptables -v -t "$(str_to_lower $j)" -S "VPR_MARK${ifaceMark}"
  1083. ifaceMark="$(printf '0x%06x' $((ifaceMark + wanMark)))";
  1084. fi
  1085. i=$((i + 1))
  1086. done
  1087. done
  1088. echo "$_SEPARATOR_"
  1089. echo "Current ipsets"
  1090. ipset save
  1091. if [ -s "$dnsmasqFile" ]; then
  1092. echo "$_SEPARATOR_"
  1093. echo "DNSMASQ ipsets"
  1094. cat "$dnsmasqFile"
  1095. fi
  1096. echo "$_SEPARATOR_"
  1097. } | tee -a /var/${packageName}-support
  1098. if [ -n "$set_p" ]; then
  1099. printf "%b" "Pasting to paste.ee... "
  1100. if is_present 'curl' && is_variant_installed 'libopenssl' && is_installed 'ca-bundle'; then
  1101. json_init; json_add_string "description" "${packageName}-support"
  1102. json_add_array "sections"; json_add_object '0'
  1103. json_add_string "name" "$(uci -q get system.@system[0].hostname)"
  1104. json_add_string "contents" "$(cat /var/${packageName}-support)"
  1105. json_close_object; json_close_array; payload=$(json_dump)
  1106. out=$(curl -s -k "https://api.paste.ee/v1/pastes" -X "POST" -H "Content-Type: application/json" -H "X-Auth-Token:uVOJt6pNqjcEWu7qiuUuuxWQafpHhwMvNEBviRV2B" -d "$payload")
  1107. json_load "$out"; json_get_var id id; json_get_var s success
  1108. [ "$s" = "1" ] && printf "%b" "https://paste.ee/p/$id $__OK__\\n" || printf "%b" "$__FAIL__\\n"
  1109. [ -e "/var/${packageName}-support" ] && rm -f "/var/${packageName}-support"
  1110. else
  1111. printf "%b" "$__FAIL__\\n"
  1112. printf "%b" "$_ERROR_: curl, libopenssl or ca-bundle were not found!\\nRun 'opkg update; opkg install curl libopenssl ca-bundle' to install them.\\n"
  1113. fi
  1114. else
  1115. printf "%b" "Your support details have been logged to '/var/${packageName}-support'. $__OK__\\n"
  1116. fi
  1117. }
  1118. # shellcheck disable=SC2120
  1119. validate_config() {
  1120. uci_validate_section "${packageName}" config "${1}" \
  1121. 'enabled:bool:0' \
  1122. 'strict_enforcement:bool:1' \
  1123. 'ipv6_enabled:bool:0' \
  1124. 'src_ipset:bool:0' \
  1125. 'dest_ipset:bool:0' \
  1126. 'resolver_ipset::or("", "none", "dnsmasq.ipset")' \
  1127. 'verbosity:range(0,2):1' \
  1128. 'wan_tid:integer:201' \
  1129. 'wan_fw_mark:hex(8)' \
  1130. 'fw_mask:hex(8)' \
  1131. 'icmp_interface:string' \
  1132. 'ignored_interface:list(string)' \
  1133. 'supported_interface:list(string)' \
  1134. 'boot_timeout:integer:30' \
  1135. 'iptables_rule_option:or("", "append", "insert")' \
  1136. 'procd_reload_delay:integer:0' \
  1137. 'webui_enable_column:bool:0' \
  1138. 'webui_protocol_column:bool:0' \
  1139. 'webui_supported_protocol:list(string)' \
  1140. 'webui_chain_column:bool:0' \
  1141. 'webui_sorting:bool:1' \
  1142. 'webui_show_ignore_target:bool:0'
  1143. }
  1144. # shellcheck disable=SC2120
  1145. validate_policy() {
  1146. uci_validate_section "${packageName}" policy "${1}" \
  1147. 'name:string' \
  1148. 'enabled:bool:0' \
  1149. 'interface:network' \
  1150. 'proto:or(string)' \
  1151. 'chain:or("", "PREROUTING", "FORWARD", "INPUT", "OUTPUT")' \
  1152. 'src_addr:list(neg(or(host,network,macaddr)))' \
  1153. 'src_port:list(neg(or(portrange, string)))' \
  1154. 'dest_addr:list(neg(host))' \
  1155. 'dest_port:list(neg(or(portrange, string)))'
  1156. }
  1157. # shellcheck disable=SC2120
  1158. validate_include() {
  1159. uci_validate_section "${packageName}" include "${1}" \
  1160. 'path:string' \
  1161. 'enabled:bool:0'
  1162. }