2022-08-24 04:00:06 +00:00
|
|
|
// Copyright (c) Tailscale Inc & AUTHORS
|
|
|
|
// SPDX-License-Identifier: BSD-3-Clause
|
|
|
|
|
2023-06-30 16:06:52 +00:00
|
|
|
// TODO(#8502): add support for more architectures
|
|
|
|
//go:build linux && (arm64 || amd64)
|
2022-08-24 04:00:06 +00:00
|
|
|
|
|
|
|
package linuxfw
|
|
|
|
|
|
|
|
import (
|
2023-08-01 02:43:13 +00:00
|
|
|
"fmt"
|
|
|
|
"os/exec"
|
|
|
|
"strings"
|
|
|
|
"unicode"
|
|
|
|
|
2022-08-24 04:00:06 +00:00
|
|
|
"tailscale.com/types/logger"
|
2023-08-01 02:43:13 +00:00
|
|
|
"tailscale.com/util/multierr"
|
2022-08-24 04:00:06 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// DebugNetfilter prints debug information about iptables rules to the
|
|
|
|
// provided log function.
|
|
|
|
func DebugIptables(logf logger.Logf) error {
|
2023-07-21 03:36:12 +00:00
|
|
|
// unused.
|
2022-08-24 04:00:06 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2023-10-11 01:26:52 +00:00
|
|
|
// detectIptables returns the number of iptables rules that are present in the
|
2022-08-24 04:00:06 +00:00
|
|
|
// system, ignoring the default "ACCEPT" rule present in the standard iptables
|
|
|
|
// chains.
|
|
|
|
//
|
2023-08-01 02:43:13 +00:00
|
|
|
// It only returns an error when there is no iptables binary, or when iptables -S
|
|
|
|
// fails. In all other cases, it returns the number of non-default rules.
|
2023-10-11 01:26:52 +00:00
|
|
|
func detectIptables() (int, error) {
|
2023-08-01 02:43:13 +00:00
|
|
|
// run "iptables -S" to get the list of rules using iptables
|
|
|
|
// exec.Command returns an error if the binary is not found
|
|
|
|
cmd := exec.Command("iptables", "-S")
|
|
|
|
output, err := cmd.Output()
|
|
|
|
ip6cmd := exec.Command("ip6tables", "-S")
|
|
|
|
ip6output, ip6err := ip6cmd.Output()
|
|
|
|
var allLines []string
|
|
|
|
outputStr := string(output)
|
|
|
|
lines := strings.Split(outputStr, "\n")
|
|
|
|
ip6outputStr := string(ip6output)
|
|
|
|
ip6lines := strings.Split(ip6outputStr, "\n")
|
|
|
|
switch {
|
|
|
|
case err == nil && ip6err == nil:
|
|
|
|
allLines = append(lines, ip6lines...)
|
|
|
|
case err == nil && ip6err != nil:
|
|
|
|
allLines = lines
|
|
|
|
case err != nil && ip6err == nil:
|
|
|
|
allLines = ip6lines
|
|
|
|
default:
|
2023-08-10 15:51:29 +00:00
|
|
|
return 0, FWModeNotSupportedError{
|
2023-08-01 02:43:13 +00:00
|
|
|
Mode: FirewallModeIPTables,
|
|
|
|
Err: fmt.Errorf("iptables command run fail: %w", multierr.New(err, ip6err)),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// count the number of non-default rules
|
|
|
|
count := 0
|
|
|
|
for _, line := range allLines {
|
|
|
|
trimmedLine := strings.TrimLeftFunc(line, unicode.IsSpace)
|
|
|
|
if line != "" && strings.HasPrefix(trimmedLine, "-A") {
|
|
|
|
// if the line is not empty and starts with "-A", it is a rule appended not default
|
|
|
|
count++
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// return the count of non-default rules
|
|
|
|
return count, nil
|
2022-08-24 04:00:06 +00:00
|
|
|
}
|