1# Copyright 2021 Google LLC
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7#      http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15[ -z "${gbmc_ncsi_nft_lib-}" ] || return
16
17gbmc_ncsi_nft_init=
18gbmc_ncsi_nft_lastip4=
19gbmc_ncsi_nft_lastip6=
20
21gbmc_ncsi_nft_update() {
22  [ -n "$gbmc_ncsi_nft_init" ] || return
23
24  printf 'NCSI firewall for IPv4(%s) IPv6(%s)\n' \
25    "${gbmc_ncsi_nft_lastip4:-(deleted)}" \
26    "${gbmc_ncsi_nft_lastip6:-(deleted)}" >&2
27
28  local contents=
29  contents+='table inet filter {'$'\n'
30  contents+='    chain ncsi_input {'$'\n'
31
32  local ip4="$gbmc_ncsi_nft_lastip4"
33  if [ -n "$ip4" ]; then
34    contents+="        ip daddr $ip4 goto ncsi_legacy_input"$'\n'
35  fi
36
37  local ip6="$gbmc_ncsi_nft_lastip6"
38  if [ -n "$ip6" ]; then
39    contents+="        ip6 daddr $ip6/128 goto ncsi_legacy_input"$'\n'
40  fi
41
42  contents+='    }'$'\n'
43  contents+='}'$'\n'
44
45  local rfile=/run/nftables/40-gbmc-ncsi-in.rules
46  mkdir -p -m 755 "$(dirname "$rfile")"
47  printf '%s' "$contents" >"$rfile"
48
49  systemctl reset-failed nftables && systemctl --no-block reload-or-restart nftables || true
50}
51
52gbmc_ncsi_nft_hook() {
53  if [ "$change" = 'init' ]; then
54    gbmc_ncsi_nft_init=1
55    gbmc_ncsi_nft_update
56  elif [ "$change" = 'addr' -a "$intf" = '@NCSI_IF@' -a "$scope" = 'global' ] &&
57     [[ "$flags" != *deprecated* ]]; then
58    if [ "$fam" = 'inet6' ]; then
59      local -n lastip='gbmc_ncsi_nft_lastip6'
60    else
61      local -n lastip='gbmc_ncsi_nft_lastip4'
62    fi
63    if [ "$action" = 'add' -a "$ip" != "$lastip" ]; then
64      lastip="$ip"
65      gbmc_ncsi_nft_update
66    fi
67    if [ "$action" = 'del' -a "$ip" = "$lastip" ]; then
68      lastip=
69      gbmc_ncsi_nft_update
70    fi
71  fi
72}
73
74GBMC_IP_MONITOR_HOOKS+=(gbmc_ncsi_nft_hook)
75
76gbmc_ncsi_nft_lib=1
77