diff --git a/internal/tools/file_commit.go b/internal/tools/file_commit.go index a169418e1..157b9f61b 100644 --- a/internal/tools/file_commit.go +++ b/internal/tools/file_commit.go @@ -51,6 +51,14 @@ var fileWriteRename = func(root *os.Root, oldName, newName string) error { return root.Rename(oldName, newName) } +// fileWriteCaptureSecurity and fileWriteApplySecurity carry the replaced file's +// access control to the file that takes its name. Tests replace them to +// exercise a failure at either step. +var ( + fileWriteCaptureSecurity = captureFileSecurity + fileWriteApplySecurity = applyFileSecurity +) + // fileWriteNoReplaceRename publishes a create without replacing an existing // name. Tests replace it to exercise the hard-link fallback that filesystems // without a no-replace rename use. @@ -156,10 +164,20 @@ func commitRootedFileContents(root *os.Root, absolutePath, relativePath string, return fmt.Errorf("%w: link target changed", errFileChangedDuringWrite) } } + // The side file is created fresh and would publish with the directory's + // inherited access control. Read what the observed file carries while its + // validated handle is still open, so the file that takes its name keeps + // it. A list that cannot be read cannot be carried, and replacing the file + // anyway would reset it, so that refuses the write. + security, securityErr := fileWriteCaptureSecurity(file) + if securityErr != nil { + _ = file.Close() + return fmt.Errorf("writing %s: %w", relativePath, securityErr) + } if err := file.Close(); err != nil { return err } - return commitRootedFileOverwrite(root, absolutePath, relativePath, publishPath, openedInfo, mode, content) + return commitRootedFileOverwrite(root, absolutePath, relativePath, publishPath, openedInfo, mode, security, content) } // commitRootedFileCreate publishes a brand-new file whose absence the caller @@ -168,7 +186,7 @@ func commitRootedFileContents(root *os.Root, absolutePath, relativePath string, // either absent or the whole file, a concurrent create is refused rather than // replaced, and a write that cannot complete leaves no file at all. func commitRootedFileCreate(root *os.Root, relativePath, content string) error { - tempName, err := writeRootedSideFile(root, relativePath, 0o644, true, content) + tempName, err := writeRootedSideFile(root, relativePath, 0o644, true, nil, content) if err != nil { return err } @@ -244,8 +262,8 @@ func renameNoReplaceUnsupported(err error) bool { // Refused renames fail without mutating the observed inode. Writing in place // here would expose partial content and rewrite hard-link siblings, defeating // the guarantees that staging provides. -func commitRootedFileOverwrite(root *os.Root, absolutePath, relativePath, publishPath string, openedInfo os.FileInfo, mode os.FileMode, content string) error { - tempName, err := writeRootedSideFile(root, publishPath, mode, false, content) +func commitRootedFileOverwrite(root *os.Root, absolutePath, relativePath, publishPath string, openedInfo os.FileInfo, mode os.FileMode, security *fileSecurity, content string) error { + tempName, err := writeRootedSideFile(root, publishPath, mode, false, security, content) if err != nil { return err } @@ -312,13 +330,15 @@ func resolveRootedFinalPath(root *os.Root, relativePath string) (string, error) // 0o644 and remembers what the process umask actually granted; the bytes are // made owner-only while they are staged, then the granted bits are restored. // An overwrite stages 0o600 and finally carries the observed file's permission -// bits over, so the published file looks like the one it replaced. -func writeRootedSideFile(root *os.Root, relativePath string, mode os.FileMode, umaskDerived bool, content string) (string, error) { +// bits over, so the published file looks like the one it replaced. It also +// carries security, the replaced file's access control, when there is any: a +// create passes nil and keeps what the directory gives a new file. +func writeRootedSideFile(root *os.Root, relativePath string, mode os.FileMode, umaskDerived bool, security *fileSecurity, content string) (string, error) { createMode := mode.Perm() if !umaskDerived { createMode = 0o600 } - temp, tempName, err := pathjail.CreateTempMode(root, filepath.Dir(relativePath), "zero-write", ".tmp", createMode) + temp, tempName, err := createSideFile(root, relativePath, createMode, security) if err != nil { return "", fmt.Errorf("writing %s: %w", relativePath, err) } @@ -338,6 +358,13 @@ func writeRootedSideFile(root *os.Root, relativePath string, mode os.FileMode, u } } writeErr := func() error { + // The side file was created with the directory's access control. It is + // given the replaced file's before any byte is written, while it is still + // empty: applied afterwards, the replacement would sit readable by + // everyone the directory admits until the list landed. + if err := fileWriteApplySecurity(temp, security); err != nil { + return err + } if err := fileWriteTempWrite(temp, content); err != nil { return err } diff --git a/internal/tools/file_commit_security_other.go b/internal/tools/file_commit_security_other.go new file mode 100644 index 000000000..2df23b522 --- /dev/null +++ b/internal/tools/file_commit_security_other.go @@ -0,0 +1,27 @@ +//go:build !windows + +package tools + +import ( + "os" + "path/filepath" + + "github.com/Twigpine/zero/internal/pathjail" +) + +// fileSecurity is the access control an overwrite carries from the file it +// replaces. Only Windows has anything to carry here: elsewhere the permission +// bits are the access control this package preserves, and the staged file is +// given them directly. +type fileSecurity struct{} + +func captureFileSecurity(*os.File) (*fileSecurity, error) { return nil, nil } + +func applyFileSecurity(*os.File, *fileSecurity) error { return nil } + +// createSideFile creates the side file an overwrite or a create stages its +// bytes in. The mode is the kernel's exclusive-create mode, so an overwrite's +// side file is owner-only from the moment it exists. +func createSideFile(root *os.Root, relativePath string, mode os.FileMode, _ *fileSecurity) (*os.File, string, error) { + return pathjail.CreateTempMode(root, filepath.Dir(relativePath), "zero-write", ".tmp", mode) +} diff --git a/internal/tools/file_commit_security_test.go b/internal/tools/file_commit_security_test.go new file mode 100644 index 000000000..dfb4052c3 --- /dev/null +++ b/internal/tools/file_commit_security_test.go @@ -0,0 +1,119 @@ +package tools + +import ( + "context" + "errors" + "os" + "path/filepath" + "strings" + "testing" +) + +func installFileWriteSecurity(t *testing.T, capture func(*os.File) (*fileSecurity, error), apply func(*os.File, *fileSecurity) error) { + t.Helper() + priorCapture, priorApply := fileWriteCaptureSecurity, fileWriteApplySecurity + if capture != nil { + fileWriteCaptureSecurity = capture + } + if apply != nil { + fileWriteApplySecurity = apply + } + t.Cleanup(func() { fileWriteCaptureSecurity, fileWriteApplySecurity = priorCapture, priorApply }) +} + +// AN OVERWRITE THAT CANNOT CARRY THE FILE'S ACCESS CONTROL DOES NOT HAPPEN. +// +// The overwrite replaces the file with a freshly created one, and a fresh file +// has whatever the directory gives it. If the original's access control cannot +// be read, or cannot be put on the staged file, publishing anyway would quietly +// widen who can read a file its owner had locked down. Both failures therefore +// refuse the write, leave the observed bytes standing, and remove the side +// file. These run on every platform: the seams are the same everywhere, and +// only what the production functions do behind them differs. +func TestOverwriteRefusesWhenAccessControlCannotBeCarried(t *testing.T) { + failure := errors.New("injected access control failure") + for _, testCase := range []struct { + name string + capture func(*os.File) (*fileSecurity, error) + apply func(*os.File, *fileSecurity) error + }{ + {name: "reading it fails", capture: func(*os.File) (*fileSecurity, error) { return nil, failure }}, + {name: "applying it fails", apply: func(*os.File, *fileSecurity) error { return failure }}, + } { + t.Run(testCase.name, func(t *testing.T) { + root := t.TempDir() + target := filepath.Join(root, "existing.txt") + if err := os.WriteFile(target, []byte("observed\n"), 0o644); err != nil { + t.Fatal(err) + } + workspace, err := os.OpenRoot(root) + if err != nil { + t.Fatal(err) + } + defer workspace.Close() + info, err := os.Stat(target) + if err != nil { + t.Fatal(err) + } + preimage := "observed\n" + installFileWriteSecurity(t, testCase.capture, testCase.apply) + + err = commitRootedFileContents(workspace, target, "existing.txt", info, &preimage, "replacement\n") + if !errors.Is(err, failure) { + t.Fatalf("commit error = %v, want the injected access control failure", err) + } + got, readErr := os.ReadFile(target) + if readErr != nil || string(got) != "observed\n" { + t.Fatalf("file = %q, err=%v; the observed bytes must outlive a refused overwrite", got, readErr) + } + entries, err := os.ReadDir(root) + if err != nil { + t.Fatal(err) + } + if len(entries) != 1 { + names := make([]string, 0, len(entries)) + for _, entry := range entries { + names = append(names, entry.Name()) + } + t.Fatalf("directory holds %s; a refused overwrite must remove its side file", strings.Join(names, ", ")) + } + }) + } +} + +// THE CARRY IS FOR THE FILE THAT IS REPLACED, AND ONLY THAT ONE. +// +// A create has no original to take access control from and keeps what the +// directory gives a new file, so it must hand the side file nothing. An +// overwrite hands it exactly what was read from the observed file. The +// assertion on the overwrite also proves the seam was reached, so the create +// half cannot pass by the seam never being called. +func TestOnlyAnOverwriteCarriesAccessControl(t *testing.T) { + root := t.TempDir() + read := &fileSecurity{} + var applied []*fileSecurity + installFileWriteSecurity(t, + func(*os.File) (*fileSecurity, error) { return read, nil }, + func(_ *os.File, security *fileSecurity) error { + applied = append(applied, security) + return nil + }, + ) + tool := NewScopedWriteFileTool(root, nil) + + created := tool.Run(context.Background(), map[string]any{"path": "note.txt", "content": "first\n"}) + if created.Status != StatusOK { + t.Fatalf("create = %s: %s", created.Status, created.Output) + } + if len(applied) != 1 || applied[0] != nil { + t.Fatalf("a create handed its side file %v; it has no original to carry access control from", applied) + } + + overwrote := tool.Run(context.Background(), map[string]any{"path": "note.txt", "content": "second\n", "overwrite": true}) + if overwrote.Status != StatusOK { + t.Fatalf("overwrite = %s: %s", overwrote.Status, overwrote.Output) + } + if len(applied) != 2 || applied[1] != read { + t.Fatalf("an overwrite handed its side file %v, want what was read from the file it replaces", applied) + } +} diff --git a/internal/tools/file_commit_security_windows.go b/internal/tools/file_commit_security_windows.go new file mode 100644 index 000000000..f895e46cf --- /dev/null +++ b/internal/tools/file_commit_security_windows.go @@ -0,0 +1,238 @@ +//go:build windows + +package tools + +import ( + "crypto/rand" + "encoding/hex" + "errors" + "fmt" + "os" + "path/filepath" + "unsafe" + + "golang.org/x/sys/windows" + + "github.com/Twigpine/zero/internal/pathjail" +) + +// fileSecurity is the access control an overwrite carries from the file it +// replaces to the file that takes its name. +// +// An overwrite is published by renaming a freshly created side file over the +// target. A fresh file takes the directory's inherited access control list, so +// without this the rename silently drops whatever was set on the original: an +// explicit entry disappears, and a file whose inheritance had been removed +// comes back with everything the directory grants. +type fileSecurity struct { + // descriptor owns the memory dacl points into. + descriptor *windows.SECURITY_DESCRIPTOR + dacl *windows.ACL + // protected records that the original did not inherit from its directory. + protected bool +} + +// fileVolumeKeepsACLs reports whether the volume holding the open file stores +// access control lists at all. FAT and exFAT do not, and there is nothing to +// carry on them. Tests replace it; production asks the volume. +var fileVolumeKeepsACLs = func(handle windows.Handle) (bool, error) { + var flags uint32 + if err := windows.GetVolumeInformationByHandle(handle, nil, 0, nil, nil, &flags, nil, 0); err != nil { + return false, err + } + return flags&windows.FILE_PERSISTENT_ACLS != 0, nil +} + +// captureFileSecurity reads the access control list of the file an overwrite +// is about to replace. It works through the handle whose identity the caller +// has already validated, so a name swapped in afterwards cannot supply the +// list. A nil result means the volume keeps no lists. +func captureFileSecurity(file *os.File) (*fileSecurity, error) { + handle, err := reopenFileForSecurity(file, windows.READ_CONTROL) + if err != nil { + return nil, fmt.Errorf("open the existing file's access control list: %w", err) + } + defer windows.CloseHandle(handle) + keeps, err := fileVolumeKeepsACLs(handle) + if err != nil { + return nil, fmt.Errorf("inspect the volume's access control support: %w", err) + } + if !keeps { + return nil, nil + } + descriptor, err := windows.GetSecurityInfo(handle, windows.SE_FILE_OBJECT, windows.DACL_SECURITY_INFORMATION) + if err != nil { + return nil, fmt.Errorf("read the existing file's access control list: %w", err) + } + dacl, _, err := descriptor.DACL() + if err != nil { + return nil, fmt.Errorf("decode the existing file's access control list: %w", err) + } + control, _, err := descriptor.Control() + if err != nil { + return nil, fmt.Errorf("read the existing file's access control flags: %w", err) + } + return &fileSecurity{ + descriptor: descriptor, + dacl: dacl, + protected: control&windows.SE_DACL_PROTECTED != 0, + }, nil +} + +// applyFileSecurity stamps the captured access control list on the staged +// file, through a handle reopened from the staged file's own handle, before +// the rename publishes it. An unprotected list is applied unprotected, so the +// system rebuilds the inherited entries from the directory and keeps the +// explicit ones; a protected list is applied as it was read. +func applyFileSecurity(staged *os.File, security *fileSecurity) error { + if security == nil { + return nil + } + handle, err := reopenFileForSecurity(staged, windows.READ_CONTROL|windows.WRITE_DAC) + if err != nil { + return fmt.Errorf("open the staged file's access control list: %w", err) + } + defer windows.CloseHandle(handle) + information := windows.SECURITY_INFORMATION(windows.DACL_SECURITY_INFORMATION) + if security.protected { + information |= windows.SECURITY_INFORMATION(windows.PROTECTED_DACL_SECURITY_INFORMATION) + } else { + information |= windows.SECURITY_INFORMATION(windows.UNPROTECTED_DACL_SECURITY_INFORMATION) + } + if err := windows.SetSecurityInfo(handle, windows.SE_FILE_OBJECT, information, nil, nil, security.dacl, nil); err != nil { + return fmt.Errorf("carry the existing file's access control list: %w", err) + } + return nil +} + +// createSideFile creates the side file an overwrite or a create stages its +// bytes in, and returns it with its path relative to root. +// +// A create has no original and takes what the directory gives a new file. An +// overwrite that carries access control must not let the side file exist under +// the directory's list even while it is empty: access is granted when a file +// is opened and is not taken back when its list changes, so anyone the +// directory admits could open the empty side file and then read the +// replacement through that handle. Its side file is therefore born readable +// by the current user alone, and is given the replaced file's list afterwards. +func createSideFile(root *os.Root, relativePath string, mode os.FileMode, security *fileSecurity) (*os.File, string, error) { + directory := filepath.Dir(relativePath) + if security == nil { + return pathjail.CreateTempMode(root, directory, "zero-write", ".tmp", mode) + } + return createPrivateSideFile(root, directory) +} + +// createPrivateSideFile creates a uniquely named file in directory whose +// access control list, from the moment it exists, admits only the current +// user. The name is created relative to the directory's own handle and is a +// single component, so nothing is resolved by path. +func createPrivateSideFile(root *os.Root, directory string) (*os.File, string, error) { + user, err := windows.GetCurrentProcessToken().GetTokenUser() + if err != nil { + return nil, "", fmt.Errorf("identify the current user: %w", err) + } + descriptor, err := windows.SecurityDescriptorFromString("D:P(A;;FA;;;" + user.User.Sid.String() + ")") + if err != nil { + return nil, "", fmt.Errorf("build the side file's access control list: %w", err) + } + parent, err := root.Open(directory) + if err != nil { + return nil, "", err + } + defer parent.Close() + raw, err := parent.SyscallConn() + if err != nil { + return nil, "", err + } + for attempt := 0; attempt < 10; attempt++ { + noise := make([]byte, 8) + if _, err := rand.Read(noise); err != nil { + return nil, "", fmt.Errorf("generate a side file name: %w", err) + } + name := "zero-write." + hex.EncodeToString(noise) + ".tmp" + var handle windows.Handle + var createErr error + if err := raw.Control(func(parentHandle uintptr) { + objectName, nameErr := windows.NewNTUnicodeString(name) + if nameErr != nil { + createErr = nameErr + return + } + createErr = windows.NtCreateFile( + &handle, + windows.FILE_GENERIC_READ|windows.FILE_GENERIC_WRITE|windows.DELETE|windows.READ_CONTROL|windows.WRITE_DAC, + &windows.OBJECT_ATTRIBUTES{ + Length: uint32(unsafe.Sizeof(windows.OBJECT_ATTRIBUTES{})), + RootDirectory: windows.Handle(parentHandle), + ObjectName: objectName, + Attributes: windows.OBJ_CASE_INSENSITIVE | windows.OBJ_DONT_REPARSE, + SecurityDescriptor: descriptor, + }, + &windows.IO_STATUS_BLOCK{}, + nil, + windows.FILE_ATTRIBUTE_NORMAL, + windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE|windows.FILE_SHARE_DELETE, + windows.FILE_CREATE, + windows.FILE_NON_DIRECTORY_FILE|windows.FILE_SYNCHRONOUS_IO_NONALERT, + 0, + 0, + ) + }); err != nil { + return nil, "", err + } + if createErr == nil { + relative := filepath.Join(directory, name) + return os.NewFile(uintptr(handle), relative), relative, nil + } + if errors.Is(createErr, windows.STATUS_OBJECT_NAME_COLLISION) { + continue + } + return nil, "", createErr + } + return nil, "", errors.New("could not create a side file with an unused name") +} + +// reopenFileForSecurity opens the same file object again with the rights a +// security query or update needs. The handles this package holds come from +// os.Root, which opens for data access only. An empty name relative to the +// existing handle reopens that object itself, with no path to resolve again. +func reopenFileForSecurity(file *os.File, access uint32) (windows.Handle, error) { + raw, err := file.SyscallConn() + if err != nil { + return 0, err + } + var handle windows.Handle + var openErr error + if err := raw.Control(func(rawHandle uintptr) { + objectName, nameErr := windows.NewNTUnicodeString("") + if nameErr != nil { + openErr = nameErr + return + } + openErr = windows.NtCreateFile( + &handle, + access|windows.FILE_READ_ATTRIBUTES|windows.SYNCHRONIZE, + &windows.OBJECT_ATTRIBUTES{ + Length: uint32(unsafe.Sizeof(windows.OBJECT_ATTRIBUTES{})), + RootDirectory: windows.Handle(rawHandle), + ObjectName: objectName, + Attributes: windows.OBJ_CASE_INSENSITIVE, + }, + &windows.IO_STATUS_BLOCK{}, + nil, + 0, + windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE|windows.FILE_SHARE_DELETE, + windows.FILE_OPEN, + windows.FILE_NON_DIRECTORY_FILE|windows.FILE_SYNCHRONOUS_IO_NONALERT|windows.FILE_OPEN_REPARSE_POINT, + 0, + 0, + ) + }); err != nil { + return 0, err + } + if openErr != nil { + return 0, openErr + } + return handle, nil +} diff --git a/internal/tools/file_commit_security_windows_test.go b/internal/tools/file_commit_security_windows_test.go new file mode 100644 index 000000000..c85bccc43 --- /dev/null +++ b/internal/tools/file_commit_security_windows_test.go @@ -0,0 +1,310 @@ +//go:build windows + +package tools + +import ( + "context" + "io" + "os" + "path/filepath" + "strings" + "testing" + + "golang.org/x/sys/windows" +) + +func currentUserSIDString(t *testing.T) string { + t.Helper() + user, err := windows.GetCurrentProcessToken().GetTokenUser() + if err != nil { + t.Fatalf("read the current user: %v", err) + } + return user.User.Sid.String() +} + +func setTestFileDACL(t *testing.T, path string, sddl string, protected bool) { + t.Helper() + descriptor, err := windows.SecurityDescriptorFromString(sddl) + if err != nil { + t.Fatalf("parse %q: %v", sddl, err) + } + dacl, _, err := descriptor.DACL() + if err != nil { + t.Fatalf("decode %q: %v", sddl, err) + } + information := windows.SECURITY_INFORMATION(windows.DACL_SECURITY_INFORMATION) + if protected { + information |= windows.SECURITY_INFORMATION(windows.PROTECTED_DACL_SECURITY_INFORMATION) + } else { + information |= windows.SECURITY_INFORMATION(windows.UNPROTECTED_DACL_SECURITY_INFORMATION) + } + if err := windows.SetNamedSecurityInfo(path, windows.SE_FILE_OBJECT, information, nil, nil, dacl, nil); err != nil { + t.Fatalf("set the access control list on %s: %v", path, err) + } +} + +// renderedTestDACL returns sddl the way a list read back from a file is +// printed. The printed form names some accounts by a two-letter alias in place +// of the identifier they were written with: the built-in administrator account +// a hosted Windows runner uses comes back as LA. An expectation built from the +// raw identifier therefore matches on a developer's machine and not there. +func renderedTestDACL(t *testing.T, sddl string) string { + t.Helper() + descriptor, err := windows.SecurityDescriptorFromString(sddl) + if err != nil { + t.Fatalf("parse %q: %v", sddl, err) + } + return descriptor.String() +} + +// testDACLEntries returns the entries of a printed list without the flags in +// front of them, which say how the list was set and not who it admits. +func testDACLEntries(sddl string) string { + start := strings.Index(sddl, "(") + if start < 0 { + return "" + } + return sddl[start:] +} + +// testFileDACL returns the file's access control list as SDDL, and whether it +// is protected from inheritance. +func testFileDACL(t *testing.T, path string) (string, bool) { + t.Helper() + descriptor, err := windows.GetNamedSecurityInfo(path, windows.SE_FILE_OBJECT, windows.DACL_SECURITY_INFORMATION) + if err != nil { + t.Fatalf("read the access control list of %s: %v", path, err) + } + control, _, err := descriptor.Control() + if err != nil { + t.Fatalf("read the access control flags of %s: %v", path, err) + } + return descriptor.String(), control&windows.SE_DACL_PROTECTED != 0 +} + +// AN OVERWRITE KEEPS THE ACCESS CONTROL OF THE FILE IT REPLACES. +// +// Publishing an overwrite by rename replaced the file with one that had only +// the directory's inherited access control. A file with an extra entry lost +// it, and a file whose owner had removed inheritance and kept access to +// themselves came back readable by everyone the directory allows. Both tools +// that publish through the rename are checked, against the list read back from +// the file itself. +func TestOverwriteKeepsTheReplacedFilesAccessControl(t *testing.T) { + me := currentUserSIDString(t) + for _, layout := range []struct { + name string + sddl string + protected bool + }{ + {name: "an explicit entry beside the inherited ones", sddl: "D:(A;;FA;;;" + me + ")(A;;FR;;;WD)"}, + {name: "inheritance removed, owner only", sddl: "D:P(A;;FA;;;" + me + ")", protected: true}, + } { + for _, tool := range []struct { + name string + run func(root string) Result + }{ + {name: "write_file", run: func(root string) Result { + return NewScopedWriteFileTool(root, nil).Run(context.Background(), map[string]any{ + "path": "kept.txt", "content": "replacement\n", "overwrite": true, + }) + }}, + {name: "edit_file", run: func(root string) Result { + return NewScopedEditFileTool(root, nil).Run(context.Background(), map[string]any{ + "path": "kept.txt", "old_string": "observed", "new_string": "replacement", + }) + }}, + } { + t.Run(layout.name+"/"+tool.name, func(t *testing.T) { + root := t.TempDir() + path := filepath.Join(root, "kept.txt") + if err := os.WriteFile(path, []byte("observed\n"), 0o644); err != nil { + t.Fatal(err) + } + setTestFileDACL(t, path, layout.sddl, layout.protected) + before, protectedBefore := testFileDACL(t, path) + if protectedBefore != layout.protected { + t.Fatalf("SETUP INVALID: protected = %v after setting %q", protectedBefore, layout.sddl) + } + if !layout.protected && !strings.Contains(before, "(A;;FR;;;WD)") { + t.Fatalf("SETUP INVALID: the explicit entry is missing from %q", before) + } + + result := tool.run(root) + if result.Status != StatusOK { + t.Fatalf("%s = %s: %s", tool.name, result.Status, result.Output) + } + content, err := os.ReadFile(path) + if err != nil || string(content) != "replacement\n" { + t.Fatalf("content = %q, err=%v; the overwrite did not land", content, err) + } + after, protectedAfter := testFileDACL(t, path) + if after != before || protectedAfter != protectedBefore { + t.Fatalf("access control changed across the overwrite:\n before: %s (protected=%v)\n after: %s (protected=%v)", + before, protectedBefore, after, protectedAfter) + } + }) + } + } +} + +// openFileDACL returns the access control list of an open file as SDDL, and +// whether it is protected from inheritance, without going through its name. +func openFileDACL(t *testing.T, file *os.File) (string, bool) { + t.Helper() + handle, err := reopenFileForSecurity(file, windows.READ_CONTROL) + if err != nil { + t.Fatalf("reopen the staged file: %v", err) + } + defer windows.CloseHandle(handle) + descriptor, err := windows.GetSecurityInfo(handle, windows.SE_FILE_OBJECT, windows.DACL_SECURITY_INFORMATION) + if err != nil { + t.Fatalf("read the staged file's access control list: %v", err) + } + control, _, err := descriptor.Control() + if err != nil { + t.Fatalf("read the staged file's access control flags: %v", err) + } + return descriptor.String(), control&windows.SE_DACL_PROTECTED != 0 +} + +// THE REPLACEMENT IS NEVER READABLE BY SOMEONE THE ORIGINAL EXCLUDED. +// +// The side file is born with the directory's access control. If the directory +// lets everyone read and the file being replaced was kept to its owner, the +// replacement bytes must not sit in that side file under the directory's list +// even for a moment. So the original's list goes on while the side file is +// still empty, and this looks at the side file at the instant its bytes are +// written. +func TestStagedBytesAreWrittenUnderTheReplacedFilesAccessControl(t *testing.T) { + me := currentUserSIDString(t) + root := t.TempDir() + // Everything created in this directory inherits read access for everyone. + setTestFileDACL(t, root, "D:P(A;OICI;FA;;;"+me+")(A;OICI;FR;;;WD)", true) + path := filepath.Join(root, "private.txt") + if err := os.WriteFile(path, []byte("observed\n"), 0o644); err != nil { + t.Fatal(err) + } + inherited, _ := testFileDACL(t, path) + if !strings.Contains(inherited, ";;;WD)") { + t.Fatalf("SETUP INVALID: a file created here does not inherit the everyone entry: %q", inherited) + } + setTestFileDACL(t, path, "D:P(A;;FA;;;"+me+")", true) + want, _ := testFileDACL(t, path) + + writes := 0 + var atWrite string + var protectedAtWrite bool + var sizeAtWrite int64 + installFileWriteTempWrite(t, func(file *os.File, content string) error { + writes++ + atWrite, protectedAtWrite = openFileDACL(t, file) + if info, err := file.Stat(); err == nil { + sizeAtWrite = info.Size() + } + _, err := io.WriteString(file, content) + return err + }) + + result := NewScopedWriteFileTool(root, nil).Run(context.Background(), map[string]any{ + "path": "private.txt", "content": "replacement\n", "overwrite": true, + }) + if result.Status != StatusOK { + t.Fatalf("overwrite = %s: %s", result.Status, result.Output) + } + if writes != 1 { + t.Fatalf("SETUP INVALID: the side file write ran %d times, want once", writes) + } + if sizeAtWrite != 0 { + t.Fatalf("SETUP INVALID: the side file already held %d bytes when the write seam ran", sizeAtWrite) + } + if strings.Contains(atWrite, ";;;WD)") || !protectedAtWrite || atWrite != want { + t.Fatalf("the side file was written under the wrong access control:\n at write: %s (protected=%v)\n original: %s", + atWrite, protectedAtWrite, want) + } +} + +// NOBODY ELSE CAN OPEN THE SIDE FILE, FROM THE MOMENT IT EXISTS. +// +// Putting the original's list on an empty side file is not enough by itself. +// Access is granted when a file is opened and is not taken back when its list +// changes, so a side file that existed for an instant under the directory's +// list could be opened in that instant and read through that handle later. +// The side file is therefore created admitting the current user alone. +// +// Here the directory and the replaced file both let everyone read, so neither +// inheritance nor the carried list can explain a private side file: only the +// way it was created can. The list is read at the point the original's list is +// about to be applied, which is the earliest the side file can be observed. +func TestOverwriteSideFileIsPrivateFromBirth(t *testing.T) { + me := currentUserSIDString(t) + root := t.TempDir() + setTestFileDACL(t, root, "D:P(A;OICI;FA;;;"+me+")(A;OICI;FR;;;WD)", true) + path := filepath.Join(root, "shared.txt") + if err := os.WriteFile(path, []byte("observed\n"), 0o644); err != nil { + t.Fatal(err) + } + setTestFileDACL(t, path, "D:P(A;;FA;;;"+me+")(A;;FR;;;WD)", true) + want, _ := testFileDACL(t, path) + if !strings.Contains(want, ";;;WD)") { + t.Fatalf("SETUP INVALID: the replaced file does not admit everyone: %q", want) + } + + calls := 0 + var atBirth string + var protectedAtBirth bool + installFileWriteSecurity(t, nil, func(file *os.File, security *fileSecurity) error { + calls++ + atBirth, protectedAtBirth = openFileDACL(t, file) + return applyFileSecurity(file, security) + }) + + result := NewScopedWriteFileTool(root, nil).Run(context.Background(), map[string]any{ + "path": "shared.txt", "content": "replacement\n", "overwrite": true, + }) + if result.Status != StatusOK { + t.Fatalf("overwrite = %s: %s", result.Status, result.Output) + } + if calls != 1 { + t.Fatalf("SETUP INVALID: the access control seam ran %d times, want once", calls) + } + private := testDACLEntries(renderedTestDACL(t, "D:P(A;;FA;;;"+me+")")) + if !protectedAtBirth || testDACLEntries(atBirth) != private { + t.Fatalf("the side file was not private when it was created: %s (protected=%v); want the one entry %s, for the current user", + atBirth, protectedAtBirth, private) + } + after, _ := testFileDACL(t, path) + if after != want { + t.Fatalf("the published file's access control changed:\n before: %s\n after: %s", want, after) + } +} + +// A VOLUME THAT KEEPS NO ACCESS CONTROL LISTS HAS NOTHING TO CARRY. +// +// FAT and exFAT volumes store none, and asking one to take a list fails. The +// overwrite must still work there, carrying nothing. +func TestOverwriteOnAVolumeWithoutAccessControlListsCarriesNothing(t *testing.T) { + prior := fileVolumeKeepsACLs + fileVolumeKeepsACLs = func(windows.Handle) (bool, error) { return false, nil } + t.Cleanup(func() { fileVolumeKeepsACLs = prior }) + var applied []*fileSecurity + installFileWriteSecurity(t, nil, func(_ *os.File, security *fileSecurity) error { + applied = append(applied, security) + return nil + }) + + root := t.TempDir() + path := filepath.Join(root, "kept.txt") + if err := os.WriteFile(path, []byte("observed\n"), 0o644); err != nil { + t.Fatal(err) + } + result := NewScopedWriteFileTool(root, nil).Run(context.Background(), map[string]any{ + "path": "kept.txt", "content": "replacement\n", "overwrite": true, + }) + if result.Status != StatusOK { + t.Fatalf("overwrite = %s: %s", result.Status, result.Output) + } + if len(applied) != 1 || applied[0] != nil { + t.Fatalf("the side file was handed %v; a volume without access control lists has none to carry", applied) + } +}