| 1 | // Copyright 2023 CNI authors |
| 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 | package utils |
| 16 | |
| 17 | import ( |
| 18 | "github.com/coreos/go-iptables/iptables" |
| 19 | "sigs.k8s.io/knftables" |
| 20 | ) |
| 21 | |
| 22 | // SupportsIPTables tests whether the system supports using netfilter via the iptables API |
| 23 | // (whether via "iptables-legacy" or "iptables-nft"). (Note that this returns true if it |
| 24 | // is *possible* to use iptables; it does not test whether any other components on the |
| 25 | // system are *actually* using iptables.) |
| 26 | func SupportsIPTables() bool { |
| 27 | ipt, err := iptables.NewWithProtocol(iptables.ProtocolIPv4) |
| 28 | if err != nil { |
| 29 | return false |
| 30 | } |
| 31 | // We don't care whether the chain actually exists, only whether we can *check* |
| 32 | // whether it exists. |
| 33 | _, err = ipt.ChainExists("filter", "INPUT") |
| 34 | return err == nil |
| 35 | } |
| 36 | |
| 37 | // SupportsNFTables tests whether the system supports using netfilter via the nftables API |
| 38 | // (ie, not via "iptables-nft"). (Note that this returns true if it is *possible* to use |
| 39 | // nftables; it does not test whether any other components on the system are *actually* |
| 40 | // using nftables.) |
| 41 | func SupportsNFTables() bool { |
| 42 | // knftables.New() does sanity checks so we don't need any further test like in |
| 43 | // the iptables case. |
| 44 | _, err := knftables.New(knftables.IPv4Family, "supports_nftables_test") |
| 45 | return err == nil |
| 46 | } |