fix(winapi): look in install paths before App Paths (#657)

CocCoc and Yandex both ship browser.exe and App Paths names only one, so ABE asked Yandex's program
for CocCoc's key and CocCoc's v20 cookies came out empty. A browser's own install locations now come
first, then App Paths, then a running process.
This commit is contained in:
Roger authored and GitHub committed 2026-10-27 17:58:27 +08:00
1 parent 2b70e4ad65
commit 9d51aa869e
6 files changed
+112 -22

No files matched your search

+23 -19
View File
@@ -17,30 +17,24 @@ import (
// located via registry App Paths or any install-location fallback.
var ErrExecutableNotFound = errors.New("browser executable not found")
// ExecutablePath resolves a browser's .exe with a 4-tier search:
// 1. Registry App Paths in HKLM
// 2. Registry App Paths in HKCU
// ExecutablePath resolves a browser's .exe, its own install locations first: an executable name such as browser.exe is
// shared by more than one vendor, so App Paths or a running process may name another vendor's program.
// 1. Hard-coded install fallbacks — the vendor's own directories.
// 2. Registry App Paths in HKLM, then HKCU — installs elsewhere.
// 3. Running-process probe — scan EnumProcesses for a match by exe name
// and return the owner's QueryFullProcessImageName. Picks up portable
// builds and non-standard installs that never wrote to App Paths.
// 4. Hard-coded install fallbacks (last resort when the browser
// is not running and the registry is missing the entry).
func ExecutablePath(exeName string, fallbacks []string) (string, error) {
return executablePath(exeName, fallbacks, appPathsLookup, runningProcessPath)
}
func executablePath(exeName string, fallbacks []string, appPaths func(string, registry.Key) (string, error),
running func(string) string,
) (string, error) {
if exeName == "" {
return "", fmt.Errorf("%w: no executable name", ErrExecutableNotFound)
}
if p, err := appPathsLookup(exeName, registry.LOCAL_MACHINE); err == nil {
return p, nil
}
if p, err := appPathsLookup(exeName, registry.CURRENT_USER); err == nil {
return p, nil
}
if p := runningProcessPath(exeName); p != "" {
return p, nil
}
for _, candidate := range fallbacks {
// Use ExpandEnvString (kernel32!ExpandEnvironmentStringsW)
// rather than os.ExpandEnv: Go stdlib only understands Unix-style
@@ -56,14 +50,24 @@ func ExecutablePath(exeName string, fallbacks []string) (string, error) {
}
}
return "", fmt.Errorf("%w: %q (registry miss, no running process, no fallback match)",
if p, err := appPaths(exeName, registry.LOCAL_MACHINE); err == nil {
return p, nil
}
if p, err := appPaths(exeName, registry.CURRENT_USER); err == nil {
return p, nil
}
if p := running(exeName); p != "" {
return p, nil
}
return "", fmt.Errorf("%w: %q (no install location, registry miss, no running process)",
ErrExecutableNotFound, exeName)
}
// runningProcessPath scans live processes for one whose image filename
// matches exeName (case-insensitive) and returns the full path on the
// first hit. Errors are swallowed — this is a best-effort probe that
// yields to the hard-coded fallbacks if nothing matches.
// first hit. Errors are swallowed — this is the last, best-effort probe.
func runningProcessPath(exeName string) string {
pids, err := EnumProcesses()
if err != nil {
@@ -0,0 +1,84 @@
//go:build windows
package winapi
import (
"errors"
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"golang.org/x/sys/windows/registry"
)
func writeExe(t *testing.T, parts ...string) string {
t.Helper()
path := filepath.Join(parts...)
require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o700))
require.NoError(t, os.WriteFile(path, []byte("MZ"), 0o600))
return path
}
func appPathsAt(byRoot map[registry.Key]string) func(string, registry.Key) (string, error) {
return func(_ string, root registry.Key) (string, error) {
if p, ok := byRoot[root]; ok {
return p, nil
}
return "", errors.New("no App Paths entry")
}
}
func runningAt(path string) func(string) string { return func(string) string { return path } }
// CocCoc and Yandex both ship browser.exe, and App Paths names only one of them.
func TestExecutablePath_InstallLocationWinsOverAnotherVendorsAppPaths(t *testing.T) {
dir := t.TempDir()
own := writeExe(t, dir, "CocCoc", "Browser", "Application", "browser.exe")
other := writeExe(t, dir, "Yandex", "YandexBrowser", "Application", "browser.exe")
got, err := executablePath("browser.exe", []string{filepath.Join(dir, "missing", "browser.exe"), own},
appPathsAt(map[registry.Key]string{registry.LOCAL_MACHINE: other}), runningAt(other))
require.NoError(t, err)
assert.Equal(t, own, got)
}
func TestExecutablePath_ExpandsFallbackVariables(t *testing.T) {
dir := t.TempDir()
own := writeExe(t, dir, "Chrome", "chrome.exe")
t.Setenv("HBD_TEST_INSTALL", dir)
got, err := executablePath("chrome.exe", []string{`%HBD_TEST_INSTALL%\Chrome\chrome.exe`}, appPathsAt(nil), runningAt(""))
require.NoError(t, err)
assert.Equal(t, own, got)
}
func TestExecutablePath_InstallsElsewhereFallBackInOrder(t *testing.T) {
dir := t.TempDir()
machine := writeExe(t, dir, "machine", "chrome.exe")
user := writeExe(t, dir, "user", "chrome.exe")
running := writeExe(t, dir, "portable", "chrome.exe")
missing := []string{filepath.Join(dir, "missing", "chrome.exe")}
got, err := executablePath("chrome.exe", missing,
appPathsAt(map[registry.Key]string{registry.LOCAL_MACHINE: machine, registry.CURRENT_USER: user}), runningAt(running))
require.NoError(t, err)
assert.Equal(t, machine, got)
got, err = executablePath("chrome.exe", missing, appPathsAt(map[registry.Key]string{registry.CURRENT_USER: user}), runningAt(running))
require.NoError(t, err)
assert.Equal(t, user, got)
got, err = executablePath("chrome.exe", missing, appPathsAt(nil), runningAt(running))
require.NoError(t, err)
assert.Equal(t, running, got)
}
func TestExecutablePath_NotFound(t *testing.T) {
_, err := executablePath("chrome.exe", nil, appPathsAt(nil), runningAt(""))
require.ErrorIs(t, err, ErrExecutableNotFound)
_, err = executablePath("", nil, appPathsAt(nil), runningAt(""))
require.ErrorIs(t, err, ErrExecutableNotFound)
}
+1 -1
View File
@@ -43,7 +43,7 @@ The rewrite is invisible from the outside. Every item below behaves exactly as i
| Archive | zip layout `<browser-key>/<User Data layout>`, readable by v1.1.0 `restore` |
| Exit status | `0` when the run completes (including partial results and "no browsers found"); `1` when it cannot start or finish |
Not part of the contract: log lines and the human-readable summary on stderr, and row order where today's order is unspecified or wrong. Output may change only for listed bug fixes where today's output is wrong — Firefox history order, Firefox bookmark fields, Safari bookmark IDs, and the `browser` value `restore` stamps ([RFC-008](008-output-and-export.md)); each is called out where it is fixed.
Not part of the contract: log lines and the human-readable summary on stderr, and row order where today's order is unspecified or wrong. Output may change only for listed bug fixes where today's output is wrong — Firefox history order, Firefox bookmark fields, Safari bookmark IDs, the `browser` value `restore` stamps, and CocCoc cookies on a Windows machine that also has Yandex ([RFC-008](008-output-and-export.md)); each is called out where it is fixed.
## Hard constraints
+1
View File
@@ -72,6 +72,7 @@ Extractors emit records one at a time ([RFC-003](003-core-types.md)), but sortin
- **Firefox bookmarks** — `folder` holds the real folder name instead of `url`, and `type` and `id` are filled; today they are always `url`, empty, and `0`.
- **Safari bookmark IDs** — unique across the whole bookmark tree; today each ID is the index among its siblings, so IDs repeat across folders.
- **`browser` in `restore` output** — the display name (`Chrome`), as `dump` writes it; today `restore` writes the vault key (`chrome`).
- **CocCoc cookies beside Yandex** — on Windows, ABE looks for a browser's program in its own install locations before registry App Paths. CocCoc and Yandex both ship `browser.exe`, and App Paths names only one of them, so today CocCoc's key is requested from Yandex's program and its `v20` cookies export with empty values.
## Secrets in output
+1
View File
@@ -59,6 +59,7 @@ Each bug designed out by this rewrite gets a test that would have caught it, so
- **Temp snapshot cleanup**: a run that fails mid-way leaves no copied `Login Data` or `Cookies` behind.
- **Discovery errors are not absence**: an unreadable user data dir (permission denied) is reported as an `error` result, distinct from one that simply isn't there (nothing). The home directory comes from `DiscoverOptions`, so a `t.TempDir()` stands in.
- **Safari discovery reads a copy**: listing Safari profiles opens a snapshot copy of `SafariTabs.db`, never the live file.
- **Shared executable names**: when App Paths names another vendor's `browser.exe`, the browser's own install location wins.
## Table and payload consistency
+2 -2
View File
@@ -49,7 +49,7 @@ browser/chromium.Extract()
→ masterkey.Retrievers{V10: &DPAPIRetriever{}, V20: &ABERetriever{}}
→ ABERetriever.RetrieveKey():
reads Local State → extracts APPB-prefixed blob
resolves browser exe via registry App Paths
resolves browser exe: install locations, then App Paths
→ utils/injector.Reflective.Inject(exePath, payload, env)
```
@@ -198,7 +198,7 @@ Go consumes the same constants via **`go tool cgo -godefs`** (a development-time
`masterkey.DefaultRetrievers()` on Windows returns a `Retrievers` struct with `V10 = &DPAPIRetriever{}` and `V20 = &ABERetriever{}`. The two tiers are wired independently — not in a ChainRetriever — because a single Chrome profile upgraded from pre-127 can carry mixed v10+v20 ciphertexts, and both keys must be available for `decryptValue` to route each ciphertext to its matching tier (see [RFC-015](015-key-retrieval-mechanisms.md) §4.4 and issue #578). `ABERetriever.RetrieveKey`:
1. Reads `Local State` → extracts `os_crypt.app_bound_encrypted_key` → strips `APPB` prefix. If the field is missing, `ABERetriever` returns `(nil, nil)`, `V20` remains empty, and the independently-wired `V10` DPAPI tier still runs.
2. Resolves browser executable via `utils/winutil/browser_path_windows.go` (registry App Paths → hardcoded fallback).
2. Resolves browser executable via `internal/winapi/executable_windows.go` (install-location fallbacks → registry App Paths → running process; the install locations come first because an executable name such as `browser.exe` is shared by more than one vendor).
3. Base64-encodes the encrypted blob and passes it as `HBD_ABE_ENC_B64` env var.
4. `Reflective.Inject(exePath, payload, env)` runs the full flow in §3.
5. Returns the 32-byte key on success, or a formatted diagnostic error.