utils

package
v1.3.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 13, 2026 License: MIT Imports: 27 Imported by: 0

Documentation

Index

Constants

View Source
const (
	DefaultCIDR     = "0.0.0.0/0" // matches serializer default for source/destination
	DefaultPriority = 100         // matches serializer default
	DefaultProtocol = "all"
	DefaultTarget   = "ACCEPT"

	// Rule types for progressive removal
	RuleTypeUnknown = ""        // Rules without type (remove first)
	RuleTypeServer  = "server"  // Server-synced rules (remove second)
	RuleTypeAlpacon = "alpacon" // Alpacon-created rules (remove last)
)

Default values matching alpacon-server FirewallRuleSyncSerializer

Variables

View Source
var (
	PlatformLike string
)
View Source
var (
	VirtualIfacePattern = regexp.MustCompile(`^(lo|docker|veth|br-|virbr|vmnet|tap|tun|wg|zt|tailscale|enp0s|cni)`)
)

Functions

func BackupFirewallRules added in v1.2.0

func BackupFirewallRules() (string, error)

BackupFirewallRules creates a backup of current firewall rules Returns the backup string and error

func BuildFirewallComment added in v1.2.0

func BuildFirewallComment(existingComment, ruleID, ruleType string) string

BuildFirewallComment builds firewall rule comment with rule_id and type Preserves existing comment if present Format: "existing comment,rule_id:{uuid},type:{user|server}" or "rule_id:{uuid},type:{user|server}"

func CalculateDiskIOBps

func CalculateDiskIOBps(current disk.IOCountersStat, last disk.IOCountersStat, interval time.Duration) (readBps float64, writeBps float64)

func CalculateNetworkBps

func CalculateNetworkBps(current net.IOCountersStat, last net.IOCountersStat, interval time.Duration) (inputBps float64, outputBps float64)

func CalculateNetworkPps

func CalculateNetworkPps(current net.IOCountersStat, last net.IOCountersStat, interval time.Duration) (inputPps float64, outputPps float64)

func CheckFirewallTool added in v1.2.0

func CheckFirewallTool() (nftablesInstalled bool, iptablesInstalled bool, err error)

CheckFirewallTool checks if firewall tools (nftables or iptables) are installed and detects which backend to use based on existing rules Returns (nftablesInstalled, iptablesInstalled, error)

func ChownRecursive

func ChownRecursive(path string, uid, gid int) error

func ConvertGroupIds

func ConvertGroupIds(groupIds []string) []uint32

func CopyDir

func CopyDir(src, dst string, allowOverwrite bool) error

func CopyFile

func CopyFile(src, dst string, allowOverwrite bool) error

func DetectHighLevelFirewall added in v1.2.2

func DetectHighLevelFirewall() (detected bool, toolName string)

DetectHighLevelFirewall detects if high-level firewall management tools are active Returns (detected, toolName) where toolName is "ufw" or "firewalld"

func ExpandGlobArgs added in v1.3.0

func ExpandGlobArgs(args []string, baseDir string) []string

expandGlobArgs expands glob patterns in arguments using filepath.Glob. baseDir is used as the working directory for relative path glob expansion.

func FilterVirtualInterface

func FilterVirtualInterface(ifaces net.InterfaceStatList) map[string]net.InterfaceStat

func FormatPermissions

func FormatPermissions(mode os.FileMode) string

func GenerateServerRuleID added in v1.2.0

func GenerateServerRuleID() string

GenerateServerRuleID generates a new UUID for server-type firewall rules

func GetCopyPath added in v1.1.5

func GetCopyPath(src, dst string) string

func GetDiskBaseName

func GetDiskBaseName(name string) string

func GetEnvOrDefault

func GetEnvOrDefault(envVar, defaultValue string) string

func GetFileInfo

func GetFileInfo(info os.FileInfo, path string) (permString, permOctal, owner, group string, err error)

func GetLatestVersion

func GetLatestVersion() string

func GetSystemUser

func GetSystemUser(username string) (*user.User, error)

func GetUserAgent

func GetUserAgent(name string) string

func InitPlatform

func InitPlatform()

func IsFirewallDisabled added in v1.2.2

func IsFirewallDisabled() bool

IsFirewallDisabled checks if firewall functionality is disabled

func IsSuccessStatusCode

func IsSuccessStatusCode(code int) bool

func IsSudoPAMDisabled added in v1.3.1

func IsSudoPAMDisabled() bool

IsSudoPAMDisabled returns whether sudo PAM functionality is disabled.

func IsVirtualDisk

func IsVirtualDisk(name string) bool

func IsVirtualFileSystem

func IsVirtualFileSystem(device string, fstype string, mountPoint string) bool

func JoinPath

func JoinPath(base string, paths ...string) string

func JoinUint64s

func JoinUint64s(values []uint64) string

func LookUpGID

func LookUpGID(groupname string) (int, error)

func LookUpUID

func LookUpUID(username string) (int, error)

func ParseCommentOrGenerate added in v1.2.0

func ParseCommentOrGenerate(comment string) (ruleID, ruleType string)

ParseCommentOrGenerate parses firewall comment and returns rule_id and type If not found in comment, generates new UUID and assigns "server" type

func ParseDiskName

func ParseDiskName(device string) string

func ParseFirewallComment added in v1.2.0

func ParseFirewallComment(comment string) (ruleID, ruleType, existingComment string)

ParseFirewallComment parses firewall rule comment to extract rule_id and type Format: "rule_id:{uuid},type:{user|server}" or "existing comment,rule_id:{uuid},type:{user|server}" Returns: ruleID, ruleType, existingComment

func Put

func Put(url string, body bytes.Buffer, timeout time.Duration) ([]byte, int, error)

func Quote

func Quote(s string) string

func RecreateIptablesRuleWithComment added in v1.2.0

func RecreateIptablesRuleWithComment(chainName string, rule *FirewallRuleSync, newComment string) bool

RecreateIptablesRuleWithComment re-creates an iptables rule with updated comment Returns true if re-creation was successful

func RecreateNftablesRuleWithComment added in v1.2.0

func RecreateNftablesRuleWithComment(tableName string, rule *FirewallRuleSync, newComment string) bool

RecreateNftablesRuleWithComment re-creates an nftables rule with updated comment Returns true if re-creation was successful

func RemoveFirewallRulesByType added in v1.2.0

func RemoveFirewallRulesByType(ruleType string) (int, error)

RemoveFirewallRulesByType removes all firewall rules of a specific type

func RemoveIptablesRule added in v1.2.0

func RemoveIptablesRule(chainName string, rule FirewallRuleSync) error

RemoveIptablesRule removes a specific rule from iptables

func RemoveNftablesRule added in v1.2.0

func RemoveNftablesRule(tableName string, rule FirewallRuleSync) error

RemoveNftablesRule removes a specific rule from nftables

func ReorderIptablesChains added in v1.2.0

func ReorderIptablesChains(chainNames []string) (map[string]interface{}, error)

ReorderIptablesChains reorders iptables INPUT chain jump rules

func ReorderNftablesChains added in v1.2.0

func ReorderNftablesChains(chainNames []string) (map[string]interface{}, error)

ReorderNftablesChains reorders nftables INPUT chain jump rules

func RestoreFirewallRules added in v1.2.0

func RestoreFirewallRules(backup string) error

RestoreFirewallRules restores firewall rules from backup string Automatically detects the firewall type and uses appropriate restore method

func RestoreIptablesBackup added in v1.2.0

func RestoreIptablesBackup(backup string)

RestoreIptablesBackup restores iptables rules from backup Deprecated: Use RestoreFirewallRules instead

func RestoreNftablesBackup added in v1.2.0

func RestoreNftablesBackup(backup string)

RestoreNftablesBackup restores nftables ruleset from backup Deprecated: Use RestoreFirewallRules instead

func ScanBlock

func ScanBlock(data []byte, atEOF bool) (advance int, token []byte, err error)

ScanBlock is a utility function that can be used to scan through text files that chunk using two-lined separators.

Based on a function from the Datadog Agent. Original source: https://github.com/DataDog/datadog-agent License: Apache-2.0 license

func SetFirewallCommandExecutor added in v1.2.0

func SetFirewallCommandExecutor(executor FirewallCommandExecutor)

SetFirewallCommandExecutor sets the command executor function This should be called from the runner package to inject its runCmdWithOutput

Types

type FirewallChainSync added in v1.2.0

type FirewallChainSync struct {
	Name  string             `json:"name"`
	Rules []FirewallRuleSync `json:"rules"`
}

FirewallChainSync represents a firewall chain for sync payload

type FirewallCommandExecutor added in v1.2.0

type FirewallCommandExecutor func(args []string, user string, dir string, env map[string]string, timeout int) (exitCode int, output string)

FirewallCommandExecutor is a function type for executing firewall commands This allows the runner package to inject its runCmdWithOutput function

type FirewallRuleSync added in v1.2.0

type FirewallRuleSync struct {
	Chain           string `json:"chain"`
	Protocol        string `json:"protocol"`
	PortStart       *int   `json:"port_start,omitempty"`
	PortEnd         *int   `json:"port_end,omitempty"`
	SourceCIDR      string `json:"source_cidr"`
	DestinationCIDR string `json:"destination_cidr,omitempty"`
	Target          string `json:"target"`
	Priority        int    `json:"priority"`
	Dports          string `json:"dports,omitempty"`
	ICMPType        *int   `json:"icmp_type,omitempty"`
	RuleID          string `json:"rule_id,omitempty"`
	RuleType        string `json:"rule_type,omitempty"`
}

FirewallRuleSync represents a single firewall rule for sync This matches the alpacon-server FirewallRuleSyncSerializer format

type FirewallSyncPayload added in v1.2.0

type FirewallSyncPayload struct {
	Chains []FirewallChainSync `json:"chains"`
}

FirewallSyncPayload represents the complete firewall sync payload

func CollectFirewallRules added in v1.2.0

func CollectFirewallRules() (*FirewallSyncPayload, error)

CollectFirewallRules collects current firewall rules from the system This is the reverse operation of command.go firewall application logic

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL