fix: write keys.json atomically, unify zip handling (#686)

dumpkeys truncated keys.json before writing it, so a failed write left a partial file; app now writes it through the
same temp-file-and-rename path zips use. Unzipping moves next to zip writing and checks entries with filepath.IsLocal.
This commit is contained in:
Roger authored and GitHub committed 2026-11-09 17:25:35 +08:00
1 parent 9e9d1c531d
commit 8ce917d57e
11 files changed
+321 -155

No files matched your search

+3 -15
View File
@@ -1,10 +1,6 @@
package main
import (
"errors"
"fmt"
"os"
"github.com/spf13/cobra"
"github.com/moond4rk/hackbrowserdata/internal/app"
@@ -27,20 +23,12 @@ func newDumpKeysCommand() *cobra.Command {
if err != nil {
return err
}
keyFile, err := app.DumpKeys(command.Context(), app.Discover(options), options)
vaultCount, err := app.DumpKeys(command.Context(), app.Discover(options), options, outputPath)
if err != nil {
return err
}
log.Infof("Exported keys for %d vault(s)", len(keyFile.Vaults))
if outputPath == "" {
return keyFile.Write(os.Stdout)
}
file, err := os.OpenFile(outputPath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o600)
if err != nil {
return fmt.Errorf("create %s: %w", outputPath, err)
}
return errors.Join(keyFile.Write(file), file.Close())
log.Infof("Exported keys for %d vault(s)", vaultCount)
return nil
},
}
+26 -4
View File
@@ -3,7 +3,9 @@ package app
import (
"context"
"fmt"
"os"
"github.com/moond4rk/hackbrowserdata/internal/atomicfile"
"github.com/moond4rk/hackbrowserdata/internal/browser"
"github.com/moond4rk/hackbrowserdata/internal/browser/chromium"
"github.com/moond4rk/hackbrowserdata/internal/log"
@@ -11,12 +13,32 @@ import (
"github.com/moond4rk/hackbrowserdata/internal/snapshot"
)
// DumpKeys keeps the keys that worked when a dir's others fail, and leaves out a dir with none.
// It fails only when the run is stopped, so a stopped run writes no keys.json.
func DumpKeys(ctx context.Context, discovery Discovery, options Options) (masterkey.KeyFile, error) {
return dumpKeysWith(ctx, discovery, keysFromMachine(newLoginKeychain(options)))
// DumpKeys writes the key file to outputPath, or to stdout when it is "", and returns how many vaults it holds.
// A stopped run writes nothing, so it never leaves a keys.json behind.
func DumpKeys(ctx context.Context, discovery Discovery, options Options, outputPath string) (int, error) {
keyFile, err := dumpKeysWith(ctx, discovery, keysFromMachine(newLoginKeychain(options)))
if err != nil {
return 0, err
}
if outputPath == "" {
return len(keyFile.Vaults), keyFile.Write(os.Stdout)
}
if err := writeKeyFile(outputPath, keyFile); err != nil {
return 0, err
}
return len(keyFile.Vaults), nil
}
// writeKeyFile replaces outputPath only once the file is complete, so a failure keeps the old keys.json.
func writeKeyFile(outputPath string, keyFile masterkey.KeyFile) error {
if err := atomicfile.Write(outputPath, keyFile.Write); err != nil {
return fmt.Errorf("write %s: %w", outputPath, err)
}
return nil
}
// dumpKeysWith keeps the keys that worked when a dir's others fail, and leaves out a dir with none.
// It fails only when the run is stopped.
func dumpKeysWith(ctx context.Context, discovery Discovery, keys dirKeysFunc) (masterkey.KeyFile, error) {
keyFile := masterkey.NewKeyFile()
for _, dir := range discovery.Dirs {
+27
View File
@@ -3,6 +3,8 @@ package app
import (
"context"
"errors"
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/assert"
@@ -79,3 +81,28 @@ func TestDumpKeys_StoppedRunReturnsNoKeyFile(t *testing.T) {
require.ErrorIs(t, err, context.Canceled)
assert.Empty(t, keyFile.Vaults)
}
func TestWriteKeyFile_ReplacesTheFileWhole(t *testing.T) {
path := filepath.Join(t.TempDir(), "keys.json")
require.NoError(t, os.WriteFile(path, []byte("stale"), 0o600))
keyFile := masterkey.NewKeyFile()
keyFile.Vaults = append(keyFile.Vaults, masterkey.Vault{
Browser: "chrome", Kind: "chromium", Profiles: []string{"Default"}, Keys: masterkey.Set{masterkey.V10: []byte("key")},
})
require.NoError(t, writeKeyFile(path, keyFile))
file, err := os.Open(path)
require.NoError(t, err)
defer file.Close()
written, err := masterkey.ReadKeyFile(file)
require.NoError(t, err)
assert.Equal(t, keyFile.Vaults, written.Vaults)
}
func TestWriteKeyFile_FailureLeavesNoFile(t *testing.T) {
dir := t.TempDir()
require.Error(t, writeKeyFile(filepath.Join(dir, "missing", "keys.json"), masterkey.NewKeyFile()))
entries, err := os.ReadDir(dir)
require.NoError(t, err)
assert.Empty(t, entries)
}
+34
View File
@@ -0,0 +1,34 @@
// Package atomicfile writes a file in full or not at all, so no reader ever sees a partial one.
package atomicfile
import (
"errors"
"fmt"
"io"
"os"
"path/filepath"
)
// Write renames a finished temp file into place, so path is never partial and a failure keeps the old file.
func Write(path string, write func(io.Writer) error) (err error) {
// CreateTemp makes a new 0600 file under an unpredictable name, so a planted file or symlink is never written through.
temporary, err := os.CreateTemp(filepath.Dir(path), filepath.Base(path)+".*.tmp")
if err != nil {
return fmt.Errorf("create %s: %w", path, err)
}
defer func() {
if err != nil {
err = errors.Join(err, os.Remove(temporary.Name()))
}
}()
if err := write(temporary); err != nil {
return errors.Join(err, temporary.Close())
}
if err := temporary.Close(); err != nil {
return fmt.Errorf("finish %s: %w", path, err)
}
if err := os.Rename(temporary.Name(), path); err != nil {
return fmt.Errorf("move %s into place: %w", path, err)
}
return nil
}
+114
View File
@@ -0,0 +1,114 @@
package atomicfile
import (
"errors"
"io"
"os"
"path/filepath"
"runtime"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestWrite_ReplacesAnExistingFile(t *testing.T) {
path := filepath.Join(t.TempDir(), "keys.json")
writeFile(t, path, "stale")
require.NoError(t, Write(path, writeString("fresh")))
got, err := os.ReadFile(path)
require.NoError(t, err)
assert.Equal(t, "fresh", string(got))
assert.Equal(t, []string{"keys.json"}, filesIn(t, filepath.Dir(path)))
}
func TestWrite_FailureKeepsAnExistingFile(t *testing.T) {
out := t.TempDir()
path := filepath.Join(out, "keys.json")
writeFile(t, path, "precious")
failure := errors.New("encoder failed")
err := Write(path, func(writer io.Writer) error {
if _, err := io.WriteString(writer, "half"); err != nil {
return err
}
return failure
})
require.ErrorIs(t, err, failure)
got, err := os.ReadFile(path)
require.NoError(t, err)
assert.Equal(t, "precious", string(got))
assert.Equal(t, []string{"keys.json"}, filesIn(t, out), "no temp file may survive a failed write")
}
// TestWrite_IsOwnerOnly keeps a written file as private as the browser files and records it holds.
func TestWrite_IsOwnerOnly(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("Windows has no mode bits to check")
}
path := filepath.Join(t.TempDir(), "out.zip")
require.NoError(t, Write(path, writeString("")))
info, err := os.Stat(path)
require.NoError(t, err)
assert.Equal(t, os.FileMode(0o600), info.Mode().Perm())
}
func TestWrite_LeavesAPlantedTempFileAlone(t *testing.T) {
out := t.TempDir()
path := filepath.Join(out, "out.zip")
writeFile(t, path+".tmp", "planted")
require.NoError(t, os.Chmod(path+".tmp", 0o644))
require.NoError(t, Write(path, writeString("")))
planted, err := os.ReadFile(path + ".tmp")
require.NoError(t, err)
assert.Equal(t, "planted", string(planted))
assert.Equal(t, []string{"out.zip", "out.zip.tmp"}, filesIn(t, out))
if runtime.GOOS != "windows" {
info, err := os.Stat(path)
require.NoError(t, err)
assert.Equal(t, os.FileMode(0o600), info.Mode().Perm(), "a planted 0644 file must not set the file's mode")
}
}
func TestWrite_DoesNotFollowAPlantedSymlink(t *testing.T) {
path := filepath.Join(t.TempDir(), "out.zip")
victim := filepath.Join(t.TempDir(), "victim")
writeFile(t, victim, "precious")
if err := os.Symlink(victim, path+".tmp"); err != nil {
t.Skipf("cannot create a symlink here: %v", err)
}
require.NoError(t, Write(path, writeString("")))
got, err := os.ReadFile(victim)
require.NoError(t, err)
assert.Equal(t, "precious", string(got))
info, err := os.Lstat(path)
require.NoError(t, err)
assert.True(t, info.Mode().IsRegular(), "the written file must be a file, not the planted symlink")
}
func writeString(content string) func(io.Writer) error {
return func(writer io.Writer) error {
_, err := io.WriteString(writer, content)
return err
}
}
func filesIn(t *testing.T, dir string) []string {
t.Helper()
dirEntries, err := os.ReadDir(dir)
require.NoError(t, err)
names := make([]string, 0, len(dirEntries))
for _, entry := range dirEntries {
names = append(names, entry.Name())
}
return names
}
func writeFile(t *testing.T, path, data string) {
t.Helper()
require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o755))
require.NoError(t, os.WriteFile(path, []byte(data), 0o600))
}
+2 -2
View File
@@ -59,10 +59,10 @@ func currentHost() Host {
return host
}
func (d KeyFile) Write(writer io.Writer) error {
func (k KeyFile) Write(writer io.Writer) error {
encoder := json.NewEncoder(writer)
encoder.SetIndent("", " ")
if err := encoder.Encode(d); err != nil {
if err := encoder.Encode(k); err != nil {
return fmt.Errorf("encode key file: %w", err)
}
return nil
+3 -1
View File
@@ -8,6 +8,8 @@ import (
"os"
"path/filepath"
"strings"
"github.com/moond4rk/hackbrowserdata/internal/zipfile"
)
type File struct {
@@ -44,7 +46,7 @@ func Unzip(archivePath string) (*Dir, error) {
if err != nil {
return nil, err
}
if err := unzip(archivePath, snapshotDir.path); err != nil {
if err := zipfile.Extract(archivePath, snapshotDir.path); err != nil {
return nil, errors.Join(err, snapshotDir.Close())
}
return snapshotDir, nil
-58
View File
@@ -1,14 +1,9 @@
package snapshot
import (
"archive/zip"
"errors"
"fmt"
"io"
"io/fs"
"os"
"path/filepath"
"strings"
"github.com/moond4rk/hackbrowserdata/internal/zipfile"
)
@@ -34,56 +29,3 @@ func (d *Dir) Zip(archivePath string) error {
}
return zipfile.Write(archivePath, d.path, names)
}
func unzip(archivePath, destDir string) error {
zipReader, err := zip.OpenReader(archivePath)
if err != nil {
return fmt.Errorf("open zip %s: %w", archivePath, err)
}
defer zipReader.Close()
root := filepath.Clean(destDir)
for _, zipFile := range zipReader.File {
target := filepath.Join(root, filepath.FromSlash(zipFile.Name))
if target != root && !strings.HasPrefix(target, root+string(os.PathSeparator)) {
return fmt.Errorf("zip entry %q escapes destination", zipFile.Name)
}
if zipFile.FileInfo().IsDir() {
if err := os.MkdirAll(target, 0o700); err != nil {
return err
}
continue
}
if err := os.MkdirAll(filepath.Dir(target), 0o700); err != nil {
return err
}
if err := writeZipEntry(zipFile, target); err != nil {
return err
}
}
return nil
}
func writeZipEntry(zipFile *zip.File, target string) (err error) {
entryReader, err := zipFile.Open()
if err != nil {
return err
}
defer entryReader.Close()
out, err := os.OpenFile(target, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o600)
if err != nil {
return err
}
defer func() { err = errors.Join(err, out.Close()) }()
for {
_, err := io.CopyN(out, entryReader, 1<<20)
if errors.Is(err, io.EOF) {
return nil
}
if err != nil {
return err
}
}
}
-8
View File
@@ -55,14 +55,6 @@ func TestUnzip_RejectsZipSlipAndCleansUp(t *testing.T) {
assert.Empty(t, entries, "a rejected archive leaves neither the escaped file nor the snapshot directory behind")
}
func TestUnzip_RejectsASiblingSharingTheRootPrefix(t *testing.T) {
parent := t.TempDir()
root := filepath.Join(parent, "snap")
require.Error(t, unzip(zipWith(t, "../snapx/evil.txt"), root))
assert.NoFileExists(t, filepath.Join(parent, "snapx", "evil.txt"))
}
func TestZip_FailureLeavesNoFile(t *testing.T) {
out := t.TempDir()
err := Open(filepath.Join(t.TempDir(), "missing")).Zip(filepath.Join(out, "browser-data.zip"))
+69 -28
View File
@@ -1,4 +1,4 @@
// Package zipfile writes the zip archives HBD produces: export's --zip and the archive command's.
// Package zipfile writes the zip archives HBD produces, export's --zip and the archive command's, and extracts them.
package zipfile
import (
@@ -8,37 +8,24 @@ import (
"io"
"os"
"path/filepath"
"github.com/moond4rk/hackbrowserdata/internal/atomicfile"
)
// Write renames a finished temp file into place, so archivePath is never a partial zip and a failure keeps the old one.
// Names are slash-separated paths relative to root, and each becomes the entry of that name.
func Write(archivePath, root string, names []string) (err error) {
// CreateTemp makes a new 0600 file under an unpredictable name, so a planted file or symlink is never written through.
temporary, err := os.CreateTemp(filepath.Dir(archivePath), filepath.Base(archivePath)+".*.tmp")
if err != nil {
return fmt.Errorf("create %s: %w", archivePath, err)
}
defer func() {
if err != nil {
err = errors.Join(err, os.Remove(temporary.Name()))
// Write never leaves a partial archivePath. Names are slash-separated paths relative to root, each its own entry.
func Write(archivePath, root string, names []string) error {
return atomicfile.Write(archivePath, func(out io.Writer) error {
zipWriter := zip.NewWriter(out)
for _, name := range names {
if err := addFile(zipWriter, filepath.Join(root, filepath.FromSlash(name)), name); err != nil {
return errors.Join(fmt.Errorf("add %s: %w", name, err), zipWriter.Close())
}
}
}()
zipWriter := zip.NewWriter(temporary)
for _, name := range names {
if err := addFile(zipWriter, filepath.Join(root, filepath.FromSlash(name)), name); err != nil {
return errors.Join(fmt.Errorf("add %s: %w", name, err), zipWriter.Close(), temporary.Close())
if err := zipWriter.Close(); err != nil {
return fmt.Errorf("finish %s: %w", archivePath, err)
}
}
if err := zipWriter.Close(); err != nil {
return errors.Join(fmt.Errorf("finish %s: %w", archivePath, err), temporary.Close())
}
if err := temporary.Close(); err != nil {
return fmt.Errorf("finish %s: %w", archivePath, err)
}
if err := os.Rename(temporary.Name(), archivePath); err != nil {
return fmt.Errorf("move zip into place: %w", err)
}
return nil
return nil
})
}
func addFile(zipWriter *zip.Writer, path, name string) error {
@@ -54,3 +41,57 @@ func addFile(zipWriter *zip.Writer, path, name string) error {
_, err = io.Copy(entryWriter, file)
return err
}
// Extract unpacks archivePath into dir, refusing any entry that would land outside it.
func Extract(archivePath, dir string) error {
zipReader, err := zip.OpenReader(archivePath)
if err != nil {
return fmt.Errorf("open zip %s: %w", archivePath, err)
}
defer zipReader.Close()
for _, zipFile := range zipReader.File {
name := filepath.FromSlash(zipFile.Name)
if !filepath.IsLocal(name) {
return fmt.Errorf("zip entry %q escapes destination", zipFile.Name)
}
target := filepath.Join(dir, name)
if zipFile.FileInfo().IsDir() {
if err := os.MkdirAll(target, 0o700); err != nil {
return err
}
continue
}
if err := os.MkdirAll(filepath.Dir(target), 0o700); err != nil {
return err
}
if err := extractFile(zipFile, target); err != nil {
return err
}
}
return nil
}
func extractFile(zipFile *zip.File, target string) (err error) {
entryReader, err := zipFile.Open()
if err != nil {
return err
}
defer entryReader.Close()
out, err := os.OpenFile(target, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o600)
if err != nil {
return err
}
defer func() { err = errors.Join(err, out.Close()) }()
for {
_, err := io.CopyN(out, entryReader, 1<<20)
if errors.Is(err, io.EOF) {
return nil
}
if err != nil {
return err
}
}
}
+43 -39
View File
@@ -5,7 +5,6 @@ import (
"io"
"os"
"path/filepath"
"runtime"
"testing"
"github.com/stretchr/testify/assert"
@@ -35,51 +34,56 @@ func TestWrite_FailureKeepsAnExistingArchive(t *testing.T) {
assert.Equal(t, []string{"out.zip"}, filesIn(t, out), "no temp file may survive a failed zip")
}
// TestWrite_IsOwnerOnly keeps an archive as private as the browser files and records it holds.
func TestWrite_IsOwnerOnly(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("Windows has no mode bits to check")
}
func TestExtract_RoundTripsWhatWriteZipped(t *testing.T) {
root := t.TempDir()
writeFile(t, filepath.Join(root, "chrome", "Default", "History"), "history")
writeFile(t, filepath.Join(root, "chrome", "Local State"), "{}")
archive := filepath.Join(t.TempDir(), "out.zip")
require.NoError(t, Write(archive, t.TempDir(), nil))
info, err := os.Stat(archive)
require.NoError(t, err)
assert.Equal(t, os.FileMode(0o600), info.Mode().Perm())
require.NoError(t, Write(archive, root, []string{"chrome/Default/History", "chrome/Local State"}))
dir := t.TempDir()
require.NoError(t, Extract(archive, dir))
for name, want := range map[string]string{"chrome/Default/History": "history", "chrome/Local State": "{}"} {
got, err := os.ReadFile(filepath.Join(dir, filepath.FromSlash(name)))
require.NoError(t, err, name)
assert.Equal(t, want, string(got), name)
}
}
func TestWrite_LeavesAPlantedTempFileAlone(t *testing.T) {
out := t.TempDir()
archive := filepath.Join(out, "out.zip")
writeFile(t, archive+".tmp", "planted")
require.NoError(t, os.Chmod(archive+".tmp", 0o644))
func TestExtract_RejectsAnEntryOutsideTheDir(t *testing.T) {
for _, name := range []string{"../escape.txt", "/abs/escape.txt", "a/../../escape.txt"} {
t.Run(name, func(t *testing.T) {
parent := t.TempDir()
dir := filepath.Join(parent, "snap")
require.Error(t, Extract(zipWith(t, name), dir))
assert.NoFileExists(t, filepath.Join(parent, "escape.txt"))
})
}
}
require.NoError(t, Write(archive, t.TempDir(), nil))
planted, err := os.ReadFile(archive + ".tmp")
func TestExtract_RejectsASiblingSharingTheDirPrefix(t *testing.T) {
parent := t.TempDir()
dir := filepath.Join(parent, "snap")
require.Error(t, Extract(zipWith(t, "../snapx/evil.txt"), dir))
assert.NoFileExists(t, filepath.Join(parent, "snapx", "evil.txt"))
}
func zipWith(t *testing.T, names ...string) string {
t.Helper()
archive := filepath.Join(t.TempDir(), "test.zip")
file, err := os.Create(archive)
require.NoError(t, err)
assert.Equal(t, "planted", string(planted))
assert.Equal(t, []string{"out.zip", "out.zip.tmp"}, filesIn(t, out))
if runtime.GOOS != "windows" {
info, err := os.Stat(archive)
zipWriter := zip.NewWriter(file)
for _, name := range names {
writer, err := zipWriter.Create(name)
require.NoError(t, err)
_, err = writer.Write([]byte(name))
require.NoError(t, err)
assert.Equal(t, os.FileMode(0o600), info.Mode().Perm(), "a planted 0644 file must not set the archive's mode")
}
}
func TestWrite_DoesNotFollowAPlantedSymlink(t *testing.T) {
archive := filepath.Join(t.TempDir(), "out.zip")
victim := filepath.Join(t.TempDir(), "victim")
writeFile(t, victim, "precious")
if err := os.Symlink(victim, archive+".tmp"); err != nil {
t.Skipf("cannot create a symlink here: %v", err)
}
require.NoError(t, Write(archive, t.TempDir(), nil))
got, err := os.ReadFile(victim)
require.NoError(t, err)
assert.Equal(t, "precious", string(got))
info, err := os.Lstat(archive)
require.NoError(t, err)
assert.True(t, info.Mode().IsRegular(), "the archive must be a file, not the planted symlink")
require.NoError(t, zipWriter.Close())
require.NoError(t, file.Close())
return archive
}
func filesIn(t *testing.T, dir string) []string {