utils

package
v2.3.2 Latest Latest
Warning

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

Go to latest
Published: Jul 13, 2026 License: MIT Imports: 29 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

View Source
const AuditOutputCap = 1 << 20 // 1 MiB

AuditOutputCap bounds command output retained for the fin audit payload.

View Source
const DefaultLSColors = `` /* 1405-byte string literal not displayed */

DefaultLSColors is the shared GNU coreutils-style LS_COLORS string used by both the Websh PTY path and the exec/shell path so the two stay in sync.

Variables

View Source
var FirewallFunctionalityDisabled = true

Temporary flag to disable all firewall functionality Set to true to completely disable alpacon firewall management

View Source
var (
	PlatformLike string
)
View Source
var (
	VirtualIfacePattern = regexp.MustCompile(`^(lo|docker|veth|br-|virbr|vmnet|tap|tun|wg|zt|tailscale|enp0s|cni|utun|awdl|llw|bridge|anpi|ap|Loopback|isatap|Teredo|6to4)`)
)

Functions

func ApplyCommandPath added in v2.2.3

func ApplyCommandPath(cmd *exec.Cmd, file, pathEnv string)

ApplyCommandPath pins cmd to the executable resolved against pathEnv. On Unix, a bare command name that is not found in pathEnv is recorded as a lookup failure on cmd.Err rather than being left to fall back to Alpamon's process PATH, so command lookup and execution share the same environment.

func BuildFirewallComment

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 ChownRecursive

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

func ConfigDir

func ConfigDir() string

ConfigDir returns the configuration directory for alpamon.

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 CreateZip

func CreateZip(destPath string, paths []string, recursive bool) error

CreateZip creates a zip archive at destPath containing the specified paths. If recursive is true and a path is a directory, its contents are included recursively.

func DataDir

func DataDir() string

DataDir returns the data directory for alpamon.

func DefaultPath

func DefaultPath() string

DefaultPath returns the default PATH environment variable.

func DefaultShell

func DefaultShell() string

DefaultShell returns the default shell for the platform.

func DefaultShellArgs

func DefaultShellArgs() []string

DefaultShellArgs returns the default shell arguments for interactive login.

func EnsureDirectories

func EnsureDirectories() error

EnsureDirectories creates required alpamon directories with permissions and root:root ownership matching configs/tmpfile.conf. Replaces systemd-tmpfiles when systemd is unavailable.

func EnvironmentFilePath

func EnvironmentFilePath() string

EnvironmentFilePath returns the path to the system environment file.

func FileExists

func FileExists(path string) bool

func FilterVirtualInterface

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

func FormatPermissions

func FormatPermissions(mode os.FileMode) string

func FromWirePath

func FromWirePath(p string) string

FromWirePath converts a wire-format path to a native OS path. It is a no-op on Unix. On Windows, "/C:/Users/foo" → "C:\\Users\\foo". A bare "/C:" is normalized to the drive root "C:\\" since "C:" alone is drive-relative on Windows, not what a breadcrumb click to the drive letter means.

func GenerateServerRuleID

func GenerateServerRuleID() string

GenerateServerRuleID generates a new UUID for server-type firewall rules

func GetCopyPath

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 GetPamVersion

func GetPamVersion() string

GetPamVersion returns the installed alpamon-pam package version. Returns empty string if the package is not installed. Results are cached with a TTL to avoid spawning external processes on every sync.

func GetSystemUser

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

func GetUserAgent

func GetUserAgent(name string) string

func HasSystemd

func HasSystemd() bool

HasSystemd returns true if systemd is available and running as PID 1.

func InitPlatform

func InitPlatform()

func InvalidatePamCache

func InvalidatePamCache()

InvalidatePamCache clears the cached pam version so the next call to GetPamVersion will re-query the system. Call this after upgrading alpamon-pam to avoid reporting a stale version for up to pamCacheTTL.

func IsFirewallDisabled

func IsFirewallDisabled() bool

IsFirewallDisabled checks if firewall functionality is disabled

func IsSuccessStatusCode

func IsSuccessStatusCode(code int) bool

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 LoadEtcEnvironment added in v2.2.3

func LoadEtcEnvironment(env map[string]string)

LoadEtcEnvironment parses /etc/environment and merges system-wide environment variables into the provided map. This supplements the PAM pam_env module, which is not invoked for non-login execution paths such as Websh PTY sessions and demoted exec/shell commands. The path is resolved via EnvironmentFilePath and is empty (a no-op) on platforms without an /etc/environment equivalent.

func LogDir

func LogDir() string

LogDir returns the log directory for alpamon.

func LookPath added in v2.2.3

func LookPath(file, pathEnv string) (string, error)

LookPath searches for an executable named file in the directories listed in pathEnv (a PATH-style, OS-list-separated string). If file already contains a path separator it is returned unchanged. It mirrors exec.LookPath but uses the supplied PATH instead of the current process environment, so command lookup can match the environment handed to a child process.

func LookUpGID

func LookUpGID(groupname string) (int, error)

func LookUpUID

func LookUpUID(username string) (int, error)

func NewHTTPClient

func NewHTTPClient() *http.Client

NewHTTPClient creates an HTTP client with TLS configuration from global settings

func OpenIfZip

func OpenIfZip(path, ext string) *zip.ReadCloser

OpenIfZip returns a zip handle if path is a valid zip and ext is not in the denylist, else nil. Caller must Close. Reusing this handle for extraction closes the TOCTOU window.

func ParseCommentOrGenerate

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

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 io.Reader, contentLength int64, timeout time.Duration) ([]byte, int, error)

Put issues a PUT request. Pass contentLength=-1 to force chunked transfer.

codeql[go/request-forgery]: Intentional - HTTP client for admin-specified URLs

func Quote

func Quote(s string) string

func RunDir

func RunDir() string

RunDir returns the runtime directory for alpamon. When running as root (production), uses the system directory (e.g., /run/alpamon, /var/run/alpamon). When running as a regular user (development), uses /tmp/alpamon to avoid permission issues.

func SanitizePath

func SanitizePath(path string) (string, error)

SanitizePath validates and cleans a file path to prevent path traversal and other unsafe shapes. Returns the cleaned absolute native path.

Rejected inputs:

  • paths containing a null byte (would truncate at the OS boundary and bypass logging that captures the full string)
  • paths whose cleaned form retains a literal ".." (post-Clean traversal)
  • paths whose cleaned form starts with `\\` (Windows UNC, local device, and extended-length namespaces: `\\server\share`, `\\.\PHYSICALDRIVE0`, `\\?\...`, `\\?\UNC\...`). These have no legitimate WebFTP use; an attacker who can supply wire input could otherwise make alpamon (running as SYSTEM on Windows) authenticate to a hostile SMB server or open raw devices. The prefix has no legitimate meaning on Unix either, so the check is universal — no platform branch needed.

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 SetPlatformLike

func SetPlatformLike(platform string)

SetPlatformLike allows setting PlatformLike for testing purposes.

func ToWirePath

func ToWirePath(p string) string

ToWirePath converts a native OS path to the wire format. It is a no-op on Unix. On Windows, "C:\\Users\\foo" → "/C:/Users/foo".

func TruncateMiddle added in v2.3.1

func TruncateMiddle(s string, max int) string

TruncateMiddle keeps s's first and last halves within max bytes, replacing the dropped middle with a marker. It returns s unchanged when already within max.

func Unzip

func Unzip(src, destDir string) error

Unzip extracts a zip archive to the specified destination directory. It validates that extracted paths stay within the destination (zip slip protection).

func UnzipReader

func UnzipReader(r *zip.ReadCloser, destDir string) error

UnzipReader extracts an already-opened zip into destDir. Caller owns r. Used when the caller has pre-validated the same handle to close TOCTOU windows.

Types

type DefaultVersionResolver

type DefaultVersionResolver struct{}

DefaultVersionResolver implements common.VersionResolver using real GitHub API calls and system package queries.

func NewDefaultVersionResolver

func NewDefaultVersionResolver() *DefaultVersionResolver

func (*DefaultVersionResolver) GetLatestVersion

func (r *DefaultVersionResolver) GetLatestVersion() string

func (*DefaultVersionResolver) GetPamVersion

func (r *DefaultVersionResolver) GetPamVersion() string

func (*DefaultVersionResolver) InvalidatePamCache

func (r *DefaultVersionResolver) InvalidatePamCache()

type DemoteOptions

type DemoteOptions struct {
	// ValidateGroup checks if the specified group is in the user's group list
	ValidateGroup bool
}

DemoteOptions configures the behavior of privilege demotion

type DemoteResult

type DemoteResult struct {
	// SysProcAttr contains the credentials for privilege demotion
	SysProcAttr *syscall.SysProcAttr
	// User contains the looked up user information
	User *user.User
}

DemoteResult contains the result of privilege demotion

func Demote

func Demote(username, groupname string, opts DemoteOptions) (*DemoteResult, error)

Demote creates syscall attributes for privilege demotion to the specified user/group. If username or groupname is empty, or if not running as root, returns nil without error. When ValidateGroup is true, returns an error if the group is not in the user's group list.

type FirewallChainSync

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

FirewallChainSync represents a firewall chain for sync payload

type FirewallRuleSync

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

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

FirewallSyncPayload represents the complete firewall sync payload

func BuildSyncPayload

func BuildSyncPayload(chains map[string][]FirewallRuleSync) *FirewallSyncPayload

BuildSyncPayload creates sync payload from parsed rules

Jump to

Keyboard shortcuts

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