Compare commits

3 Commits

Author SHA1 Message Date
wmantly 6500fadafb Merge pull request #1 from theta42/fix/install-sssd-auto-v1.2.1
feat(install): add automatic SSSD and PAM package installation v1.2.1
2026-08-03 15:02:08 -04:00
wmantly 6348c4c060 feat(install): add automatic SSSD and PAM package installation v1.2.1 2026-08-03 15:01:57 -04:00
wmantly 821ce5f991 release: v1.2.0 - Pure Go update engine, enhanced journal log fetcher, and protocol concurrency fixes 2026-08-03 02:13:11 -04:00
6 changed files with 218 additions and 48 deletions
+25
View File
@@ -0,0 +1,25 @@
# Changelog
All notable changes to the `theta-agent` daemon will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [v1.2.0] - 2026-08-03
### Added
- **Protocol v1.1.0 Compliance**: Full alignment with `PROTOCOL.md` (v1.1.0) specification.
- **Ed25519 Cryptographic Verification**: Verification of Ed25519 Base64 signatures for high-risk C2 commands (`reboot`, `service_restart`, `configure_ldap`, `arbitrary_bash`, `update_binary`).
- **Enhanced Journal Log Fetcher (`fetch_logs`)**: Support for querying service-specific systemd logs (`service` parameter) with configurable line count (`lines` parameter).
- **Pure Go Self-Update Engine (`update_binary`)**: Replaced shell script execution with pure Go HTTP client fetching, SHA256 verification, atomic file replacement, and clean daemon restart.
### Fixed
- **Goroutine Leak Prevention**: Added `stopCh` lifecycle management to terminate background telemetry and heartbeat tickers upon WebSocket disconnection.
- **Dynamic Config Rerenders**: Resolved data races when toggling capabilities or reloading `agent.yml` via `reload_config`.
- **Config Path Uniformity**: Standardized canonical configuration file path across codebase, installer, and documentation to `/etc/theta42/agent.yml`.
## [v0.1.0] - 2026-08-01
### Added
- Initial release of `theta-agent` Go daemon replacing legacy bash metric scripts.
- Persistent outbound WebSocket telemetry and local capability matrix enforcement.
+35 -1
View File
@@ -23,10 +23,35 @@ if [ "$EUID" -ne 0 ]; then
error "This script must be run as root." error "This script must be run as root."
fi fi
# Install SSSD and PAM integration packages if missing
install_sssd_deps() {
if ! command -v sssd >/dev/null 2>&1; then
log "Installing SSSD and PAM integration dependencies..."
if command -v apt-get >/dev/null 2>&1; then
DEBIAN_FRONTEND=noninteractive apt-get update -qq || true
DEBIAN_FRONTEND=noninteractive apt-get install -y -qq sssd sssd-ldap libnss-sss libpam-sss libsss-sudo pam-auth-update || true
if command -v pam-auth-update >/dev/null 2>&1; then
pam-auth-update --enable mkhomedir || true
fi
elif command -v dnf >/dev/null 2>&1; then
dnf install -y sssd sssd-ldap sssd-tools || true
elif command -v yum >/dev/null 2>&1; then
yum install -y sssd sssd-ldap sssd-tools || true
elif command -v pacman >/dev/null 2>&1; then
pacman -S --noconfirm sssd || true
elif command -v zypper >/dev/null 2>&1; then
zypper in -y sssd || true
fi
else
log "SSSD is already installed."
fi
}
# 2. Argument Parsing # 2. Argument Parsing
URL="" URL=""
TOKEN="" TOKEN=""
B64_CONFIG="" B64_CONFIG=""
INSTALL_SSSD=0
while [[ $# -gt 0 ]]; do while [[ $# -gt 0 ]]; do
case $1 in case $1 in
@@ -38,6 +63,10 @@ while [[ $# -gt 0 ]]; do
TOKEN="$2" TOKEN="$2"
shift 2 shift 2
;; ;;
--install-sssd|--ldap)
INSTALL_SSSD=1
shift
;;
*) *)
B64_CONFIG="$1" B64_CONFIG="$1"
shift shift
@@ -50,7 +79,7 @@ if [ -z "$B64_CONFIG" ] && [ -z "$URL" ] || [ -z "$B64_CONFIG" ] && [ -z "$TOKEN
error "Missing required configuration. Either provide a base64 encoded config, or both --url and --token." error "Missing required configuration. Either provide a base64 encoded config, or both --url and --token."
echo "Usage examples:" echo "Usage examples:"
echo " sh install.sh \"BASE64_CONFIG\"" echo " sh install.sh \"BASE64_CONFIG\""
echo " sh install.sh --url \"https://sso.local\" --token \"secret-token\"" echo " sh install.sh --url \"https://sso.local\" --token \"secret-token\" --install-sssd"
exit 1 exit 1
fi fi
@@ -86,6 +115,11 @@ EOF
fi fi
chmod 600 "$CONFIG_FILE" chmod 600 "$CONFIG_FILE"
# 4b. Ensure SSSD dependencies are installed if configure_ldap is enabled
if [ "$INSTALL_SSSD" -eq 1 ] || grep -q -i "configure_ldap:\s*true" "$CONFIG_FILE" 2>/dev/null; then
install_sssd_deps
fi
# 5. Setup systemd service # 5. Setup systemd service
log "Creating systemd service unit..." log "Creating systemd service unit..."
cat <<EOF > "$SERVICE_FILE" cat <<EOF > "$SERVICE_FILE"
+44 -25
View File
@@ -114,38 +114,57 @@ func collectGPUUsage(exec Executor) float64 {
} }
// StartTelemetryLoop manages the initial discovery push and the periodic telemetry stream. // StartTelemetryLoop manages the initial discovery push and the periodic telemetry stream.
func StartTelemetryLoop(c *websocket.Conn, cfg *Config, exec Executor) { func StartTelemetryLoop(c MessageWriter, cm *ConfigManager, exec Executor, stopCh <-chan struct{}) {
cfg := cm.Get()
// 1. Immediate Discovery Push // 1. Immediate Discovery Push
pushDiscovery(c, cfg) pushDiscovery(c, cfg)
// If telemetry capability is disabled in agent.yml, return early after discovery
if !cfg.Capabilities.Telemetry {
log.Println("Telemetry capability is disabled in agent.yml; skipping telemetry stream.")
return
}
// 2. Periodic Telemetry Stream // 2. Periodic Telemetry Stream
ticker := time.NewTicker(30 * time.Second) ticker := time.NewTicker(30 * time.Second)
go func() { go func() {
defer ticker.Stop()
var lastIPs []string var lastIPs []string
for range ticker.C { for {
// Network Change Detection select {
currentIPs := collectIPs() case <-stopCh:
if !equalSlices(lastIPs, currentIPs) {
log.Println("Network change detected. Pushing discovery update...")
pushDiscovery(c, cfg)
lastIPs = currentIPs
}
telemetry := CollectTelemetryData(exec)
payload, _ := json.Marshal(WSMessage{
Type: "telemetry",
Payload: map[string]interface{}{
"cpu_usage_percent": telemetry.CPUUsagePercent,
"ram_usage_percent": telemetry.RAMUsagePercent,
"disk_usage_percent": telemetry.DiskUsagePercent,
"zfs_health": telemetry.ZFSHealth,
"gpu_usage_percent": telemetry.GPUUsage,
"timestamp": telemetry.Timestamp,
},
})
if err := c.WriteMessage(websocket.TextMessage, payload); err != nil {
log.Printf("Failed to stream telemetry: %v", err)
return return
case <-ticker.C:
currentCFG := cm.Get()
if !currentCFG.Capabilities.Telemetry {
continue
}
// Network Change Detection
currentIPs := collectIPs()
if !equalSlices(lastIPs, currentIPs) {
log.Println("Network change detected. Pushing discovery update...")
pushDiscovery(c, currentCFG)
lastIPs = currentIPs
}
telemetry := CollectTelemetryData(exec)
payload, _ := json.Marshal(WSMessage{
Type: "telemetry",
Payload: map[string]interface{}{
"cpu_usage_percent": telemetry.CPUUsagePercent,
"ram_usage_percent": telemetry.RAMUsagePercent,
"disk_usage_percent": telemetry.DiskUsagePercent,
"zfs_health": telemetry.ZFSHealth,
"gpu_usage_percent": telemetry.GPUUsage,
"timestamp": telemetry.Timestamp,
},
})
if err := c.WriteMessage(websocket.TextMessage, payload); err != nil {
log.Printf("Failed to stream telemetry: %v", err)
return
}
} }
} }
}() }()
@@ -176,7 +195,7 @@ func equalSlices(a, b []string) bool {
return true return true
} }
func pushDiscovery(c *websocket.Conn, cfg *Config) { func pushDiscovery(c MessageWriter, cfg *Config) {
discovery := CollectDiscoveryData(cfg) discovery := CollectDiscoveryData(cfg)
discoveryPayload, _ := json.Marshal(discovery) discoveryPayload, _ := json.Marshal(discovery)
Binary file not shown.
+103 -21
View File
@@ -2,11 +2,16 @@ package main
import ( import (
"crypto/ed25519" "crypto/ed25519"
"crypto/sha256"
"encoding/base64" "encoding/base64"
"encoding/json" "encoding/json"
"fmt" "fmt"
"io"
"log" "log"
"net/http"
"net/url" "net/url"
"os"
"path/filepath"
"strings" "strings"
"time" "time"
@@ -83,17 +88,25 @@ func connectWebSocket(cm *ConfigManager, exec Executor) {
log.Println("Successfully connected to SSO Manager.") log.Println("Successfully connected to SSO Manager.")
// Start telemetry and discovery stopCh := make(chan struct{})
StartTelemetryLoop(c, cfg, exec)
// Start telemetry and discovery with stopCh lifecycle control
StartTelemetryLoop(c, cm, exec, stopCh)
// Heartbeat loop // Heartbeat loop
go func() { go func() {
ticker := time.NewTicker(60 * time.Second) ticker := time.NewTicker(60 * time.Second)
for range ticker.C { defer ticker.Stop()
hb := WSMessage{Type: "heartbeat", Payload: map[string]interface{}{"timestamp": time.Now().Format(time.RFC3339)}} for {
payload, _ := json.Marshal(hb) select {
if err := c.WriteMessage(websocket.TextMessage, payload); err != nil { case <-stopCh:
return return
case <-ticker.C:
hb := WSMessage{Type: "heartbeat", Payload: map[string]interface{}{"timestamp": time.Now().Format(time.RFC3339)}}
payload, _ := json.Marshal(hb)
if err := c.WriteMessage(websocket.TextMessage, payload); err != nil {
return
}
} }
} }
}() }()
@@ -116,6 +129,7 @@ func connectWebSocket(cm *ConfigManager, exec Executor) {
} }
// Cleanup on disconnect // Cleanup on disconnect
close(stopCh)
c.Close() c.Close()
log.Println("WebSocket disconnected. Reconnecting in 5 seconds...") log.Println("WebSocket disconnected. Reconnecting in 5 seconds...")
@@ -142,15 +156,33 @@ func handleCommand(cm *ConfigManager, msg WSMessage, c MessageWriter, exec Execu
sendResponse("ok", "configuration reloaded") sendResponse("ok", "configuration reloaded")
} }
case "fetch_logs": case "fetch_logs":
out, err := exec.Execute("journalctl", "-u", "theta-agent", "-n", "100") serviceName, _ := msg.Payload["service"].(string)
if serviceName == "" {
serviceName = "theta-agent"
}
if serviceName != "theta-agent" && !cfg.Capabilities.CanManageService(serviceName) {
log.Printf("Fetch logs rejected for '%s': not in allowed service list", serviceName)
sendResponse("error", "service log fetch rejected")
return
}
linesCount := 100
if l, ok := msg.Payload["lines"].(float64); ok && l > 0 {
linesCount = int(l)
}
log.Printf("Fetching logs for service %s (%d lines)...", serviceName, linesCount)
out, err := exec.Execute("journalctl", "-u", serviceName, "-n", fmt.Sprintf("%d", linesCount), "--no-pager")
if err != nil { if err != nil {
log.Printf("Log fetch failed: %v", err) log.Printf("Log fetch failed: %v", err)
sendResponse("error", "failed to fetch logs") sendResponse("error", "failed to fetch logs")
return return
} }
resp := map[string]string{ resp := map[string]interface{}{
"status": "ok", "status": "ok",
"logs": string(out), "service": serviceName,
"logs": string(out),
} }
respPayload, _ := json.Marshal(resp) respPayload, _ := json.Marshal(resp)
c.WriteMessage(websocket.TextMessage, respPayload) c.WriteMessage(websocket.TextMessage, respPayload)
@@ -160,28 +192,25 @@ func handleCommand(cm *ConfigManager, msg WSMessage, c MessageWriter, exec Execu
sendResponse("error", "signature verification failed") sendResponse("error", "signature verification failed")
return return
} }
if !cfg.Capabilities.ArbitraryBash { // Use Bash as a proxy for "dangerous update" capability if !cfg.Capabilities.ArbitraryBash {
sendResponse("error", "update capability disabled") sendResponse("error", "update capability disabled")
return return
} }
url, _ := msg.Payload["url"].(string) urlStr, _ := msg.Payload["url"].(string)
checksum, _ := msg.Payload["sha256"].(string) checksum, _ := msg.Payload["sha256"].(string)
if url == "" || checksum == "" { if urlStr == "" || checksum == "" {
sendResponse("error", "missing url or checksum") sendResponse("error", "missing url or sha256 checksum")
return return
} }
log.Printf("Updating binary from %s...", url) log.Printf("Updating binary from %s...", urlStr)
// implementation of download and replace if err := downloadAndUpdateBinary(urlStr, checksum); err != nil {
// ... (simplified for now, using a shell command via executor for brevity in this turn)
script := fmt.Sprintf("curl -fsSL %s -o /tmp/theta-agent.new && sha256sum -c <(echo '%s /tmp/theta-agent.new') && mv /tmp/theta-agent.new $(readlink -f /proc/self/exe)", url, checksum)
if _, err := exec.Execute("bash", "-c", script); err != nil {
log.Printf("Update failed: %v", err) log.Printf("Update failed: %v", err)
sendResponse("error", "update failed") sendResponse("error", fmt.Sprintf("update failed: %v", err))
return return
} }
sendResponse("ok", "update applied. restarting agent...") sendResponse("ok", "update applied successfully; restarting agent...")
os.Exit(0) os.Exit(0)
case "config": case "config":
log.Printf("Received config payload: %v", msg.Payload) log.Printf("Received config payload: %v", msg.Payload)
@@ -287,3 +316,56 @@ func handleCommand(cm *ConfigManager, msg WSMessage, c MessageWriter, exec Execu
sendResponse("error", "unknown command type") sendResponse("error", "unknown command type")
} }
} }
func downloadAndUpdateBinary(downloadURL string, expectedSHA256 string) error {
resp, err := http.Get(downloadURL)
if err != nil {
return fmt.Errorf("http fetch failed: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("unexpected http status: %s", resp.Status)
}
tmpFile, err := os.CreateTemp("", "theta-agent-update-*")
if err != nil {
return fmt.Errorf("failed to create temp file: %w", err)
}
tmpPath := tmpFile.Name()
defer os.Remove(tmpPath)
hasher := sha256.New()
writer := io.MultiWriter(tmpFile, hasher)
if _, err := io.Copy(writer, resp.Body); err != nil {
tmpFile.Close()
return fmt.Errorf("failed to save binary: %w", err)
}
tmpFile.Close()
actualSHA256 := fmt.Sprintf("%x", hasher.Sum(nil))
if !strings.EqualFold(actualSHA256, strings.TrimSpace(expectedSHA256)) {
return fmt.Errorf("sha256 mismatch: expected %s, got %s", expectedSHA256, actualSHA256)
}
if err := os.Chmod(tmpPath, 0755); err != nil {
return fmt.Errorf("failed to set executable permissions: %w", err)
}
selfPath, err := os.Executable()
if err != nil {
return fmt.Errorf("failed to resolve current binary path: %w", err)
}
resolvedPath, err := filepath.EvalSymlinks(selfPath)
if err == nil {
selfPath = resolvedPath
}
if err := os.Rename(tmpPath, selfPath); err != nil {
return fmt.Errorf("failed to replace binary: %w", err)
}
return nil
}
+11 -1
View File
@@ -33,6 +33,15 @@ func (m *MockExecutor) WriteFile(path string, data []byte, perm os.FileMode) err
return nil return nil
} }
func (m *MockExecutor) ReadFile(path string) ([]byte, error) {
if m.WrittenFiles != nil {
if data, ok := m.WrittenFiles[path]; ok {
return data, nil
}
}
return []byte("mock file content"), nil
}
func TestHandleCommand(t *testing.T) { func TestHandleCommand(t *testing.T) {
tests := []struct { tests := []struct {
name string name string
@@ -182,7 +191,8 @@ func TestHandleCommand(t *testing.T) {
t.Run(tc.name, func(t *testing.T) { t.Run(tc.name, func(t *testing.T) {
mockConn := &MockConn{} mockConn := &MockConn{}
mockExec := &MockExecutor{} mockExec := &MockExecutor{}
handleCommand(tc.cfg, tc.msg, mockConn, mockExec) cm := &ConfigManager{current: tc.cfg}
handleCommand(cm, tc.msg, mockConn, mockExec)
if len(mockConn.Messages) != 1 { if len(mockConn.Messages) != 1 {
t.Fatalf("expected 1 response message, got %d", len(mockConn.Messages)) t.Fatalf("expected 1 response message, got %d", len(mockConn.Messages))