Skip to content

Instantly share code, notes, and snippets.

@gabriel-samfira
Created April 5, 2023 12:10
Show Gist options
  • Save gabriel-samfira/7ecf38640651d4246f4e1e1ec759ab5f to your computer and use it in GitHub Desktop.
Save gabriel-samfira/7ecf38640651d4246f4e1e1ec759ab5f to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"log"
"os"
"strings"
"github.com/Microsoft/go-winio"
"golang.org/x/sys/windows"
)
const (
seTakeOwnershipPrivilege = "SeTakeOwnershipPrivilege"
)
func main() {
if len(os.Args) != 3 {
fmt.Println("Usage: set_owner_windows.exe file_or_directory SID|USERNAME")
os.Exit(1)
}
if _, err := os.Stat(os.Args[1]); err != nil {
log.Fatal(err)
}
privileges := []string{winio.SeRestorePrivilege, seTakeOwnershipPrivilege}
if err := winio.EnableProcessPrivileges(privileges); err != nil {
fmt.Println(err)
os.Exit(3)
}
defer winio.DisableProcessPrivileges(privileges)
var sid *windows.SID
var err error
sidString := os.Args[2]
if len(sidString) >= 2 && !strings.EqualFold(string(sidString[:2]), "s-") {
sid, _, _, err = windows.LookupSID("", sidString)
if err != nil {
fmt.Println(err)
os.Exit(3)
}
} else {
sidPtr, err := windows.UTF16PtrFromString(sidString)
if err != nil {
fmt.Println(err)
os.Exit(3)
}
if err := windows.ConvertStringSidToSid(sidPtr, &sid); err != nil {
fmt.Println(err)
os.Exit(3)
}
}
if err := windows.SetNamedSecurityInfo(
os.Args[1], windows.SE_FILE_OBJECT,
windows.OWNER_SECURITY_INFORMATION,
sid, nil, nil, nil); err != nil {
fmt.Println(err)
os.Exit(3)
}
os.Exit(0)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment