gsudo

repository·master·Indexed 25 days ago

https://github.com/gerardog/gsudo

A 'sudo' equivalent for Windows that allows users to run commands or shells with elevated administrative privileges from consoles such as CMD, PowerShell, WSL, git-bash, MinGW, Cygwin, Yori, Take Command, and NuShell. It features a credentials cache to reduce UAC popups, a dedicated PowerShell module (gsudoModule) for advanced functionality, and support for script self-elevation.

Tokens
12.7K
Snippets
32
Records
86
Agent score
91%

What's inside gsudo

  1. Introduction to gsudo

    master

    Overview

    gsudo is a sudo equivalent for Windows, providing a user experience similar to the original *nix sudo. It allows you to run commands with elevated permissions or elevate your current shell within the same console window (or a new one if specified).

    Core Capabilities

    • Elevate Commands: Prepend gsudo (or the sudo alias) to any command to run it with elevated permissions.
    • In-place Execution: Elevated commands run in the current user-level console without opening a new window (unless the -n flag is used).
    • Shell Integration: gsudo uses your current shell to interpret commands. For example, in PowerShell, gsudo mkdir x executes pwsh -c "mkdir x".
    • Script Support:
      • Returns the command's exit code via %errorlevel%.
      • If elevation fails, it returns exit code 999.
      • If already running in an elevated console, gsudo runs the command as-is without requiring further elevation or showing a UAC popup.
    • Last Command Elevation: Use gsudo !! to elevate the last command executed (supported in CMD, Git-Bash, MinGW, MSYS2, Cygwin, and PowerShell with the gsudo module installed).
  2. Understand gsudo elevation modes

    master

    gsudo uses four different mechanisms to achieve elevation, each with different trade-offs regarding console functionality, redirection, and environment variables.

    • TokenSwitch Mode (Default): Uses undocumented kernel32 APIs to replace the process token. It provides native console performance and supports redirection, but the process inherits the non-elevated environment variables. If elevating as a different user, it may fall back to Attached or Piped mode.
    • Attached mode: The elevated window attaches to the non-elevated console via Windows/ConHost. It offers native console speed and no encoding issues but does not support I/O redirection.
    • VT mode (PseudoConsole): Runs a VT PseudoConsole and sends I/O via named pipes. It provides a full-featured console screen and full input support, but has slightly lower performance and struggles with encoding changes.
    • Piped mode: A basic mechanism where I/O is redirected through named pipes. It supports redirection but has poor input support (characters only, no key presses like <kbd>TAB</kbd>) and struggles with encoding.
  3. Compare gsudo and Microsoft sudo features

    master

    Key Advantages of gsudo:

    • Shell Integration: Can elevate the current shell or elevate commands using the current shell context.
    • User Experience: Supports a Credentials Cache to reduce UAC pop-ups and provides a red # indicator for elevation in CMD.
    • Advanced Execution: Supports sudo !! to elevate the last command and provides options to keep new windows open or keep the shell open after elevation.
    • Compatibility: Works on Windows 7 SP1 through Windows 11, including support for Win11 Administration Protection.
  4. Perform multiple elevations using gsudo cache

    master

    To avoid repeated UAC (User Account Control) prompts when running multiple elevated commands in sequence, you can leverage the gsudo credentials cache. This allows subsequent commands to run elevated without triggering a new interactive popup.

    Sample scripts demonstrating this pattern include:

    • many-elevations-using-gsudo-cache.cmd (Batch)
    • many-elevations-using-gsudo-cache.ps1 (PowerShell)
  5. Use gsudo from WSL to elevate Windows privileges

    master

    On WSL, the Linux root user is distinct from Windows Administrator privileges. To perform Windows-level administrative tasks from a WSL terminal, you must elevate the WSL.EXE process using gsudo.

    • To elevate WSL commands (Linux-native commands), prepend gsudo to the command.
    • To run Windows commands (CMD/Windows-native commands), use the -d flag with gsudo.
    # elevate default shell
    PC:~$ gsudo 
    
    # run elevated WSL command
    PC:~$ gsudo mkdir /mnt/c/Windows/MyFolder
    
    # run elevated Windows command
    PC:~$ gsudo -d notepad C:/Windows/System32/drivers/etc/hosts
  6. Implement self-elevation in PowerShell scripts

    master

    To make a PowerShell script self-elevating, use a helper function to check the current Windows Principal role. If not elevated, call gsudo to re-run the script's source path with the original arguments.

    function Test-IsElevated {
      return (New-Object Security.Principal.WindowsPrincipal(
        [Security.Principal.WindowsIdentity]::GetCurrent()))
        .IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
    }
    
    if ((Test-IsElevated) -eq $false) {
      Write-Warning "This script requires local admin privileges. Elevating..."
      gsudo "& '$($MyInvocation.MyCommand.Source)'" $args
      if ($LastExitCode -eq 999 ) {
        Write-error 'Failed to elevate.'
      }
      return
    }
    
    # You are elevated. Do admin stuff here.
  7. Install the gsudo PowerShell Module for enhanced features

    master

    To enable tab-key auto-completion for parameters and the gsudo !! shortcut (which elevates the last executed command), add the gsudoModule.psd1 to your PowerShell $PROFILE.

    Installation: Replace the path below with the actual path to the module on your system.

    Import-Module 'C:\path\to\gsudoModule.psd1'

    Automated Installation: Run this command to append the import to your profile automatically:

    Write-Output "\nImport-Module `"gsudoModule`"" | Add-Content $PROFILE
  8. Mitigate console hijacking risks with -n/--new or SecurityEnforceUacIsolation

    master

    When gsudo elevates in the same console, a medium-integrity process could potentially drive the high-integrity process (e.g., by sending keystrokes or screen scraping).

    To mitigate this risk, you can:

    1. Elevate in a new console: Use the -n or --new flag for individual commands to ensure the elevated process runs in a separate window.
    2. Use the experimental security setting: Enable SecurityEnforceUacIsolation to make the elevated command run redirected with input redirected to NULL. This makes the command non-interactive and prevents it from being driven by other processes.

    To enable the experimental setting, use:

    gsudo config SecurityEnforceUacIsolation true
    gsudo config SecurityEnforceUacIsolation true
  9. Elevate the current shell on demand

    master

    Instead of creating dedicated elevated profiles, you can elevate your existing session or specific commands within a window using gsudo:

    • To elevate the entire current shell: Run gsudo by itself. This will invoke your current caller shell (such as CMD or PowerShell) with elevated privileges in the same window.
    • To elevate a specific command: Prepend gsudo to the command you wish to run with elevated privileges.
  10. Install gsudo on Windows 10/11

    master

    You can install gsudo using common Windows package managers or via direct download/script.

    Using Package Managers

    • WinGet: winget install gerardog.gsudo
    • Chocolatey: choco install gsudo
    • Scoop: scoop install gsudo

    Manual Installation

    • MSI Installer: Download and run the .msi file from the latest release.
    • PowerShell Script: Run the following command to download and install automatically:
      PowerShell -Command "Set-ExecutionPolicy RemoteSigned -scope Process; [Net.ServicePointManager]::SecurityProtocol = 'Tls12'; iwr -useb https://raw.githubusercontent.com/gerardog/gsudo/master/installgsudo.ps1 | iex"
    • ZIP File: Download the .zip file from the latest release, uncompress it, and manually add the directory to your PATH.

    Note: Please restart your consoles after installation to refresh the PATH environment variable.

    winget install gerardog.gsudo