86 lines
2.4 KiB
Bash
86 lines
2.4 KiB
Bash
# Copyright 2021 Google LLC
|
|
#
|
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
# you may not use this file except in compliance with the License.
|
|
# You may obtain a copy of the License at
|
|
#
|
|
# http://www.apache.org/licenses/LICENSE-2.0
|
|
#
|
|
# Unless required by applicable law or agreed to in writing, software
|
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
# See the License for the specific language governing permissions and
|
|
# limitations under the License.
|
|
|
|
[ -n "${gbmc_ncsi_nft_lib-}" ] && return
|
|
|
|
source /usr/share/network/lib.sh || exit
|
|
|
|
gbmc_ncsi_nft_init=
|
|
gbmc_ncsi_nft_lastip4=
|
|
gbmc_ncsi_nft_lastip6=
|
|
|
|
gbmc_ncsi_nft_update() {
|
|
[ -n "$gbmc_ncsi_nft_init" ] || return
|
|
|
|
printf 'NCSI firewall for IPv4(%s) IPv6(%s)\n' \
|
|
"${gbmc_ncsi_nft_lastip4:-(deleted)}" \
|
|
"${gbmc_ncsi_nft_lastip6:-(deleted)}" >&2
|
|
|
|
local contents=
|
|
contents+='table inet filter {'$'\n'
|
|
contents+=' chain ncsi_input {'$'\n'
|
|
|
|
local ip4="$gbmc_ncsi_nft_lastip4"
|
|
if [ -n "$ip4" ]; then
|
|
contents+=" ip daddr $ip4 goto ncsi_legacy_input"$'\n'
|
|
fi
|
|
|
|
local ip6="$gbmc_ncsi_nft_lastip6"
|
|
if [ -n "$ip6" ]; then
|
|
contents+=" ip6 daddr $ip6 goto ncsi_legacy_input"$'\n'
|
|
fi
|
|
|
|
contents+=' }'$'\n'
|
|
contents+='}'$'\n'
|
|
|
|
local rfile=/run/nftables/30-gbmc-ncsi-in.rules
|
|
mkdir -p -m 755 "$(dirname "$rfile")"
|
|
printf '%s' "$contents" >"$rfile"
|
|
|
|
systemctl reset-failed nftables && systemctl --no-block reload-or-restart nftables || true
|
|
}
|
|
|
|
gbmc_ncsi_nft_hook() {
|
|
if [ "$change" = 'init' ]; then
|
|
gbmc_ncsi_nft_init=1
|
|
gbmc_ncsi_nft_update
|
|
elif [ "$change" = 'addr' -a "$intf" = '@NCSI_IF@' -a "$scope" = 'global' ]; then
|
|
if [ "$fam" = 'inet6' ]; then
|
|
local -n lastip='gbmc_ncsi_nft_lastip6'
|
|
local pfx_bytes=()
|
|
ip_to_bytes pfx_bytes "$ip" || return
|
|
# We only want to allow a <pfx>:: address
|
|
for (( i = 8; i < 16; ++i )); do
|
|
if (( pfx_bytes[i] != 0 )); then
|
|
return
|
|
fi
|
|
done
|
|
else
|
|
local -n lastip='gbmc_ncsi_nft_lastip4'
|
|
fi
|
|
if [ "$action" = 'add' -a "$ip" != "$lastip" ]; then
|
|
lastip="$ip"
|
|
gbmc_ncsi_nft_update
|
|
fi
|
|
if [ "$action" = 'del' -a "$ip" = "$lastip" ]; then
|
|
lastip=
|
|
gbmc_ncsi_nft_update
|
|
fi
|
|
fi
|
|
}
|
|
|
|
GBMC_IP_MONITOR_HOOKS+=(gbmc_ncsi_nft_hook)
|
|
|
|
gbmc_ncsi_nft_lib=1
|