How to Sign Out a User from Windows Service with Elevated Permissions Without Using psexec.exe?

I’m developing a Windows Service that needs to sign out a user from their session. However, I’m encountering an issue where the service does not have the necessary elevated permissions to log out the user on their behalf.

I understand that psexec.exe can be used to run commands with elevated privileges, which could help in signing out the user, but I would prefer not to rely on external tools like psexec.exe in my solution. Instead, I want to implement a function within my own code to achieve this.

I tried something using go but getting below error:
Failed to run command in user session: failed to query user token: A required privilege is not held by the client.

Here are the specifics of my use case:

  • The service runs under a standard system account.
  • I need to sign out the user from their session programmatically.
  • The goal is to achieve this without integrating psexec.exe or similar external tools.

Is there a way to accomplish this using native Windows APIs or any other method within my code? If so, could you provide guidance or examples on how to implement such functionality?

Thank you!

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>package main
import (
"fmt"
"log"
"strings"
"syscall"
"unsafe"
"golang.org/x/sys/windows"
)
const (
SE_DEBUG_NAME = "SeDebugPrivilege"
SE_IMPERSONATE_NAME = "SeImpersonatePrivilege"
)
func main() {
// Attempt to get the SYSTEM token using specific SYSTEM processes
token, err := getSystemToken()
if err != nil {
log.Fatalf("Failed to get SYSTEM token: %v", err)
}
defer token.Close()
log.Println("Successfully obtained SYSTEM token", token)
// Ensure necessary privileges
if err := enablePrivilege(token, SE_DEBUG_NAME); err != nil {
log.Fatalf("Failed to enable SeDebugPrivilege: %v", err)
}
if err := enablePrivilege(token, SE_IMPERSONATE_NAME); err != nil {
log.Fatalf("Failed to enable SeImpersonatePrivilege: %v", err)
}
// Run a command as SYSTEM user, for example, open notepad
err = runCommandAsSystem(token, `C:WindowsSystem32cmd.exe`, "/C", "start", "notepad.exe")
if err != nil {
log.Fatalf("Failed to run command as SYSTEM: %v", err)
}
}
func getSystemToken() (windows.Token, error) {
// Specific SYSTEM processes like winlogon.exe or lsass.exe
processes := []string{"winlogon.exe", "lsass.exe"}
for _, process := range processes {
pid, err := findProcessByName(process)
if err != nil {
log.Printf("Failed to find process %s: %v", process, err)
continue
}
hProcess, err := windows.OpenProcess(windows.PROCESS_QUERY_INFORMATION, false, pid)
if err != nil {
log.Printf("Failed to open system process (PID %d - %s): %v", pid, process, err)
continue
}
defer windows.CloseHandle(hProcess)
var systemToken windows.Token
err = windows.OpenProcessToken(hProcess, windows.TOKEN_DUPLICATE|windows.TOKEN_QUERY|windows.TOKEN_ASSIGN_PRIMARY, &systemToken)
if err != nil {
log.Printf("Failed to get system token from process (PID %d - %s): %v", pid, process, err)
continue
}
return systemToken, nil
}
return 0, fmt.Errorf("all attempts to retrieve SYSTEM token failed")
}
func findProcessByName(name string) (uint32, error) {
snapshot, err := windows.CreateToolhelp32Snapshot(windows.TH32CS_SNAPPROCESS, 0)
if err != nil {
return 0, fmt.Errorf("failed to create process snapshot: %v", err)
}
defer windows.CloseHandle(snapshot)
var entry windows.ProcessEntry32
entry.Size = uint32(unsafe.Sizeof(entry))
err = windows.Process32First(snapshot, &entry)
for err == nil {
if syscall.UTF16ToString(entry.ExeFile[:]) == name {
return entry.ProcessID, nil
}
err = windows.Process32Next(snapshot, &entry)
}
return 0, fmt.Errorf("process not found")
}
func enablePrivilege(token windows.Token, privilegeName string) error {
var luid windows.LUID
privilegeNamePtr, err := syscall.UTF16PtrFromString(privilegeName)
if err != nil {
return fmt.Errorf("failed to convert privilege name to UTF-16: %v", err)
}
err = windows.LookupPrivilegeValue(nil, privilegeNamePtr, &luid)
if err != nil {
return fmt.Errorf("failed to lookup privilege value: %v", err)
}
tokenPrivileges := windows.Tokenprivileges{
PrivilegeCount: 1,
Privileges: [1]windows.LUIDAndAttributes{
{
Luid: luid,
Attributes: windows.SE_PRIVILEGE_ENABLED,
},
},
}
err = windows.AdjustTokenPrivileges(
token,
false,
&tokenPrivileges,
0,
nil,
nil,
)
if err != nil {
return fmt.Errorf("failed to adjust token privileges: %v", err)
}
return nil
}
func runCommandAsSystem(token windows.Token, command string, args ...string) error {
// Convert command and arguments to Windows UTF-16
cmdPtr, err := syscall.UTF16PtrFromString(command)
if err != nil {
return err
}
cmdLine := command + " " + strings.Join(args, " ")
cmdLinePtr, err := syscall.UTF16PtrFromString(cmdLine)
if err != nil {
return err
}
// Create the process in the SYSTEM account
startupInfo := new(windows.StartupInfo)
processInfo := new(windows.ProcessInformation)
err = windows.CreateProcessAsUser(
token,
cmdPtr,
cmdLinePtr,
nil,
nil,
false,
0,
nil,
nil,
startupInfo,
processInfo,
)
if err != nil {
return err
}
defer windows.CloseHandle(processInfo.Process)
defer windows.CloseHandle(processInfo.Thread)
log.Printf("Command executed with PID %d", processInfo.ProcessId)
return nil
}
</code>
<code>package main import ( "fmt" "log" "strings" "syscall" "unsafe" "golang.org/x/sys/windows" ) const ( SE_DEBUG_NAME = "SeDebugPrivilege" SE_IMPERSONATE_NAME = "SeImpersonatePrivilege" ) func main() { // Attempt to get the SYSTEM token using specific SYSTEM processes token, err := getSystemToken() if err != nil { log.Fatalf("Failed to get SYSTEM token: %v", err) } defer token.Close() log.Println("Successfully obtained SYSTEM token", token) // Ensure necessary privileges if err := enablePrivilege(token, SE_DEBUG_NAME); err != nil { log.Fatalf("Failed to enable SeDebugPrivilege: %v", err) } if err := enablePrivilege(token, SE_IMPERSONATE_NAME); err != nil { log.Fatalf("Failed to enable SeImpersonatePrivilege: %v", err) } // Run a command as SYSTEM user, for example, open notepad err = runCommandAsSystem(token, `C:WindowsSystem32cmd.exe`, "/C", "start", "notepad.exe") if err != nil { log.Fatalf("Failed to run command as SYSTEM: %v", err) } } func getSystemToken() (windows.Token, error) { // Specific SYSTEM processes like winlogon.exe or lsass.exe processes := []string{"winlogon.exe", "lsass.exe"} for _, process := range processes { pid, err := findProcessByName(process) if err != nil { log.Printf("Failed to find process %s: %v", process, err) continue } hProcess, err := windows.OpenProcess(windows.PROCESS_QUERY_INFORMATION, false, pid) if err != nil { log.Printf("Failed to open system process (PID %d - %s): %v", pid, process, err) continue } defer windows.CloseHandle(hProcess) var systemToken windows.Token err = windows.OpenProcessToken(hProcess, windows.TOKEN_DUPLICATE|windows.TOKEN_QUERY|windows.TOKEN_ASSIGN_PRIMARY, &systemToken) if err != nil { log.Printf("Failed to get system token from process (PID %d - %s): %v", pid, process, err) continue } return systemToken, nil } return 0, fmt.Errorf("all attempts to retrieve SYSTEM token failed") } func findProcessByName(name string) (uint32, error) { snapshot, err := windows.CreateToolhelp32Snapshot(windows.TH32CS_SNAPPROCESS, 0) if err != nil { return 0, fmt.Errorf("failed to create process snapshot: %v", err) } defer windows.CloseHandle(snapshot) var entry windows.ProcessEntry32 entry.Size = uint32(unsafe.Sizeof(entry)) err = windows.Process32First(snapshot, &entry) for err == nil { if syscall.UTF16ToString(entry.ExeFile[:]) == name { return entry.ProcessID, nil } err = windows.Process32Next(snapshot, &entry) } return 0, fmt.Errorf("process not found") } func enablePrivilege(token windows.Token, privilegeName string) error { var luid windows.LUID privilegeNamePtr, err := syscall.UTF16PtrFromString(privilegeName) if err != nil { return fmt.Errorf("failed to convert privilege name to UTF-16: %v", err) } err = windows.LookupPrivilegeValue(nil, privilegeNamePtr, &luid) if err != nil { return fmt.Errorf("failed to lookup privilege value: %v", err) } tokenPrivileges := windows.Tokenprivileges{ PrivilegeCount: 1, Privileges: [1]windows.LUIDAndAttributes{ { Luid: luid, Attributes: windows.SE_PRIVILEGE_ENABLED, }, }, } err = windows.AdjustTokenPrivileges( token, false, &tokenPrivileges, 0, nil, nil, ) if err != nil { return fmt.Errorf("failed to adjust token privileges: %v", err) } return nil } func runCommandAsSystem(token windows.Token, command string, args ...string) error { // Convert command and arguments to Windows UTF-16 cmdPtr, err := syscall.UTF16PtrFromString(command) if err != nil { return err } cmdLine := command + " " + strings.Join(args, " ") cmdLinePtr, err := syscall.UTF16PtrFromString(cmdLine) if err != nil { return err } // Create the process in the SYSTEM account startupInfo := new(windows.StartupInfo) processInfo := new(windows.ProcessInformation) err = windows.CreateProcessAsUser( token, cmdPtr, cmdLinePtr, nil, nil, false, 0, nil, nil, startupInfo, processInfo, ) if err != nil { return err } defer windows.CloseHandle(processInfo.Process) defer windows.CloseHandle(processInfo.Thread) log.Printf("Command executed with PID %d", processInfo.ProcessId) return nil } </code>
package main

import (
"fmt"
"log"
"strings"
"syscall"
"unsafe"

"golang.org/x/sys/windows"
)

const (
SE_DEBUG_NAME       = "SeDebugPrivilege"
SE_IMPERSONATE_NAME = "SeImpersonatePrivilege"
)

func main() {

// Attempt to get the SYSTEM token using specific SYSTEM processes
token, err := getSystemToken()
if err != nil {
    log.Fatalf("Failed to get SYSTEM token: %v", err)
}
defer token.Close()

log.Println("Successfully obtained SYSTEM token", token)

// Ensure necessary privileges
if err := enablePrivilege(token, SE_DEBUG_NAME); err != nil {
    log.Fatalf("Failed to enable SeDebugPrivilege: %v", err)
}

if err := enablePrivilege(token, SE_IMPERSONATE_NAME); err != nil {
    log.Fatalf("Failed to enable SeImpersonatePrivilege: %v", err)
}

// Run a command as SYSTEM user, for example, open notepad
err = runCommandAsSystem(token, `C:WindowsSystem32cmd.exe`, "/C", "start", "notepad.exe")
if err != nil {
    log.Fatalf("Failed to run command as SYSTEM: %v", err)
}
}

func getSystemToken() (windows.Token, error) {
// Specific SYSTEM processes like winlogon.exe or lsass.exe
processes := []string{"winlogon.exe", "lsass.exe"}

for _, process := range processes {
    pid, err := findProcessByName(process)
    if err != nil {
        log.Printf("Failed to find process %s: %v", process, err)
        continue
    }

    hProcess, err := windows.OpenProcess(windows.PROCESS_QUERY_INFORMATION, false, pid)
    if err != nil {
        log.Printf("Failed to open system process (PID %d - %s): %v", pid, process, err)
        continue
    }
    defer windows.CloseHandle(hProcess)

    var systemToken windows.Token
    err = windows.OpenProcessToken(hProcess, windows.TOKEN_DUPLICATE|windows.TOKEN_QUERY|windows.TOKEN_ASSIGN_PRIMARY, &systemToken)
    if err != nil {
        log.Printf("Failed to get system token from process (PID %d - %s): %v", pid, process, err)
        continue
    }

    return systemToken, nil
}

return 0, fmt.Errorf("all attempts to retrieve SYSTEM token failed")
 }

func findProcessByName(name string) (uint32, error) {
snapshot, err := windows.CreateToolhelp32Snapshot(windows.TH32CS_SNAPPROCESS, 0)
if err != nil {
    return 0, fmt.Errorf("failed to create process snapshot: %v", err)
}
defer windows.CloseHandle(snapshot)

var entry windows.ProcessEntry32
entry.Size = uint32(unsafe.Sizeof(entry))

err = windows.Process32First(snapshot, &entry)
for err == nil {
    if syscall.UTF16ToString(entry.ExeFile[:]) == name {
        return entry.ProcessID, nil
    }
    err = windows.Process32Next(snapshot, &entry)
}

return 0, fmt.Errorf("process not found")
} 

func enablePrivilege(token windows.Token, privilegeName string) error {
var luid windows.LUID
privilegeNamePtr, err := syscall.UTF16PtrFromString(privilegeName)
if err != nil {
    return fmt.Errorf("failed to convert privilege name to UTF-16: %v", err)
}

err = windows.LookupPrivilegeValue(nil, privilegeNamePtr, &luid)
if err != nil {
    return fmt.Errorf("failed to lookup privilege value: %v", err)
}

tokenPrivileges := windows.Tokenprivileges{
    PrivilegeCount: 1,
    Privileges: [1]windows.LUIDAndAttributes{
        {
            Luid:       luid,
            Attributes: windows.SE_PRIVILEGE_ENABLED,
        },
    },
}

err = windows.AdjustTokenPrivileges(
    token,
    false,
    &tokenPrivileges,
    0,
    nil,
    nil,
)
if err != nil {
    return fmt.Errorf("failed to adjust token privileges: %v", err)
}
return nil
 }

func runCommandAsSystem(token windows.Token, command string, args ...string) error {
// Convert command and arguments to Windows UTF-16
cmdPtr, err := syscall.UTF16PtrFromString(command)
if err != nil {
    return err
}

cmdLine := command + " " + strings.Join(args, " ")
cmdLinePtr, err := syscall.UTF16PtrFromString(cmdLine)
if err != nil {
    return err
}

// Create the process in the SYSTEM account
startupInfo := new(windows.StartupInfo)
processInfo := new(windows.ProcessInformation)

err = windows.CreateProcessAsUser(
    token,
    cmdPtr,
    cmdLinePtr,
    nil,
    nil,
    false,
    0,
    nil,
    nil,
    startupInfo,
    processInfo,
)
if err != nil {
    return err
}
defer windows.CloseHandle(processInfo.Process)
defer windows.CloseHandle(processInfo.Thread)

log.Printf("Command executed with PID %d", processInfo.ProcessId)
return nil
 }

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật