DEV Community

Henrique Goncalves
Henrique Goncalves

Posted on • Originally published at blog.hadenes.io on

How to Request Admin Permissions in Windows Through UAC with Golang

Originally posted at https://blog.hadenes.io/post/how-to-request-admin-permissions-in-windows-through-uac-with-golang/

In Windows, User Account Control (UAC) is a security feature that helps prevent unauthorized changes to the operating system. When an application requires elevated privileges to perform certain actions, UAC prompts the user for permission to proceed.

In this guide, we’ll show you how to request admin permissions in Windows through UAC using Golang.

So yeah, it’s basically sudo.

Requesting Admin Permissions

To request admin permissions in Windows through UAC with Golang, you’ll need to use the syscall and windows packages. Here’s how you can do it:


package main

import (
    "syscall"
    "time"
    "os"
    "strings"
    "fmt"
    "golang.org/x/sys/windows"
)

func becomeAdmin() {
    verb := "runas"
    exe, _ := os.Executable()
    cwd, _ := os.Getwd()
    args := strings.Join(os.Args[1:], " ")

    verbPtr, _ := syscall.UTF16PtrFromString(verb)
    exePtr, _ := syscall.UTF16PtrFromString(exe)
    cwdPtr, _ := syscall.UTF16PtrFromString(cwd)
    argPtr, _ := syscall.UTF16PtrFromString(args)

    var showCmd int32 = 1 //SW_NORMAL

    err := windows.ShellExecute(0, verbPtr, exePtr, argPtr, cwdPtr, showCmd)
    if err != nil {
        fmt.Println(err)
    }
}

func checkAdmin() bool {
    _, err := os.Open("\\\\.\\PHYSICALDRIVE0")

    return err == nil
}

Enter fullscreen mode Exit fullscreen mode

The becomeAdmin() function elevates the current executable to admin privileges. It retrieves the path and arguments of the current executable using os.Executable() and os.Args , respectively, and uses windows.ShellExecute() to run the executable with elevated privileges.

The checkAdmin() function checks if the current process is running with admin privileges. It does this by attempting to open the physical drive using os.Open(). If an error occurs, the function returns false.

To use these functions, you can call checkAdmin() to check if the current process is running with admin privileges. If not, call becomeAdmin() to elevate the current process:


if !checkAdmin() {
    becomeAdmin()

    time.Sleep(2 * time.Second)

    os.Exit(0)
}

Enter fullscreen mode Exit fullscreen mode

This will kill the original process and spawn a new one with admin privileges, so you likely want this to be the first thing to run.

Source

This guide is based on the Gist created by user jerblack , which can be found at https://gist.github.com/jerblack/d0eb182cc5a1c1d92d92a4c4fcc416c6.

Top comments (0)