lxcfw 19.3 KB
Newer Older
1 2 3 4
#!/bin/bash

###################################################################################################################
#
5
# Copyright © 2017-2019 Stefan Göbel < lxcfw ʇɐ subtype ˙ de >.
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
#
# lxcfw is free software: you can redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any
# later version.
#
# lxcfw is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
# warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with lxcfw. If not, see
# <http://www.gnu.org/licenses/>.
#
###################################################################################################################
#
# See lxcfw(8) for usage information.

set   -o errexit
set   -o nounset
shopt -s nullglob
shopt -u sourcepath

declare -ga firewall_temp_stuff=()
declare -gA firewall_cmdln_opts=()

# cleanup =========================================================================================================
#
# Clean up the items in the global $firewall_temp_stuff array before exiting. Every item must start with either
# 'f:' for a file, 'd:' for a directory or 'n:' for a network namespace. This prefix will be removed, and files
# will then be deleted with 'rm -f', directories with 'rmdir --ignore-fail-on-non-empty' and namespaces with the
# 'ip netns del' command. Note that for files/directories the order of elements is important!
#
cleanup() {

   local _exit="$?"

   set +o errexit
   trap '' INT QUIT TERM EXIT

   declare -ga firewall_temp_stuff

   local _elem=''
   for _elem in "${firewall_temp_stuff[@]}" ; do
      case "$_elem" in
         f:*) rm -f                            "${_elem:2}" ;;
         d:*) rmdir --ignore-fail-on-non-empty "${_elem:2}" ;;
         n:*) ip netns del                     "${_elem:2}" ;;
      esac
   done

   exit "$_exit"

}

# lock [-d <directory>] ===========================================================================================
#
# Try to get a lock, using a lock file in the specified directory (defaults to the value of $mainscr_lock if this
# is set, otherwise /run/lock/lxcfw). This function will also install the cleanup trap.
#
lock() {

   declare -g mainscr_lock

   local _lock_dir="${mainscr_lock:-/run/lock/lxcfw}"

   eval set -- "$( getopt -n lxcfw/lock -o d: -- "$@" )"
   while : ; do case "$1" in
      -d) _lock_dir="$2" ; shift 2 ;;
Stefan Göbel's avatar
Stefan Göbel committed
73
      --) shift          ; break   ;;
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
      * ) return 1                 ;;
   esac ; done

   mkdir -p -m 0700 "$_lock_dir"
   >"$_lock_dir/lock"
   exec 666<"$_lock_dir/lock"

   if ! flock -x -n 666 ; then
      printf 'Error: Already running.\n' >&2
      return 1
   fi

   firewall_temp_stuff+=( "f:$_lock_dir/lock" "d:$_lock_dir" )
   trap cleanup EXIT

}

# source_dir [-d <directory>…] ====================================================================================
#
# Source all executable files in the specified directories (in alphabetical order, may depend on locale settings).
#
source_dir() {

   local _source_dirs=()

   eval set -- "$( getopt -n lxcfw/source_dir -o d: -- "$@" )"
   while : ; do case "$1" in
      -d) _source_dirs+=( "$2" ) ; shift 2 ;;
Stefan Göbel's avatar
Stefan Göbel committed
102
      --) shift                  ; break   ;;
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
      * ) return 1                         ;;
   esac ; done

   local _source_d=''
   local _source_f=''

   for _source_d in "${_source_dirs[@]}" ; do
      for _source_f in "$_source_d"/* ; do
         if [[ -x "$_source_f" ]] ; then
            source "$_source_f"
         fi
      done
   done

   return 0

}

# join <separator> [<string>…] ====================================================================================
#
# Join the <string>s with the specified separator character.
#
join() { local IFS="$1" ; shift ; echo "$*" ; }

# parse_command_line [<parameter>…] ===============================================================================
#
# Parses the command line parameters, which must be supplied as arguments to this function. The results will be
# stored in the global associative array $firewall_cmdln_opts (read-only after a call to this function). The
# following elements may be set:
#
#     COMMAND   -   The command to run.
#
#     rules-d   -   --directory
#     routing   -   --drop-routing
#     nftfile   -   --file
#     keep-et   -   --keep-empty
#     set-nat   -   --nat
#     no-chns   -   --no-chains
#     no-elem   -   --no-elements
#     no-flsh   -   --no-flush
#     outfile   -   --output
#     preview   -   --preview
#     rs-elem   -   --restore-sets
#
parse_command_line() {

   declare -gA firewall_cmdln_opts=()
   firewall_cmdln_opts['COMMAND']="${1:-list}"

   local _opts=(
      directory: drop-routing file: keep-empty nat no-chains no-elements no-flush output: preview restore-sets
   )

   if ! _opts="$( getopt -n lxcfw -ox -l "$( join , "${_opts[@]}" )" -- "$@" )" ; then
      return 1
   fi

   eval set -- "$_opts"

   while true ; do
      case "$1" in
         --directory    ) firewall_cmdln_opts['rules-d']="$2" ; shift 2 ;;
         --drop-routing ) firewall_cmdln_opts['routing']='1'  ; shift   ;;
         --file         ) firewall_cmdln_opts['nftfile']="$2" ; shift 2 ;;
         --keep-empty   ) firewall_cmdln_opts['keep-et']='1'  ; shift   ;;
         --nat          ) firewall_cmdln_opts['set-nat']='1'  ; shift   ;;
         --no-chains    ) firewall_cmdln_opts['no-chns']='1'  ; shift   ;;
         --no-elements  ) firewall_cmdln_opts['no-elem']='1'  ; shift   ;;
         --no-flush     ) firewall_cmdln_opts['no-flsh']='1'  ; shift   ;;
         --output       ) firewall_cmdln_opts['outfile']="$2" ; shift 2 ;;
         --preview      ) firewall_cmdln_opts['preview']='1'  ; shift   ;;
         --restore-sets ) firewall_cmdln_opts['rs-sets']='1'  ; shift   ;;
Stefan Göbel's avatar
Stefan Göbel committed
175
         --             ) shift                               ; break   ;;
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
         *              ) return 1                                      ;;
      esac
   done

   declare -grA firewall_cmdln_opts

}

# nft [<nft option>…] =============================================================================================
#
# Wrapper around /usr/bin/nft to execute the commands in the temporary network namespace. Takes the same options as
# nft. Always use this in the rule scripts instead of the nft binary unless the command should be executed in the
# default namespace (run it with the full path in this case)! The temporary network namespace must be set in the
# $fw_namespace global variable (defaults to 'lxcfw-temp'), the full path to the nft binary in the $nft_fullpath
# global variable (defaults to '/usr/bin/nft')! The ip command must be in the PATH!
#
nft() {

   declare -g fw_namespace
   declare -g nft_fullpath

   ip netns exec "${fw_namespace:-lxcfw-temp}" "${nft_fullpath:-/usr/bin/nft}" "$@"

}

# list_rules [-c] [-e] [-f] [-k] [-n <namespace>] [-p <nft path>] =================================================
#
# Dump the netfilter rules active in the specified namespace (defaults to the current namespace). If -f is set the
# output will not include a 'flush ruleset' line at the top. If -c is set, the output will omit all chains (i.e.
# only tables, sets, maps etc. will be included). If -e is set, the output will omit any elements of sets and maps.
# If -k is set, empty tables, which will usually be removed from the output when -c is set, will be kept. When -c
# is not set empty tables will never be removed. The ip command must be in the PATH. If <nft path> is not set, it
# defaults to $nft_fullpath, or /usr/bin/nft if this is not set. Note: -t is a valid option for compatibilty with
# the apply_rules function, it is ignored by list_rules.
#
list_rules() {

   declare -g nft_fullpath

   local _nft_path="${nft_fullpath:-/usr/bin/nft}"
   local _inc_flsh='1'
   local _inc_elem='1'
   local _inc_chns='1'
   local _rem_mpty='1'
   local _net_name=''

   eval set -- "$( getopt -n lxcfw/list_rules -o cefkn:p:t: -- "$@" )"
   while : ; do case "$1" in
      -c) _inc_chns='0'  ; shift   ;;
      -e) _inc_elem='0'  ; shift   ;;
      -f) _inc_flsh='0'  ; shift   ;;
      -k) _rem_mpty='0'  ; shift   ;;
      -n) _net_name="$2" ; shift 2 ;;
      -p) _nft_path="$2" ; shift 2 ;;
      -t)                  shift 2 ;;
Stefan Göbel's avatar
Stefan Göbel committed
231
      --) shift          ; break   ;;
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283
      * ) return 1                 ;;
   esac ; done

   if (( _inc_flsh )) ; then
      printf 'flush ruleset\n'
   fi

   local _flt_elem=( 'cat' )
   if (( ! _inc_elem )) ; then
      _flt_elem=( 'grep' '-E' '-v' '^[[:space:]]+elements[[:space:]]+=[[:space:]]+{.+}$' )
   fi

   local _flt_chns=( 'cat' )
   local _flt_mtbl=( 'cat' )
   if (( ! _inc_chns )) ; then
      _flt_elem=( 'awk' 'BEGIN{c=0}/^\t+chain[[:space:]]+.+[[:space:]]+{$/{c=1}c==0{print}/^\t+}$/{c=0}' )
      if (( _rem_mpty )) ; then
         _flt_mtbl=( 'sed' 'N;/^table[^{]\+{\n}$/d;P;D'                                                  )
      fi
   fi

   local _flt_line=( 'sed' '/^$/d' )

   local _netns_cmd=()
   if [[ -n "$_net_name" ]] ; then
      _netns_cmd=( 'ip' 'netns' 'exec' "$_net_name" )
   fi

   "${_netns_cmd[@]}" "$_nft_path" -nn list ruleset | \
      "${_flt_elem[@]}"                             | \
      "${_flt_chns[@]}"                             | \
      "${_flt_line[@]}"                             | \
      "${_flt_mtbl[@]}"

}

# apply_rules [-c] [-e] [-f] [-k] [-n <source namespace>] [-p <nft path>] [-t <destination namespace>] ============
#
# Load the netfilter rules of the specified <source namespace> in the <destination namespace>. Both default to the
# current namespace if not specified. Accepts the same options as list_rules, see above for a description. The -t
# option is the only addition, it is used to specify the <destination namespace>. The rules that list_rules would
# dump to STDOUT with the specified options will be the exact rules that will be applied to the destination
# namespace, for example, if -f is used, rules in the destination namespace will not be flushed before the new
# rules are added.
#
apply_rules() {

   declare -g nft_fullpath

   local _nft_path="${nft_fullpath:-/usr/bin/nft}"
   local _old_opts=( "$@" )
   local _tgt_name=''
284
   local _tmp_file=''
285 286 287 288 289 290 291

   eval set -- "$( getopt -n lxcfw/apply_rules -o cefkn:p:t: -- "$@" )"
   while : ; do case "$1" in
      -p          ) _nft_path="$2" ; shift 2 ;;
      -t          ) _tgt_name="$2" ; shift 2 ;;
      -c|-e|-f|-k )                  shift   ;;
      -n          )                  shift 2 ;;
Stefan Göbel's avatar
Stefan Göbel committed
292
      --          ) shift          ; break   ;;
293 294 295 296 297 298 299 300
      *           ) return 1                 ;;
   esac ; done

   local _cmd=( "$_nft_path" )
   if [[ -n "$_tgt_name" ]] ; then
      _cmd=( 'ip' 'netns' 'exec' "$_tgt_name" "$_nft_path" )
   fi

301 302 303 304 305
   _tmp_file=$( mktemp )
   firewall_temp_stuff+=( "f:$_tmp_file" )

   list_rules "${_old_opts[@]}" >"$_tmp_file"
   "${_cmd[@]}" -f "$_tmp_file"
306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364

}

# apply_or_list [-a] [-l] =========================================================================================
#
# Calls apply_rules (-a) or list_rules (-l) with the necessary parameters (as determined from the command line
# options the script has been called with) to copy the rule set from the temporary network namespace to the current
# namespace. Without -a or -l parameter this function returns with an error.
#
apply_or_list() {

   declare -g  nft_fullpath
   declare -g  fw_namespace

   declare -gA firewall_cmdln_opts

   local _fun_mode="${1:-}"

   if [[ "$_fun_mode" != '-a' && "$_fun_mode" != '-l' ]] ; then
      return 1
   fi

   local _nft_path="${nft_fullpath:-/usr/bin/nft}"
   local _net_name="${fw_namespace:-lxcfw-temp}"

   local _lst_args=()

   if [[ -n "${firewall_cmdln_opts[no-chns]:-}" ]] ; then _lst_args+=( '-c' ) ; fi
   if [[ -n "${firewall_cmdln_opts[no-elem]:-}" ]] ; then _lst_args+=( '-e' ) ; fi
   if [[ -n "${firewall_cmdln_opts[no-flsh]:-}" ]] ; then _lst_args+=( '-f' ) ; fi
   if [[ -n "${firewall_cmdln_opts[keep-et]:-}" ]] ; then _lst_args+=( '-k' ) ; fi

   case "$_fun_mode" in
      -a ) apply_rules -n "$_net_name" -p "$_nft_path" "${_lst_args[@]}" ;;
      -l ) list_rules  -n "$_net_name" -p "$_nft_path" "${_lst_args[@]}" ;;
   esac

}

# load_rules_temp =================================================================================================
#
# Load the required rules in the temporary network namespace. Consults the command line option to determine where
# the rules should be loaded from, e.g. from a file, a rules.d folder, or copied from the current namespace. In
# addition to the rules, if --restore-sets is set any sets or maps defined in the current namespace will be copied
# to the temporary namespace.
#
load_rules_temp() {

   declare -g  fw_namespace
   declare -g  nft_fullpath

   declare -gA firewall_cmdln_opts

   local _rule_dir="${firewall_cmdln_opts[rules-d]:-${fw_rules_dir:-/etc/lxcfw/rules.d}}"
   local _nft_file="${firewall_cmdln_opts[nftfile]:-${fw_save_file:-/etc/lxcfw/rules.nft}}"

   local _copy=''
   local _load=''
   local _reld=''
365
   local _temp=''
366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393

   case "${firewall_cmdln_opts[COMMAND]}" in

      list | save )

         if [[ -n "${firewall_cmdln_opts[preview]:-}" ]] ; then
            if   [[ -n "${firewall_cmdln_opts[rules-d]:-}" && -n "${firewall_cmdln_opts[nftfile]:-}" ]] ; then
               _reld="$_rule_dir"
               _load="$_nft_file"
            elif [[ -n "${firewall_cmdln_opts[nftfile]:-}" ]] ; then
               _load="$_nft_file"
            else
               _reld="$_rule_dir"
            fi
         else
            _copy='1'
         fi
         ;;

      load   ) _load="$_nft_file" ;;
      reload ) _reld="$_rule_dir" ;;

   esac

   local _nft_path="${nft_fullpath:-/usr/bin/nft}"
   local _net_name="${fw_namespace:-lxcfw-temp}"

   if [[ -n "$_copy" ]] ; then
394 395 396 397
      _temp=$( mktemp )
      firewall_temp_stuff+=( "f:$_temp" )
      list_rules -p "$_nft_path" >"$_temp"
      ip netns exec "$_net_name" "$_nft_path" -f "$_temp"
398 399 400 401 402 403 404 405 406 407 408
   fi

   if [[ -n "$_reld" ]] ; then
      source_dir -d "$_reld"
   fi

   if [[ -n "$_load" ]] ; then
      ip netns exec "$_net_name" "$_nft_path" -f "$_load"
   fi

   if [[ -n "${firewall_cmdln_opts[rs-sets]:-}" ]] ; then
409 410 411 412
      _temp=$( mktemp )
      firewall_temp_stuff+=( "f:$_temp" )
      list_rules -p "$_nft_path" -c -f >"$_temp"
      ip netns exec "$_net_name" "$_nft_path" -f "$_temp"
413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565
   fi

}

# command_drop ====================================================================================================
#
# Called for the drop command.
#
command_drop() {

   declare -g  fw_namespace
   declare -g  nft_fullpath

   declare -gA firewall_cmdln_opts

   local _nft_path="${nft_fullpath:-/usr/bin/nft}"
   local _net_name="${fw_namespace:-lxcfw-temp}"

   ip netns exec "$_net_name" "$_nft_path" -f <(
      cat <<'_________EOF'
         table inet filter {
            chain input   { type filter hook input   priority 0 ; policy drop ; }
            chain output  { type filter hook output  priority 0 ; policy drop ; }
            chain forward { type filter hook forward priority 0 ; policy drop ; }
         }
_________EOF
   )

   if [[ -n "${firewall_cmdln_opts[routing]:-}" ]] ; then

      ip netns exec "$_net_name" "$_nft_path" -f <(
         cat <<'____________EOF'
            table inet filter {
               chain prerouting  { type filter hook prerouting  priority 0 ; policy drop ; }
               chain postrouting { type filter hook postrouting priority 0 ; policy drop ; }
            }
____________EOF
      )

   fi

   apply_rules -n "$_net_name" -p "$_nft_path"

}

# command_flush ===================================================================================================
#
# Called for the flush command.
#
command_flush() {

   declare -g  fw_namespace
   declare -g  nft_fullpath

   declare -gA firewall_cmdln_opts

   local _nft_path="${nft_fullpath:-/usr/bin/nft}"
   local _net_name="${fw_namespace:-lxcfw-temp}"

   if [[ -n "${firewall_cmdln_opts[set-nat]:-}" ]] ; then

      ip netns exec "$_net_name" "$_nft_path" -f <(
         cat <<'____________EOF'
            table ip nat {
               chain prerouting  { type nat hook prerouting  priority 0 ; policy accept              ; }
               chain postrouting { type nat hook postrouting priority 0 ; policy accept ; masquerade ; }
            }
____________EOF
      )

   fi

   apply_rules -n "$_net_name" -p "$_nft_path"

}

# command_list, command_load, command_reload ======================================================================
#
# Called for the list, load and reload commands, respectively.
#
command_list()   { load_rules_temp && apply_or_list -l ; }
command_load()   { load_rules_temp && apply_or_list -a ; }
command_reload() { load_rules_temp && apply_or_list -a ; }

# command_save ====================================================================================================
#
# Called for the save command. Same as list, just redirected to the output file.
#
command_save() { command_list >"${firewall_cmdln_opts[outfile]:-${fw_save_file:-/etc/lxcfw/rules.nft}}" ; }

## MAIN ###########################################################################################################

# firewall_main [<option>…] =======================================================================================
#
# Main function.
#
firewall_main() {

   declare -ga firewall_temp_stuff
   declare -gA firewall_cmdln_opts

   # Source the functions:

   if [[ -f /usr/local/share/lxcfw/functions ]] ; then
      source /usr/local/share/lxcfw/functions
   fi

   # Read the configuration and set default values if required:

   if [[ -f /etc/lxcfw/lxcfw.conf ]] ; then
      source /etc/lxcfw/lxcfw.conf
   fi

   declare -gr nft_fullpath="${nft_fullpath:-$( which nft )}"
   declare -gr mainscr_lock="${mainscr_lock:-/run/lock/lxcfw}"
   declare -gr handler_lock="${handler_lock:-/run/lock/dhcp-handler}"
   declare -gr handler_fifo="${handler_fifo:-/run/dhcp/fifo}"
   declare -gr fw_rules_dir="${fw_rules_dir:-/etc/lxcfw/rules.d}"
   declare -gr fw_save_file="${fw_save_file:-/etc/lxcfw/rules.nft}"
   declare -gr fw_namespace="${fw_namespace:-lxcfw-temp}"

   # Get the lock and setup a new network namespace:

   lock -d "$mainscr_lock" || exit 1

   ip netns add "$fw_namespace"
   firewall_temp_stuff+=( "n:$fw_namespace" )

   # Parse the command line and perform the requested action:

   parse_command_line "$@"

   case "${firewall_cmdln_opts[COMMAND]}" in
      drop   ) command_drop                                                                ;;
      flush  ) command_flush                                                               ;;
      list   ) command_list                                                                ;;
      load   ) command_load                                                                ;;
      reload ) command_reload                                                              ;;
      save   ) command_save                                                                ;;
      *      ) printf 'Unknown command: %s' "${firewall_cmdln_opts[COMMAND]}" >&2 ; exit 1 ;;
   esac

}

#==================================================================================================================
#
# Run firewall_main if the script is not sourced (i.e. if it itself is executed).
#
if [[ "$0" == "$BASH_SOURCE" ]] ; then
   firewall_main "$@"
fi

# :indentSize=3:tabSize=3:noTabs=true:mode=shellscript:maxLineLen=115: ############################################