Giter Club home page Giter Club logo

gsudo's Introduction

gsudo - a sudo for Windows

Join the chat at https://gitter.im/gsudo/community CI Build Chocolatey Downloads GitHub Downloads

gsudo is a sudo equivalent for Windows, with a similar user-experience as the original Unix/Linux sudo. Allows you to run a command (or re-launch your current shell) with elevated permissions, in the current console window or a new one.

Just prepend gsudo (or the sudo alias) to your command and it will run elevated. For PowerShell use this syntax: gsudo { ScriptBlock }

One UAC popup will appear each time. You can see less popups if you enable gsudo cache.

It detects your current shell and elevates your command as native shell commands. (Supports Cmd, PowerShell, WSL, git-bash, MinGW, Cygwin, Yori, Take Command, BusyBox & NuShell.)

Table of contents


⭐ Extended documentation available at: https://gerardog.github.io/gsudo/

Demo

gsudo demo

(with gsudo config CacheMode auto)


Features

  • Elevated commands are shown in the current console. No new window (unless you specify -n)

  • Credentials cache: gsudo can elevate many times showing only one UAC pop-up if the user opts-in to enable the cache.

  • Detects your current shell (Supports CMD, PowerShell, WSL, Bash for Windows (Git-Bash/MinGW/MSYS2/Cygwin), Yori, Take Command and NuShell), and elevates your command correctly.

  • Supports being used on scripts:

    • Outputs StdOut/StdErr can be piped or captured (e.g. gsudo dir | findstr /c:"bytes free" > FreeSpace.txt) and exit codes too (%errorlevel%). If gsudo fails to elevate, the exit code will be 999.
    • If gsudo is invoked from an already elevated console, it will just run the command (it won't fail). So, you don't have to worry if you run gsudo or a script that uses gsudo from an already elevated console. (The UAC popup will not appear, as no elevation is required)
  • gsudo !! elevates the last executed command. Works on CMD, Git-Bash, MinGW, Cygwin (and PowerShell with gsudo module only)

Installation

  • Using Scoop: scoop install gsudo
  • Using WinGet: winget install gerardog.gsudo
  • Using Chocolatey: choco install gsudo
  • Running this line: (script):
    PowerShell -Command "Set-ExecutionPolicy RemoteSigned -scope Process; [Net.ServicePointManager]::SecurityProtocol = 'Tls12'; iwr -useb https://raw.githubusercontent.com/gerardog/gsudo/master/installgsudo.ps1 | iex"
  • Portable:
    1. Download gsudo.portable.zip from the latest release
    2. Extract the folder corresponding to your processor architecture (x64, x86, or arm64) from the zip file to a suitable directory on your computer.
    3. Optionally, add that directory to your system's PATH environment variable if it's not already accessible.

Please restart all your console windows after installing to ensure that the PATH environment variable is refreshed.

Note: gsudo.exe is portable. No windows service is required or system change is done, except adding it to the Path.

Usage

gsudo [options]                  # Starts your current shell elevated
gsudo [options] {command} [args] # Runs {command} with elevated permissions
gsudo cache [on | off | help]    # Starts/Stops a credentials cache session. (less UAC popups)
gsudo status [--json | filter ]  # Shows current user, cache and console status.
gsudo !!                         # Re-run last command as admin. (YMMV)
New Window options:
 -n | --new            # Starts the command in a new console/window (and returns immediately).
 -w | --wait           # When in new console, wait for the command to end.
 --keepShell           # After running a command, keep the elevated shell open.
 --keepWindow          # After running a command in a new console, ask for keypress before closing the console/window.

Security options:
 -u | --user {usr}     # Run as the specified user. Asks for password. For local admins shows UAC unless '-i Medium'
 -i | --integrity {v}  # Specify integrity level: Untrusted, Low, Medium, MediumPlus, High (default), System
 -s | --system         # Run as Local System account (NT AUTHORITY\SYSTEM).
 --ti                  # Run as member of NT SERVICE\TrustedInstaller
 -k                    # Kills all cached credentials. The next time gsudo is run a UAC popup will be appear.

Shell related options:
 -d | --direct         # Skips Shell detection. Assume CMD shell or CMD {command}.
 --loadProfile         # When elevating PowerShell commands, load user profile.

Other options:
 --loglevel {val}      # Set minimum log level to display: All, Debug, Info, Warning, Error, None
 --debug               # Enable debug mode.
 --copyns              # Connect network drives to the elevated user. Warning: Verbose, interactive asks for credentials
 --copyev              # (deprecated) Copy environment variables to the elevated process. (not needed on default console mode)
 --chdir {dir}         # Change the current directory to {dir} before running the command.

Note: You can use anywhere the sudo alias created by the installers.

Examples:

gsudo   # elevates the current shell in the current console window (Supports Cmd/PowerShell/Pwsh Core/Yori/Take Command/git-bash/cygwin)
gsudo -n # launch the current shell elevated in a new console window
gsudo -n -w powershell ./Do-Something.ps1 # launch in new window and wait for exit
gsudo notepad %windir%\system32\drivers\etc\hosts # launch windows app

sudo notepad # sudo alias built-in

# redirect/pipe input/output/error example
gsudo dir | findstr /c:"bytes free" > FreeSpace.txt

gsudo config LogLevel "Error"          # Configure Reduced logging
gsudo config Prompt "$P [elevated]$G " # Configure a custom Elevated Prompt
gsudo config Prompt --reset            # Reset to default value

# Enable credentials cache (less UAC popups):
gsudo config CacheMode Auto

Usage from PowerShell / PowerShell Core

gsudo detects if invoked from PowerShell and elevates PS commands (unless -d is used to elevate CMD commands).

The command to elevate will run in a different process, so it can't access the parent $variables and scope.

To elevate a commands or script block: Wrap it in {curly braces}.

# Syntax:
gsudo { ScriptBlock }
gsudo [options] { ScriptBlock } [-args $argument1[..., $argumentN]] ;

# Examples:
gsudo { Write-Output "Hello World" }

# Pass arguments with -args
$MyString = "Hello World"
gsudo { Write-Output $args[0] } -args $MyString  

# Output is serialized as PSObjects with properties.
$services = gsudo { Get-Service 'WSearch', 'Winmgmt'} 
Write-Output $services.DisplayName

# Inputs too: Example elevated iteration of a list.
Get-ChildItem . | gsudo { $Input.CreationTime}

Alternative syntaxes:

2. Invoke-gsudo wrapper function: (much slower)
# Pass values (not variables by reference) by prefixing `$using:`. I.E.

$MyString = "Hello World"
Invoke-Gsudo { Write-Output $using:MyString }  

# Syntax:
Invoke-Gsudo [-ScriptBlock] <ScriptBlock> 
             [[-ArgumentList] <Object[]>] 
             [-InputObject <PSObject>] 
             [-LoadProfile | -NoProfile] 
             [-Credential <PSCredential>]
- PowerShell function.
- Performs auto serialization of inputs & outputs. 
- You can prefix variables with the `$using:` scope modifier (like `$using:variableName`) and their serialized value is applied.
- Use `-LoadProfile` or `-NoProfile` to override profile loading or not.
- Use `-Credential` option for Run As User (same as `-u` but for `Get-Credentials`).
- Better forwarding of your current context to the elevated instance (current Location, $ErrorActionPreference)
3. Manual string interpolation. (not recommended) I don't recommend this approach as it is really hard to do proper escape all special characters.
Usage: gsudo 'string literal'

# Variable substitutions example:
$file='C:\My Secret.txt'; 
$algorithm='md5';
$hash = gsudo "(Get-FileHash '$file' -Algorithm $algorithm).Hash"
# or 
$hash = gsudo "(Get-FileHash ""$file"" -Algorithm $algorithm).Hash"
  • Accepts a string literal with the command to elevate.
  • Returns a list of strings.

PowerShell Module

  • Optional: Import module gsudoModule.psd1 into your PowerShell Profile:

    • Adds syntax auto-complete to gsudo in PowerShell. Plus, it suggests the 3 previous commands, making your workflow smoother than ever!
    • Enables gsudo !! on Powershell, to elevate the last executed command.
    • Adds Functions:
      • Test-IsGsudoCacheAvailable Returns true if a gsudo cache is active (meaning elevation with no UAC is possible).
      • Test-IsProcessElevated: Returns true if the current process is elevated.
      • Test-IsAdminMember: Returns true if the current user is member of the Local Administrators groups, which means it can elevate with.
    # Add the following line to your $PROFILE 
    Import-Module "gsudoModule"
    
    # Or run:
    Write-Output "`nImport-Module `"gsudoModule`"" | Add-Content $PROFILE
    • If you haven't already customized your PowerShell prompt (for example by installing Oh-My-Posh), you can easily add a red # indicating that the current process is elevated: gsudo prompt

    To do so add this line to your profile (after importing gsudoModule):

    Set-Alias Prompt gsudoPrompt

Usage from WSL (Windows Subsystem for Linux)

On WSL, elevation and root are different concepts. root allows full administration of WSL but not the windows system. Use WSL's native su or sudo to gain root access. To get admin privilege on the Windows box you need to elevate the WSL.EXE process. gsudo allows that (a UAC popup will appear).

On WSL bash, prepend gsudo to elevate WSL commands or gsudo -d for CMD commands.

# 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
PC:~$ gsudo -d "notepad C:\Windows\System32\drivers\etc\hosts"

# test for gsudo and command success
retval=$?;
if [ $retval -eq 0 ]; then
    echo "Success";
elif [ $retval -eq $((999 % 256)) ]; then # gsudo failure exit code (999) is read as 231 on wsl (999 mod 256)
    echo "gsudo failed to elevate!";
else
    echo "Command failed with exit code $retval";
fi;

Configuration

 gsudo config                          # Show current config settings & values.
 gsudo config {key} [--global] [value] # Read or write a user setting
 gsudo config {key} [--global] --reset # Reset config to default value
 --global                              # Affects all users (overrides user settings)

Credentials Cache

The Credentials Cache, if enabled and active, allows to elevate several times from a parent process with only one UAC pop-up. After 5 minutes without elevations, the cache session closes automatically (Configurable timeout via gsudo config CacheDuration).

While this very convenient, it's important to understand its potential security risks. Even if gsudo itself is secure, the inherent vulnerability lies in the host process. If your system is already compromised by a malicious process, it can manipulate the permitted process (e.g., Cmd/Powershell) and force an active gsudo cache instance to elevate privileges without triggering a UAC prompt.

This risk is the trade-off for using the Credentials Cache. The cache is safe to use as long as you are confident there are no malicious processes running on your system.

Here are the Credentials Cache Modes:

  • Explicit: (default) Every elevation shows a UAC popup, unless a cache session is started manually...
    • To start or stop a cache session run: gsudo cache {on | off}
    • This is the default mode. (Use gsudo config CacheMode Explicit to revert to this value).
  • Auto: Similar to unix-sudo. The first elevation shows a UAC popup and starts a cache session automatically.
    • Run gsudo config CacheMode Auto to use this mode.
  • Disabled: Every elevation shows a UAC popup, and trying to start a cache session will throw an error..
    • Run gsudo config CacheMode Disabled to use this mode.

In any case, you can stop all cache sessions with gsudo -k.

Learn more

Known issues

  • The elevated instances do not have access to the network shares connected on the non-elevated space. This is not a gsudo issue but how Windows works. Use --copyNS to replicate Network Shares into the elevated session, but this is not bi-directional and is interactive (may prompt for user/password).

  • gsudo.exe can be placed on a network share and invoked as \\server\share\gsudo {command} but doesn't work if your current folder is a network drive. For example do not map \\server\share\ to Z: and then Z:\>gsudo do-something.

  • Please report issues in the Issues section.

FAQ

  • Why is it named gsudo instead of just sudo?

    When I created gsudo, there were other sudo packages on most Windows popular package managers such as Chocolatey and Scoop, so I had no other choice to pick another name. gsudo installers create an alias for sudo, so feel free to use sudo on your command line to invoke gsudo.

  • Why did you migrated from .Net Framework 4.6 to .Net Core 7.0?

    Starting from v1.4.0, it is built using .Net 7.0 NativeAOT. It loads faster and uses less memory, and runs on machines without any .Net runtime installed. Prior versions <v1.3.0 used .Net 4.6, because it was included in every Windows 10/11 installation.

  • Is gsudo a port of *nix sudo?

    No. gsudo reminds of the original sudo regarding user expectations. Many sudo features are *nix specific and could never have a Windows counterpart. Other features (such as sudoers) could potentially be implemented but are not at this point.

  • What are the requirements? Does it work in Windows 7/8?

    It works on Win7 SP1 onwards. Some features may only work in Windows 10/11, like elevating as TrustedInstaller.

  • How do I return to the previous security level after using gsudo?

    In the same way as you would with Unix/Linux sudo: gsudo does not alter the current process, instead it launches a new process with different permissions/integrity level. To go back to the previous level, just end the new process. For Command Prompt or PowerShell just type exit.

Please support gsudo! 💵

  • Please give us a star! ⭐
  • Help spread the word by mentioning gsudo in social networks!
  • Sponsor or Donate

gsudo's People

Contributors

bluphy avatar bmurri avatar bouska avatar christoph-wagner avatar connorjs avatar ddavness avatar dependabot[bot] avatar floh96 avatar gerardog avatar gitter-badger avatar icysteam avatar janhebnes avatar jetersen avatar joerohde avatar krrishdhaneja avatar lsiu avatar nj-brad avatar omarahmed-a avatar rehanplayz avatar rfay avatar silvenga avatar snyk-bot avatar southpaw018 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

gsudo's Issues

TimeOutException is thrown when the current user is not admin

When the current user is not admin, the UAC popup allows to specify a different user/password for elevation. Even thou the elevated instance is created corrected as other user, the elevated and non-elevated gsudo instances are unable to connect, and TimeOutException is thrown.

Running gsudo from mapped drive

Have script utilizing gsudo.exe saved on my network storage, mapped as a drive Z: Starting script from Z:, script working successfully but gsido failed with following message:

gsudo --raw --debug netsh interface ipv4 set address "UGHGH" static 10.12.15.3 255.255.255.224 10.12.15.1
Debug: IsWindowsApp("C:\WINDOWS\system32\netsh.EXE") = False ("C:\WINDOWS\system32\netsh.EXE")
Debug: Application to run: C:\WINDOWS\system32\netsh.EXE
Debug: Arguments: interface ipv4 set address "UGHGH" static 10.12.15.3 255.255.255.224 10.12.15.1
Debug: Using Console mode Raw
Debug: Caller ProcessId is 2188
Debug: Connected via Named Pipe gsudo_S-1-5-21-2888163432-2796349975-2356466950-1001_2188.
Debug: ElevationRequest length 631
Server Error: System.ComponentModel.Win32Exception (0x80004005): The directory name is invalid
   at System.Diagnostics.Process.StartWithCreateProcess(ProcessStartInfo startInfo)
   at gsudo.Helpers.ProcessFactory.StartInProcessRedirected(String fileName, String arguments, String startFolder)
   at gsudo.ProcessHosts.PipedProcessHost.<Start>d__3.MoveNext()
Warning: Connection from server lost.

Is it because of elevated users 'Administrator' profile does not have mapped such drive? Is there any workaround for such situations, or could there be a specific errromessage and related exitcode for this case?

Unable to connect to the elevated service

On my laptop the gsudo fails every time I use it either in Windows Terminal or in Powershell. I'm using Windows 1909 currently. On my desktop computer with Windows 10 2004 it works fine. Here's the error messages I get with --debug option.

Debug: IsWindowsApp(""C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe"") = False ("C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe") Debug: Command to run: "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -NoLogo Debug: Using Console mode TokenSwitch Debug: Caller PID: 3664 Debug: Caller SID: S-1-5-21-2868004287-1937137488-1281371712-1002 Debug: Elevating process: C:\ProgramData\chocolatey\lib\gsudo\bin\gsudo.exe --debug gsudoservice 3664 S-1-5-21-2868004287-1937137488-1281371712-1002 All 00:05:00 Debug: Elevated instance started. Error: Unable to connect to the elevated service.

and gsudo service error:
Info: Service started Debug: Service will shutdown if idle for 00:05:00 Error: System.Security.Principal.IdentityNotMappedException: Joidenkin tai kaikkien tunnisteviittauksien muuntaminen epäonnistui. kohteessa System.Security.Principal.NTAccount.Translate(IdentityReferenceCollection sourceAccounts, Type targetType, Boolean forceSuccess) kohteessa System.Security.Principal.NTAccount.Translate(Type targetType) kohteessa System.Security.AccessControl.CommonObjectSecurity.ModifyAccess(AccessControlModification modification, AccessRule rule, Boolean& modified) kohteessa System.Security.AccessControl.CommonObjectSecurity.AddAccessRule(AccessRule rule) kohteessa gsudo.Rpc.NamedPipeServer.<Listen>d__16.MoveNext() --- Pinon jäljityksen loppu aiemmasta sijainnista, jossa palautettiin poikkeus --- kohteessa System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() kohteessa System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) kohteessa gsudo.Commands.ServiceCommand.<Execute>d__19.MoveNext() --- Pinon jäljityksen loppu aiemmasta sijainnista, jossa palautettiin poikkeus --- kohteessa System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() kohteessa System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) kohteessa gsudo.Program.<Start>d__1.MoveNext()

Sorry for the Finnish localization. I can translate them if needed.

gsudo hangs when run from Windows Terminal started with wt alias

I'm trying out gsudo and from cmd, pwsh or Windows Terminal shortcut it works as expected.

However when starting Windows terminal by the wt alias gsudo will "hang" and never shows the elevation prompt.

Further details:

  • Windows 10 2004
  • Windows Terminal 1.0.1401.0 (Store version)
  • gsudo 0.7 and 0.5 ?? [ https://ci.appveyor.com/project/gerardog/gsudo/builds/33404236/artifacts ]

image

Cannot call the function defined in profile

Function defined in Global Profile(C:\Windows\System32\WindowsPowerShell\v1.0\profile.ps1):

Function TestUserFunc
{
    echo 'Function defined in Global Profile'
}

Call user function with sudo will rasie ObjectNotFound(shown in figure 1):
image

gsudo not found after install

I ran choco install gsudo and refreshenv from an elevated powershell and even reopened the powershell. Installation went fine but when I type gsudo in an unelevated prompt:

gsudo : Die Benennung "gsudo" wurde nicht als Name eines Cmdlet, einer Funktion, einer Skriptdatei oder eines
ausführbaren Programms erkannt. Überprüfen Sie die Schreibweise des Namens, oder ob der Pfad korrekt ist (sofern
enthalten), und wiederholen Sie den Vorgang.
In Zeile:1 Zeichen:1

  • gsudo
  •  + CategoryInfo          : ObjectNotFound: (gsudo:String) [], CommandNotFoundException
     + FullyQualifiedErrorId : CommandNotFoundException
    

(which translate to not found).

Running gsudo from an elevated prompt:

Error: Already running as the specified user/permission-level (and no command specified). Exiting...

Of course I cannot install gsudo from an unprivileged ps.

Can command history be accessed?

After typing gsudo and getting a
C:\#
prompt, pressing the up arrow key or the F7 key doesn’t appear to do anything. I’ve tried working around it, by typing gsudo cmd /k but no luck. Any ideas?

Single executable

Maybe it would be nice to have a single executable with dependencies statically linked. It might be around 50-60mb but I don't think that is an issue for the users. Just as additional distribution. Thanks!

Bad command prompt on Windows 8.1

On Windows 8.1 The elevated prompt shows:

C:\Users\Gerardo←[1;31;40m# ←[0;37;40m

instead of:

C:\Users\Gerardo# 

... which can be fixed with gsudo config Prompt "$p# "
but should work out of the box.

image

Sign gsudo with a Code-Signing certificate, so the UAC pop-up doesn't show 'Unknown Publisher'

You can get a code signing cert for 25 euros #1

See https://en.sklep.certum.pl/data-safety/code-signing-certificates/open-source-code-signing-1022.html
per https://github.com/gerardog/gsudo/blob/master/backlog.md#other-not-so-likely-ideas

Spend 500 USD in a code-signing certificate so I can sign the builds. I need to setup an https web site for gsudo or myself first as a prerequisit to get the certificate.

Issue: Minor typo in README

Spotted a small typo in the Known Issues section.

  • Under some circunstances the sudo alias can misbehave while the gsudo command works well.

circunstances circumstances

gsudo --vt seems to have problems with character encoding

First up, great work Gerardo. Superb, in fact. Now, on to the issue at hand:

image

As you can see, gsudo without conpty is fine. But with --vt for conpty, the extended unicode characters are getting corrupted/munged somehow. I don't think this is an issue with conpty since WT itself uses conpty in general, and unicode works fine (obviously.)

Let me know if you need any more information. I'm using Fira Code as a font.

Can it support SSH/non-GUI logins?

AFAIK, gsudo relies on the UAC graphical prompt. Is this a limitation of Windows or is there a way of working around this?

My shop has a few windows boxes and we would like to automate some procedures using ssh that we currently need to login via RDP to do. Today we need to Right-Click and run Powershell as Admin, but it would be great if we could just do ssh user@mybox elevate "C:/scripts/do-admin-stuff.ps1"

Handle started application exitcode

Often utilizing gsudo app parameters through the batch script. Need to distinguish STDERR and exitcode of app from STDERR and exitcode of gsudo but did not find any way to do this. Is it possible at all?

error starting batch file

As the title says, with the just released 0.5.2 version i got this error when i try to start a batch file as admin:

Server Error:System.ComponentModel.Win32Exception (0x80004005): Unable to find specified file
   in System.Diagnostics.Process.StartWithCreateProcess(ProcessStartInfo startInfo)
   in gsudo.Helpers.ProcessFactory.StartInProcessAtached(String filename, String arguments)
   in gsudo.ProcessHosts.AttachedConsoleHost.<Start>d__0.MoveNext()
Info: Elevated process exited with code 999

Issue: language changes to english after gsudo

Issue Description

When i run gsudo my terminal changes language to english

Steps to Reproduce

  1. In powershell: run gsudo and accept uac, terminal now in english
  2. In cmd even running gsudo -v is enough, accepting or declining uac also changes a language

Screenshots

image

Context:

  • Windows version: 20H2
  • gsudo version: v0.7.2

Can't run `gsudo`, installed from chocolatey

Steps to reproduce:

  1. run shell as administrator
  2. cinst gsudo
  3. gsudo
  4. open non-elevated shell
  5. gsudo

Observed behaviour:

At step 3 I see a message that the shell is already elevated. At step 5 I see a message that gsudo is not recognized as a program.

Expected behaviour:

I can run a program with elevated privileges at step 5.

My thoughts

I have two users: one has administrator privileges, the other one doesn't. It appears that gsudo sets the PATH for the administrator user but not the system PATH (I looked at environment variables as the first and as the second user). Thus, the ordinary user can't access gsudo.

I guess, it should be possible to modify system PATH instead of the user local one?

Feature: Improve PowerShell elevation syntax with a wrapper function script

For context: when writing this, gsudo is invoked as any other console .EXE app from PowerShell. This means the parsing/quote escaping is not ideal and this rules must be followed.

Looking forward to implement an `invoke-gsudo' function for PowerShell and I would like to hear opinions from people with more PowerShell experience than me.

  • This function would be a wrapper of gsudo.exe that would make it feel more PowerShell native.

  • The function name: What would be the best name for it? I bet people would throw me stones if It doesnt respect the verb-noun form. Ideally it should NOT be the same as in PowerShell/PowerShell#11343 which is hard to know since that one isn't defined yet either. (reason: to avoid all flows to break when that one is released). From now on I would just say invoke-gsudo as an alias for to be defined function name. Also, maybe it would be better to leave any alias definitions to the end user.

  • The deployment model: I think I figured out this one: By creating a Invoke-gsudo.ps1 file in the PATH (e.g. gsudo folder) would be enough. The function should be deployed by the 3 installers (scoop/choco/manual .ps1)

  • Input command parsing: Ideally one would just prepend invoke-gsudo without special quoting rules, but is that doable? Best way to get variable substitution? Would the PS-Remoting model work for gsudo?
    For example, this difference is unwanted: (related #38)

     PS> echo "abc def"
     abc def
     PS> gsudo echo "abc def"
     abc
     def
    
  • Output result marshalling: Since marshaling is impossible to avoid, this could be like: The elevated instance serializes the result instead of .ToString() it, stream (StdIn/Out) and non-elevated deserialize.

Reason I wrote this is here is because I prefer to gather feedback very early on. I don't want to invest time just to learn (after releasing) that I reinvented a wheel already available for free, in any of these areas.

sudo !! (bang bang) for PowerShell

The just released 0.7.1 doesn’t support !! for PS. At face value, this seems like it should be pretty straight forward using Get-History, but I don’t have much experience with PS and even less with using PS from C#. I would like to look into it, but was wondering if you tried and encountered any showstoppers' or problems that might make this moot or extremely complicated.

"L" key targets active gsudo window during runtime

Hey, when using gsudo the "L" key (lower case L to be exact) becomes unresponsive and instead targets the active gsudo instance.
This is especially troublesome, when trying to spawn a powershell or running chocolatey.

Repro:
1.1) Open Windows Search or the Run Dialog
1.2) Type in for example sudo powershell
1.3) Select the command invoke (only applicable for Windows Search)
1.4) A gsudo window with powershell running will now open
1.5) Select another window or collapse the gsudo window
1.6) Press only the "L"-Key (Note: Shift + L doesn't trigger the problem)
1.7) The key doesn't produce an output and instead pulls focus to the gsudo instance
1.8) Close the gsudo instance
1.9) L-key now works as intended again.

It seems to have something to do with running these applications embeded within gsudo, as when the -n parameter to spawn a new window is passed the "L" key works as intended.

Windows 10 version 2004
Gsudo Version 0.7.2 (Installed via chocolatey)

Error opening compmgmt.msc from cmd

Hi! Nice work!

I have the error when launching compmgmt.msc from cmd.exe with gsudo v0.7.
In powershell all is ok.

Microsoft Windows [Version 10.0.18363.720]
(c) Корпорация Майкрософт (Microsoft Corporation), 2019. Все права защищены.

C:\Users\***>sudo compmgmt.msc
Error: System.ComponentModel.Win32Exception (0x80004005): Операция успешно завершена
   в gsudo.Helpers.ProcessFactory.CreateProcessAsUserWithFlags(String lpApplicationName, String args, CreateProcessFlags dwCreationFlags, PROCESS_INFORMATION& pInfo)
   в gsudo.ProcessRenderers.TokenSwitchRenderer..ctor(Connection connection, ElevationRequest elevationRequest)
   в gsudo.Commands.RunCommand.<RunUsingSingleUseElevation>d__7.MoveNext()
--- Конец трассировка стека из предыдущего расположения, где возникло исключение ---
   в System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   в System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   в gsudo.Commands.RunCommand.<Execute>d__5.MoveNext()
--- Конец трассировка стека из предыдущего расположения, где возникло исключение ---
   в System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   в System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   в gsudo.Program.<Start>d__1.MoveNext()

Issue: Self-Elevation Breaks if Path Contains Spaces

Issue Description

Self-elevation fails if the path to gsudo contains spaces.

Logger.Instance.Log($"Global system settings requires elevation. Elevating...", LogLevel.Info);
return new RunCommand()
{
CommandToRun = new string[]
{ ProcessHelper.GetOwnExeName(), "--global", "config", key, reset ? "--reset" : $"\"{unescapedValue}\""}
}.Execute();

Steps to Reproduce

# Powershell
cd "Folder With Spaces"
.\gsudo.exe config CacheMode --global Auto

Screenshots

Debug: IsWindowsApp(""C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe"") = False ("C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe")
Debug: Command to run: "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -NoLogo -NoProfile -Command C:\Users\<user>\Downloads\New folder\gsudo.exe --global config CacheMode "Auto"
Debug: Using Console mode TokenSwitch
Debug: Caller PID: 25640
Debug: Found Named Pipe "ProtectedPrefix\Administrators\gsudo_A109FA9081085ECF1E3FBB4E96EC020F20DAE79D1544FD8A6877F87CF7588E3B".
Debug: Connected via Named Pipe ProtectedPrefix\Administrators\gsudo_A109FA9081085ECF1E3FBB4E96EC020F20DAE79D1544FD8A6877F87CF7588E3B.
Debug: CreateProcessAsUser: "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -NoLogo -NoProfile -Command C:\Users\<user>\Downloads\New folder\gsudo.exe --global config CacheMode "Auto"
Debug: ElevationRequest length 943
Debug: Process token successfully substituted.
C:\Users\<user>\Downloads\New : The term 'C:\Users\<user>\Downloads\New' is not recognized as the name of a cmdlet,
function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the
path is correct and try again.
At line:1 char:1
+ C:\Users\<user>\Downloads\New folder\gsudo.exe --global config CacheM ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (C:\Users\<user>\Downloads\New:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

Context:

  • Windows version: Windows 10 (2004)
  • gsudo version: gsudo v0.7.2

Feature: Improve elevation of Bash commands

firstly I wanted to use dd under windows 10, since it's not possible under wsl2 environment
Discovered Git Bash for windows has dd tool, already had Git Bash installed, great then added it to Windows Terminal.
But could only git to run correctly if I started Terminal shell with "run as administrator", otherwise permission denied.
Found Gsudo, was impressed and went to use it with dd with the following
$ gsudo dd if=/dev/zero of=/dev/sdc bs=1M count=10
/usr/bin/dd: failed to open '/Device/Null': No such file or directory
Info: Process exited with code 1

Any ideas would be greatly appreciated. :-)
Cheers, Dennis

btw, sudo bash & then dd if=/dev/zero of=/dev/sdc bs=1M count=10, works also

Incorrect quoted string parsing

The space character within the quotes seems to be tranformed into a newline character.
Using ver 0.7.0 installed from chocolatey

➜  ~ echo "ABC DEF"
ABC DEF
➜  ~ sudo echo "ABC DEF"
ABC
DEF

Help wanted: Could you Review/Audit or PenTest `gsudo` source code?

I've already heard opinions like: "I can not use this on the enterpise." or "This other sudo is just a few lines RunAs script that I can audit myself." (Sure, but building a feature-rich sudo takes far more lines than that.) and the next one probably will be: "I won't run as administrator something from a nobody on the internet."

This is a trust problem. And I cannot create trust by myself.

The only way that I can think of gaining trust in a free open-source project made in spare-time is by incremental contributions from the community. What if anyone could get involved and deposit a small unit of trust?

So, I thought: Well lets create a place where anyone who has read the code can pass a message to the next one.

Contributions should contain:

  • A description of your expertise area, or relevant certifications if any: (for example, Information Technology Student, Senior C++/C# Windows Security Analyst, Developer, Certified PenTest/CISA, etc.) (All contributions are worthy)
  • What kind of audit/review have you done, for example:
    • I've read all the code and I couldn't find any intentional backdoor or unintentional security hole.
    • I've analyzed the code and the security measures of X seems appropriate.
    • As certified "x" I can certify that...
  • Commit ID and timestamp of the audited code (master branch only!)

If a review or audit finds issues, the best path forward would be to create an issue with the findings so we can first triage each one and create proposals appropriate issues for each matter.

The scope of the Audit is just those parts of gsudo that are distributed on each release. (tree link). (i.e. build scripts/unit tests are not distributed nor used by end-users, so IMHO I see no point auditing that.)

Thank you very, very much.

RunAsUser

If my normal account isn't an admin can I pass administrator credentials (username/password) to use?

I see some mention of this in backlod.md but I'm not sure it's implemented yet?

Discussion: How can we make gsudo as secure as possible?

It's in everybody interest to make gsudo as secure as possible. The current Windows security model makes almost impossible to make a risk-less sudo for Windows. Otherwise, Microsoft would have already made one.

Therefore, using gsudo has inherent risks, and my vision is that it should expose as few attack vectors or risks as possible, document each risk, and provide a way to disable every feature that results in new risks/attack vectors.

As a start, I created issue #19 requesting help from the community willing to review / audit gsudo source or perform a PenTest. Let's use this thread instead to discuss more general security-hardening related ideas. Such as feedback on what are the gsudo weak points and/or proposals on how to be more secure.

Get involved please! Thanks!

An error occurs when I attempt to execute "gsudo regedit"

(I set an alias for gsudo.)

test1

Error: System.ComponentModel.Win32Exception (0x80004005): The operation completed successfully
   at gsudo.Helpers.ProcessFactory.CreateProcessAsUserWithFlags(String lpApplicationName, String args, CreateProcessFlags dwCreationFlags, PROCESS_INFORMATION& pInfo)
   at gsudo.ProcessRenderers.TokenSwitchRenderer..ctor(Connection connection, ElevationRequest elevationRequest)
   at gsudo.Commands.RunCommand.GetRenderer(Connection connection, ElevationRequest elevationRequest)
   at gsudo.Commands.RunCommand.<RunUsingElevatedService>d__9.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at gsudo.Commands.RunCommand.<Execute>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at gsudo.Program.<Start>d__1.MoveNext()

crashpad error

running gsudo 0.7.0 installed via chocolatey under Windows 10 shows the following error:

[41808:53392:20200525,083449.588:ERROR crash_report_database_win.cc:569] 
CreateDirectory : The system cannot find the path specified. (3)
Could not initialize crash reporting DB
Can not init crashpad with status: CRASHPAD_DB_INIT_ERROR

Also reported on crashpad's bugtracker : https://bugs.chromium.org/p/crashpad/issues/detail?id=343

After enabling cache: "Unable to connect to the elevated service."

I installed gsudo 0.7 with chocolatey. Testing it, everything works fine. But after I set Cache to Auto, I get Error: Unable to connect to the elevated service. on every invocation. Restarting the computer did not help. Powershell or cmd makes no difference.

After clearing the registry key, I tried gsudo cache on, this does not result in the error, but it also doesn’t work, any request afterwards results in a new UAC prompt. Auto or Explicit doesn’t make a difference.

Windows 10 V2004 Build 19041.264 (VM, German)
Windows 10 V1909 Build 18363.836 (German, English language pack)

gsudo Tee hangs when used to save files from Vim

I'm trying to reproduce the trick of saving files using sudo from a non-root vim using gsudo. However, gsudo hangs.

Here's the steps:

  1. Open a protected file (that requires elevation to be writeen) with a non-elevated vim.exe or gvim.exe
  2. Change the file
  3. Execute the command in vim: :w !gsudo tee %

Expected result: file should be save with chagnes

Actual result: command hangs

Notes

  • you'll also need to have tee installed (either cygwin, msys, etc).
  • I've tried using only :w !tee % (for non protected file). It works fine, which indicates that the issue is indeed on gsudo

Here's some reference on how this trick works on unix/linux: https://vim.fandom.com/wiki/Su-write

sudo-alias doesn't work

When typing in the 'sudo' alias, I get an error:

❯ sudo
Cannot find file at '..\lib\sudo\bin\sudo.cmd' (C:\ProgramData\chocolatey\lib\sudo\bin\sudo.cmd). This usually indicates a missing or moved file.

Install was done using choco install gsudo.
Initially I had another sudo-package installed. I removed both sudo and gsudo and re-installed gsudo, but I get the same result.

Feature Request: sudo !! (sudo bang bang) for CMD

To be fair, this is not my top priority but a nice-to-have. Upvote if you would like to see this feature implemented sooner.

from: https://stackoverflow.com/a/15137462/97471

The bang bang (!!) command is a shortcut to repeat the previous command you entered in your terminal. This command is very useful when you forget that you need admin rights to make a certain action, and lets you repeat it with super-user rights just by typing

sudo !!

instead of typing arrow-up, scrolling to the beginning of the line, adding sudo and hitting enter (imagine scrolling through those loooong apt-get commands). So many seconds gained! Yay!

sudo bang bang

There are many other bang-commands such as !x, !?x, !!:p and !!*. This blog post lists them and explains what they are for.

Make gsudo installable through winget

Microsoft has released their own package installer for Windows called winget. gsudo should also be added to their package list here.

I would add it myself, but there isn't an executable installer that I can link to, which is needed if you make the manifest using the WinGetYamlGenerator tool.

Problem with Chocolatey Install in v0.6.0.2

After upgrading to v0.6.0.2, gsudo stopped working with this error message:

Cannot find file at '..\lib\gsudo\tools\gsudo.exe' (C:\ProgramData\chocolatey\lib\gsudo\tools\gsudo.exe). This usually indicates a missing or moved file.

The gsudo.exe executable is in the chocolatey\lib\gsudo\bin folder but not chocolatey\lib\gsudo\tools folder. I copied the executable to tools folder as a workaround and it appears to be functional now.

Unhandled Exception after CTRL+C

Dear all,

if you press CTRL+C during a loop command like "ping foo -t" I get the following error:
Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object.

thanks a lot
Daniel

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.