Created
April 5, 2023 12:10
-
-
Save gabriel-samfira/7ecf38640651d4246f4e1e1ec759ab5f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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