func enablePrivilege()

in google_guest_agent/uefi/uefi_windows.go [120:178]


func enablePrivilege(name string) error {
	// Get current process handle.
	handle, _, err := procGetCurrentProcess.Call()
	if handle == uintptr(0) {
		return fmt.Errorf("unable to get current process handle: %w", err)
	}
	defer procCloseHandle.Call(handle)

	// Get access token that contains the privileges to be modified for the current process.
	var tHandle uintptr
	opRes, _, err := procOpenProcessToken.Call(
		uintptr(handle),
		uintptr(uint32(PROC_TOKEN_ADJUST_PRIVILEGES)),
		uintptr(unsafe.Pointer(&tHandle)),
	)
	if opRes == uintptr(0) {
		return fmt.Errorf("unable to open current process token: %w", err)
	}
	defer procCloseHandle.Call(tHandle)

	// Generate a pointer to a null-terminated string that specifies the name of the privilege.
	namePtr, err := syscall.UTF16PtrFromString(name)
	if err != nil {
		return fmt.Errorf("unable to encode privilege name(%s) to UTF16: %w", name, err)
	}

	// Retrieve the LUID for the required privilege.
	var luid LUID
	lpRes, _, err := procLookupPrivilegeValueW.Call(
		uintptr(0),
		uintptr(unsafe.Pointer(namePtr)),
		uintptr(unsafe.Pointer(&luid)),
	)
	if lpRes == uintptr(0) {
		return fmt.Errorf("unable to lookup LUID for privilege %q: %w", name, err)
	}

	newState := TOKEN_PRIVILEGES{PrivilegeCount: 1}

	newState.Privileges[0] = LUID_AND_ATTRIBUTES{
		LUID:       luid,
		Attributes: PROC_SE_PRIVILEGE_ENABLED,
	}

	// Enable specified privilege on the current process.
	ajRes, _, err := procAdjustTokenPrivileges.Call(
		uintptr(tHandle),
		uintptr(uint32(0)),
		uintptr(unsafe.Pointer(&newState)),
		uintptr(uint32(0)),
		uintptr(0),
		uintptr(0),
	)
	if ajRes == uintptr(0) {
		return fmt.Errorf("unable to set privilege %q: %w", name, err)
	}

	return nil
}