//go:build windows package fileops import ( "os" "unsafe" "golang.org/x/sys/windows" ) // CreatePrivateFile applies a protected DACL at creation before bytes are written. func CreatePrivateFile(path string) (*os.File, error) { user, err := windows.GetCurrentProcessToken().GetTokenUser() if err != nil { return nil, err } // Apply a protected DACL at creation, before any handle can read key bytes. // Chmod(0600) does not restrict Windows ACLs, and changing the DACL after // creation cannot revoke a read handle opened in the intervening window. // Elevated tokens can default the owner to Administrators. Bind the owner // explicitly so metadata-preserving publication cannot silently change a // user-owned config to that default group owner. sid := user.User.Sid.String() sd, err := windows.SecurityDescriptorFromString("O:" + sid + "D:P(A;;FA;;;SY)(A;;FA;;;BA)(A;;FA;;;" + sid + ")") if err != nil { return nil, err } name, err := windows.UTF16PtrFromString(path) if err != nil { return nil, err } attributes := windows.SecurityAttributes{SecurityDescriptor: sd} attributes.Length = uint32(unsafe.Sizeof(attributes)) handle, err := windows.CreateFile(name, windows.GENERIC_WRITE, windows.FILE_SHARE_READ, &attributes, windows.CREATE_NEW, windows.FILE_ATTRIBUTE_NORMAL, 0) if err != nil { return nil, &os.PathError{Op: "create", Path: path, Err: err} } return os.NewFile(uintptr(handle), path), nil }