Documentation
¶
Index ¶
- Constants
- Variables
- func ApplyCommandPath(cmd *exec.Cmd, file, pathEnv string)
- func BuildFirewallComment(existingComment, ruleID, ruleType string) string
- func CalculateDiskIOBps(current disk.IOCountersStat, last disk.IOCountersStat, interval time.Duration) (readBps float64, writeBps float64)
- func CalculateNetworkBps(current net.IOCountersStat, last net.IOCountersStat, interval time.Duration) (inputBps float64, outputBps float64)
- func CalculateNetworkPps(current net.IOCountersStat, last net.IOCountersStat, interval time.Duration) (inputPps float64, outputPps float64)
- func ChownRecursive(path string, uid, gid int) error
- func ConfigDir() string
- func ConvertGroupIds(groupIds []string) []uint32
- func CopyDir(src, dst string, allowOverwrite bool) error
- func CopyFile(src, dst string, allowOverwrite bool) error
- func CreateZip(destPath string, paths []string, recursive bool) error
- func DataDir() string
- func DefaultPath() string
- func DefaultShell() string
- func DefaultShellArgs() []string
- func EnsureDirectories() error
- func EnvironmentFilePath() string
- func FileExists(path string) bool
- func FilterVirtualInterface(ifaces net.InterfaceStatList) map[string]net.InterfaceStat
- func FormatPermissions(mode os.FileMode) string
- func FromWirePath(p string) string
- func GenerateServerRuleID() string
- func GetCopyPath(src, dst string) string
- func GetDiskBaseName(name string) string
- func GetEnvOrDefault(envVar, defaultValue string) string
- func GetFileInfo(info os.FileInfo, path string) (permString, permOctal, owner, group string, err error)
- func GetLatestVersion() string
- func GetPamVersion() string
- func GetSystemUser(username string) (*user.User, error)
- func GetUserAgent(name string) string
- func HasSystemd() bool
- func InitPlatform()
- func InvalidatePamCache()
- func IsFirewallDisabled() bool
- func IsSuccessStatusCode(code int) bool
- func IsVirtualDisk(name string) bool
- func IsVirtualFileSystem(device string, fstype string, mountPoint string) bool
- func JoinPath(base string, paths ...string) string
- func LoadEtcEnvironment(env map[string]string)
- func LogDir() string
- func LookPath(file, pathEnv string) (string, error)
- func LookUpGID(groupname string) (int, error)
- func LookUpUID(username string) (int, error)
- func NewHTTPClient() *http.Client
- func OpenIfZip(path, ext string) *zip.ReadCloser
- func ParseCommentOrGenerate(comment string) (ruleID, ruleType string)
- func ParseDiskName(device string) string
- func ParseFirewallComment(comment string) (ruleID, ruleType, existingComment string)
- func Put(url string, body io.Reader, contentLength int64, timeout time.Duration) ([]byte, int, error)
- func Quote(s string) string
- func RunDir() string
- func SanitizePath(path string) (string, error)
- func ScanBlock(data []byte, atEOF bool) (advance int, token []byte, err error)
- func SetPlatformLike(platform string)
- func ToWirePath(p string) string
- func TruncateMiddle(s string, max int) string
- func Unzip(src, destDir string) error
- func UnzipReader(r *zip.ReadCloser, destDir string) error
- type DefaultVersionResolver
- type DemoteOptions
- type DemoteResult
- type FirewallChainSync
- type FirewallRuleSync
- type FirewallSyncPayload
Constants ¶
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
const AuditOutputCap = 1 << 20 // 1 MiB
AuditOutputCap bounds command output retained for the fin audit payload.
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 ¶
var FirewallFunctionalityDisabled = true
Temporary flag to disable all firewall functionality Set to true to completely disable alpacon firewall management
var (
PlatformLike string
)
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
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 ¶
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 ConvertGroupIds ¶
func CreateZip ¶
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 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 FilterVirtualInterface ¶
func FilterVirtualInterface(ifaces net.InterfaceStatList) map[string]net.InterfaceStat
func FormatPermissions ¶
func FromWirePath ¶
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 GetDiskBaseName ¶
func GetEnvOrDefault ¶
func GetFileInfo ¶
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 GetUserAgent ¶
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 IsVirtualDisk ¶
func IsVirtualFileSystem ¶
func LoadEtcEnvironment ¶ added in v2.2.3
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 LookPath ¶ added in v2.2.3
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 NewHTTPClient ¶
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 ¶
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 ParseFirewallComment ¶
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 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 ¶
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 ¶
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 ¶
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
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 ¶
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