util/linuxfw: initial implementation of package

This package is an initial implementation of something that can read
netfilter and iptables rules from the Linux kernel without needing to
shell out to an external utility; it speaks directly to the kernel using
syscalls and parses the data returned.

Currently this is read-only since it only knows how to parse a subset of
the available data.

Signed-off-by: Andrew Dunham <andrew@tailscale.com>
Change-Id: Iccadf5dcc081b73268d8ccf8884c24eb6a6f1ff5
This commit is contained in:
Andrew Dunham
2022-08-24 00:00:06 -04:00
committed by Andrew Dunham
parent 3c107ff301
commit ba48ec5e39
11 changed files with 1347 additions and 7 deletions

35
util/linuxfw/helpers.go Normal file
View File

@@ -0,0 +1,35 @@
// Copyright (c) Tailscale Inc & AUTHORS
// SPDX-License-Identifier: BSD-3-Clause
package linuxfw
import (
"encoding/hex"
"fmt"
"strings"
"unicode"
)
func formatMaybePrintable(b []byte) string {
// Remove a single trailing null, if any
if len(b) > 0 && b[len(b)-1] == 0 {
b = b[:len(b)-1]
}
nonprintable := strings.IndexFunc(string(b), func(r rune) bool {
return r > unicode.MaxASCII || !unicode.IsPrint(r)
})
if nonprintable >= 0 {
return "<hex>" + hex.EncodeToString(b)
}
return string(b)
}
func formatPortRange(r [2]uint16) string {
if r == [2]uint16{0, 65535} {
return fmt.Sprintf(`any`)
} else if r[0] == r[1] {
return fmt.Sprintf(`%d`, r[0])
}
return fmt.Sprintf(`%d-%d`, r[0], r[1])
}