gerardog / gsudo Goto Github PK
View Code? Open in Web Editor NEWSudo for Windows
Home Page: https://gerardog.github.io/gsudo
License: MIT License
Sudo for Windows
Home Page: https://gerardog.github.io/gsudo
License: MIT License
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.
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:
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.
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.
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?
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?
When launching gsudo from powershell core v7.0.0-rc2 it launches with profile.
See my profile here: https://github.com/casz/dotfiles/blob/master/powershell/profile.ps1
Of course I could remove my "Modules Loaded" message 🤔 But it seems that it also adds two new lines in pwsh rather than just one newline.
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
Subj
Not necessarily a problem, but tickles my perfectionist sense.
I tried the gsudo thing, but it's a pretty awful experience. Any sort of TAB completion seems to break, and Unicode (non-ASCII) characters don't seem to display. I'm guessing it's some sort of process that redirects input and output, and does a terrible job at it. I think the solution with a separate window works better.
Originally posted by @MikeChristensen in microsoft/terminal#632 (comment)
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
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:
vim.exe
or gvim.exe
:w !gsudo tee %
Expected result: file should be save with chagnes
Actual result: command hangs
Notes
:w !tee %
(for non protected file). It works fine, which indicates that the issue is indeed on gsudoHere's some reference on how this trick works on unix/linux: https://vim.fandom.com/wiki/Su-write
(I set an alias for gsudo.)
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()
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!
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"
There's no need to add gsudo to the path in the Chocolatey package. If you delete the gsudo.exe.ignore a shim will be created in Chocolatey's bin folder which is already on the path. You can also remove the instruction to refreshenv as the environment won't need to change and gsudo will work instantly.
I think there should be a way for de-escalation as an additional feature
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.
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.
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?
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()
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 typingsudo !!
instead of typing arrow-up, scrolling to the beginning of the line, adding
sudo
and hitting enter (imagine scrolling through those loooongapt-get
commands). So many seconds gained! Yay!There are many other bang-commands such as
!x
,!?x
,!!:p
and!!*
. This blog post lists them and explains what they are for.
Is it possible to add an option to run as TrustedInstaller?
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.
First up, great work Gerardo. Superb, in fact. Now, on to the issue at hand:
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.
Looks like the install script kills gsudo
, that runs it. 😂
Workaround is to remove C:\ProgramData\chocolatey\bin\gsudo.exe
(which is a link) and to reinstall gsudo from a regular elevated console.
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.
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!
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
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?
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.
cinst gsudo
gsudo
gsudo
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.
I can run a program with elevated privileges at step 5.
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?
windows 10 powershell
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
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)
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:
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.
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.
When i run gsudo my terminal changes language to english
gsudo -v
is enough, accepting or declining uac also changes a languagerunning 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
I suggest the chocolatey package download the zip from GitHub?
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)
Self-elevation fails if the path to gsudo contains spaces.
gsudo/src/gsudo/Commands/ConfigCommand.cs
Lines 62 to 67 in 3088ef6
# Powershell
cd "Folder With Spaces"
.\gsudo.exe config CacheMode --global Auto
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
Windows 10 (2004)
gsudo v0.7.2
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
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.