qubes-firewall 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. #!/bin/sh
  2. set -e
  3. PIDFILE=/var/run/qubes/qubes-firewall.pid
  4. XENSTORE_IPTABLES=/qubes-iptables
  5. XENSTORE_IPTABLES_HEADER=/qubes-iptables-header
  6. XENSTORE_ERROR=/qubes-iptables-error
  7. OLD_RULES=""
  8. # PIDfile handling
  9. [ -e "$PIDFILE" ] && kill -s 0 $(cat "$PIDFILE") 2>/dev/null && exit 0
  10. echo $$ >$PIDFILE
  11. trap 'exit 0' TERM
  12. FIRST_TIME=yes
  13. while true; do
  14. echo "1" > /proc/sys/net/ipv4/ip_forward
  15. if [ "$FIRST_TIME" ]; then
  16. FIRST_TIME=
  17. TRIGGER=reload
  18. else
  19. # Wait for changes in qubesdb file
  20. /usr/bin/qubesdb-watch $XENSTORE_IPTABLES
  21. TRIGGER=$(/usr/bin/qubesdb-read $XENSTORE_IPTABLES)
  22. fi
  23. if ! [ "$TRIGGER" = "reload" ]; then continue ; fi
  24. # Disable forwarding to prevent potential "leaks" that might
  25. # be bypassing the firewall or some proxy service (e.g. tor)
  26. # during the time when the rules are being (re)applied
  27. echo "0" > /proc/sys/net/ipv4/ip_forward
  28. RULES=$(qubesdb-read $XENSTORE_IPTABLES_HEADER)
  29. IPTABLES_SAVE=$(iptables-save | sed '/^\*filter/,/^COMMIT/d')
  30. OUT=$(printf '%s\n%s\n' "$RULES" "$IPTABLES_SAVE" | sed 's/\\n\|\\x0a/\n/g' | iptables-restore 2>&1 || true)
  31. for i in $(qubesdb-list -f /qubes-iptables-domainrules) ; do
  32. RULES=$(qubesdb-read "$i")
  33. ERRS=$(printf '%s\n' "$RULES" | sed 's/\\n\|\\x0a/\n/g' | /sbin/iptables-restore -n 2>&1 || true)
  34. if [ -n "$ERRS" ]; then
  35. echo "Failed applying rules for $i: $ERRS" >&2
  36. OUT="$OUT$ERRS"
  37. fi
  38. done
  39. qubesdb-write $XENSTORE_ERROR "$OUT"
  40. if [ -n "$OUT" ]; then
  41. DISPLAY=:0 /usr/bin/notify-send -t 3000 "Firewall loading error ($(hostname))" "$OUT" || :
  42. fi
  43. # Check if user didn't define some custom rules to be applied as well...
  44. [ -x /rw/config/qubes-firewall-user-script ] && /rw/config/qubes-firewall-user-script
  45. # XXX: Backward compatibility
  46. [ -x /rw/config/qubes_firewall_user_script ] && /rw/config/qubes_firewall_user_script
  47. done