Build constraints, x/sys, and a thread-locked goroutine: how a-better-antivirus plants decoy files that catch infostealers, and what the pattern costs.
· 9 min read

Cross-Platform File Tripwires in Go: Inside a-better-antivirus


“Plant a convincing fake password file and notice when something reads it” sounds like one feature. It isn’t. On Windows it’s an audit entry in a security descriptor. On Linux it’s a fanotify mark owned by the process holding the fanotify descriptor. On macOS the service matches eslogger events against its in-memory bait list. Three kernels, three mechanisms, nothing in common.

The internal/baits package in a-better-antivirus at the revision reviewed for this post papers over that with build constraints and nothing else. blend_windows.go, blend_linux.go, and blend_darwin.go declare the same function names: SetTripwire, HasTripwire, ClearTripwire, setTimes, getTimes, ownedBy, indexedLikeFolder, controller, asOwner. No interface, no registry, no plugin table. The toolchain picks one file per build and the rest of the package never learns which.

What the tool actually does

The package doc on cmd/aba/main.go still describes the Windows path: the aba command plants decoy files and fake app data, watches them with Windows file auditing, and freezes and cuts off anything suspicious that reads them. The Linux and macOS implementations pursue the same honeytoken strategy with different event sources. The bet is simple. A legitimate program has no reason to read a browser profile it didn’t create, so an unexpected reader deserves scrutiny.

main is two lines:

var version = "dev" // set by the release build: -ldflags "-X main.version=v0.1.0"

func main() {
	cli.Version = version
	os.Exit(cli.Execute())
}

Execute returns an exit code and main hands it to os.Exit. That ordering matters more than it looks: os.Exit skips deferred functions, so all the real work has to happen inside cli.Execute, where defers still run. If you’re building the command layer this sits on, the Cobra CLI post covers it.

Three tripwires behind one function name

SetTripwire(path string) error means something different in each file.

On Windows it’s a one-liner: return winsec.SetBaitAudit(path). The comment above it explains the mechanism. The tripwire is an audit rule on the file, and reads land in the Security event log. HasTripwire and ClearTripwire forward to winsec.HasBaitAudit and winsec.ClearAudit. Because the rule lives in the file’s security descriptor, it can be read back and it can be stripped, which is why the alerts package carries a KindAuditRemoved alert for a bait whose audit rule disappeared.

On Linux nothing touches the file at all. Per the comment, the service asks the kernel to report every open of that file via fanotify, and the kernel keeps that mark with the file itself whatever name it’s reached by. SetTripwire checks the path is a regular file with os.Lstat and fi.Mode().IsRegular(), then delegates.

On macOS the tripwire is thinner still. The comment says eslogger reports every open, so a bait is watched purely by being in the list the service watches. SetTripwire validates the file is ordinary and stops there. HasTripwire returns true, nil, unconditionally.

One signature, three unrelated kernel features, zero runtime dispatch.

Package-level function variables as injection points

Linux has a constraint the other two don’t: only the process holding the fanotify descriptor can set or query marks, and that’s the background service, not the CLI invocation you typed. The fix is two exported function variables.

var (
	// Watch marks a bait file; Watched reports whether the file at path is
	// marked. Set by the service.
	Watch   func(path string) error
	Watched func(path string) bool
)

SetTripwire calls Watch(path) when it isn’t nil and returns nil otherwise. HasTripwire returns Watched(path) when set, true otherwise. The comment is explicit that in the CLI these have nothing to do, because the service marks every bait when it’s told the baits changed.

I’d call this a defensible trade rather than a clean one. An interface is the textbook answer, but it would have to be carried through callers to represent a detail that exists on one platform out of three. Package-level function variables keep the API identical across builds and let the service plug its watcher in during startup. What you pay for that convenience is mutable global state with no synchronisation if it is changed later. The code relies on assigning the hooks during service preparation, before the watcher starts serving events, and the nil checks preserve the CLI path where no hooks are installed.

Making a planted file look lived-in with x/sys

Here’s the attack on the defence: a stealer can read a file’s properties from a folder listing without opening it, and so without tripping anything. A bait that looks new is a bait that gets skipped.

The comment block in internal/baits/apply.go enumerates what a freshly written file is missing. An age, because nothing a browser wrote was created this minute. Three distinct timestamps, since created, modified, and last opened are never the same instant on a file that’s been used. A folder older than its contents. And you as the owner: files written by an installer running as administrator belong to Administrators, which nothing on a real Desktop does. The list also notes an indexing mistake the project made earlier, marking baits “don’t index,” which made them the only such files in Documents.

Timestamps are where the platforms split hardest, and all three lean on golang.org/x/sys.

Windows opens a handle purely to write metadata:

h, err := windows.CreateFile(p, windows.FILE_WRITE_ATTRIBUTES,
	windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE|windows.FILE_SHARE_DELETE,
	nil, windows.OPEN_EXISTING, windows.FILE_FLAG_BACKUP_SEMANTICS, 0)
if err != nil {
	return
}
defer windows.CloseHandle(h)
windows.SetFileTime(h, fileTime(created), fileTime(accessed), fileTime(written))

FILE_WRITE_ATTRIBUTES is the access right SetFileTime needs and little more, and FILE_FLAG_BACKUP_SEMANTICS is what lets the same call open a directory handle, which the folder-aging pass depends on. Notice the defer windows.CloseHandle(h) sits after the error check, so the code only schedules cleanup for a handle it successfully opened (more on defer here).

Linux has no portable call here for setting birth time, so setTimes only moves access and modification times via unix.UtimesNanoAt with AT_SYMLINK_NOFOLLOW. Reading them back, getTimes asks unix.Statx for STATX_BTIME and checks sx.Mask&unix.STATX_BTIME != 0 before trusting the field. If birth time is unavailable it falls back to ctime from unix.Lstat; that is a metadata-change time, not a true creation time, and changing the timestamps can itself advance it. The mask check matters because statx may return fewer fields than requested.

macOS has no creation-time setter in this code either. The implementation relies on observed filesystem behaviour described in its comment: first set modification time earlier than creation time so macOS moves creation time back, then set the intended modification time. That is two UtimesNanoAt calls rather than a direct birth-time update.

Dropping privileges onto one OS thread

baits.Create can run as administrator while writing into folders that belong to the user. On Unix-like systems, an unprivileged process could try to swap part of that path for a symlink and redirect a privileged write.

Both the Linux and macOS builds answer that with asOwner(path string, fn func()) error. controller(path) walks from / down and returns the uid and gid of the first component that isn’t root’s. If that uid is zero, or the process isn’t running as root, fn just runs.

Otherwise the code changes credentials for one OS thread, so the goroutine performing the file operation must stay on that thread. Linux locks the calling goroutine and temporarily sets supplementary groups, filesystem gid and filesystem uid. macOS starts a dedicated goroutine, locks it, and uses the thread-credential syscall behind pthread_setugid_np. In both builds, successful restoration is followed by runtime.UnlockOSThread; if restoration fails, the code deliberately leaves the goroutine locked so the runtime retires that thread instead of reusing its altered credentials. The macOS shape is roughly:

// Illustrative: the lifecycle, not project code.
func asOwnerOnDedicatedThread(fn func()) error {
	errc := make(chan error, 1)
	go func() {
		runtime.LockOSThread()
		if err := setThreadCredentials(); err != nil {
			runtime.UnlockOSThread()
			errc <- err
			return
		}
		fn()
		if restoreThreadCredentials() {
			runtime.UnlockOSThread()
		}
		// If restoration failed, exit while still locked so the runtime
		// discards this OS thread.
		errc <- nil
	}()
	return <-errc
}

The comment on Create says Create, Repair, Blend, and Remove all go through asOwner. Create does it by wrapping the entire create call:

if e := asOwner(files[0].Path, func() { bs, err = create(s, u, g) }); e != nil {
	return &config.BaitState{ID: s.ID, Name: s.Name, Kind: s.Kind,
		Status: "error", CreatedAt: time.Now()}, e
}

The named returns on Create, (bs *config.BaitState, err error), earn their keep here. The closure assigns straight into them, no result struct and no extra channel.

Bookkeeping so uninstall doesn’t eat your folders

One small function in apply.go is worth lifting wholesale. topMissingDir walks up from a directory and returns the highest ancestor that doesn’t exist yet:

func topMissingDir(dir string) string {
	top := ""
	for d := dir; ; d = filepath.Dir(d) {
		if _, err := os.Stat(d); err == nil {
			return top
		}
		top = d
		if filepath.Dir(d) == d {
			return top
		}
	}
}

filepath.Dir(d) == d is the root-reached condition, and it’s the bit people get wrong and spin forever on. create records the result in bs.CreatedDirs before os.MkdirAll runs, so later removal knows which directory tree it created and which ones were already yours. Uninstall deleting ~/Documents is the kind of bug that ends a project.

create is equally careful with files. If os.ReadFile(f.Path) succeeds, the existing file is adopted rather than overwritten, on the grounds that the user may have customised it. legacyMarkers holds a single string left behind by the original PowerShell honeypot script, and a match sets bf.Created = true so those older baits get cleaned up too. Only files create wrote itself get that flag. That one boolean is what makes removal safe.

Alerts as plain JSON structs

internal/alerts stores detections as JSON files in the data dir. Alert is a flat record with omitempty on nearly every optional field, and the kinds are string constants: read, delete, bait-missing, audit-removed, audit-disabled, decoy-retired, tamper, test, and clipper for a program that swaps the wallet address ABA put on the clipboard.

IDs are built to group by time:

func NewID(t time.Time) string {
	b := make([]byte, 2)
	rand.Read(b)
	return t.Format("20060102-150405") + "-" + hex.EncodeToString(b)
}

A timestamp in 20060102-150405 layout plus two random bytes from crypto/rand. Lexical order groups alerts by second, which is useful when the IDs become filenames in a directory; the random suffix does not preserve order within the same second. (If that layout string looks like magic numbers, the Go time package guide explains the reference-time scheme.) Two bytes gives 65,536 suffixes per one-second bucket, so uniqueness is probabilistic rather than guaranteed. That is a pragmatic local identifier, not a fleet-wide ID scheme.

Reading back what happened is just as small:

func (a *Alert) Did(act config.Action) bool {
	for _, r := range a.Actions {
		if r.Action == act && r.OK {
			return true
		}
	}
	return false
}

AddAction(act, err, detail) builds an ActionResult with OK: err == nil and folds the error text into Detail when there is one. Failed attempts are recorded the same way successful ones are. For a security tool that’s the right call: a freeze that didn’t work is the thing you most want in the file, and a schema that only logs successes quietly tells you the system did nothing.

The build-constraint trick is the part I’d steal first. It costs one file per platform and buys you a package where the platform question never appears in a call site. The function-var injection on Linux is the part I’d steal nervously, and only with the same comments attached.