Powershell: Support sudo <PowerShell cmdlet>

Created on 28 Feb 2017  Â·  99Comments  Â·  Source: PowerShell/PowerShell

Steps to reproduce

sudo Remove-Item foo.txt where foo.txt is owned by root

Expected behavior

foo.txt is deleted

Actual behavior

sudo: Remove-Item: command not found

Committee-Reviewed Issue-Enhancement WG-Engine

Most helpful comment

Even on Windows, it would be good to have similar capability to run a cmdlet as another user or elevated and something that could relied on in portable scripts. May need an RFC for this.

All 99 comments

Hum! Very interesting. But, I think the actual behavior is as expected. As in Windows we don't have a command like sudo.
But, you could use 'sudo powershell' and then do the remove foo.txt (which was created using 'sudo powershell') then it works when using Remove-Item. Of course, it won't work in a non-elevated permission.

I would only use 'sudo' on Linux commands ("sudo nautilus") from within PowerShell.

:)

Even on Windows, it would be good to have similar capability to run a cmdlet as another user or elevated and something that could relied on in portable scripts. May need an RFC for this.

This functionality would be useful to work around #3506.

This is going to become a blocker for adapting Linux for me if this is not resolved. We are not allowed to sudo bash and similarly will not be able to do sudo powershell.

I agree with Maximo, we should leave sudo to bash and make a new cmdlet for doing elevation in powershell using sudo as scaffolding on expected functionality.

@dantraMSFT has been investigating this, Dan can you provide an update on some current thinking for this?

@pixelrebirth Can you provide more detail as to what you expect? Are you expecting simple execution with a wait, output redirection or pipeline redirection?
Some example usage would be useful as well.

@dantraMSFT For sake of the argument I am going to call the new sudo like cmdlet: Invoke-Elevated
This is how sudo works and would translate to Invoke-Elevated in a powershell way

$cred = Get-Credential
Invoke-Elevated -credential $cred -command {
        Get-ChildItem ./test | Remove-Item -force
} | Get-SomeCmdlet

In this example, everything in the scriptblock would be executed elevated and then piped to a NON elevated Get-SomeCmdlet
Cred can be a different user or yourself as an elevated user (permissions needs to be kept somewhere like sudoers file does aka a whitelist)

Logging should be enabled, by default for instances where Invoke-Elevated is executed:
User | Command | DateTime or similar format logging

Maybe some of this gets extended or changed later, but this is what would remove my blockers

It should also work like:

Get-ChildItem ./test | Invoke-Elevated -command {Remove-Item -force}
Where the credential is your current user and it just asks for the password...

Get-ChildItem is NON elevated, Remove-Item is elevated in this example

I was on the community call today asking about this, but my wife got hurt during the explanation of the challenges for it and I missed a lot of it. Can you please put notes here so I can relay them to my boss?

I will help however possible and put pressure wherever I need to.

@pixelrebirth hope she's okay! We'll be putting up a recording of the call in the next day or two, so you can catch up if you like.

Basic summary is that @dantraMSFT is doing an initial investigation to figure out how to do this in a non-hacky way. Today, you can sudo powershell -c "invoke-foo" from another shell, but that's obviously not workable.

@dantraMSFT : as you work through your investigation, maybe post some status to make sure that everyone understands the tradeoffs with different approaches?

It may seem obvious, but maybe take a look at the sudo source code and see how they manage it-- maybe it requires some low level coding. I wish I had a deeper code understanding to help.

She is okay, she feel on her surgery hip. Thanks for the fast response on this. I am working on a little hack work around I will post here if I pull it off.

@pixelrebirth For reference, sudo uses the setuid bit, see https://unix.stackexchange.com/a/80350/86669 for details. It would probably be a bad idea to set that on a whole shell, though.

Native Windows sudo is must to have (so the issue probably doesn't belong here, although option where it is usable only via Powershell is acceptable for me ). I have used Powershell since the beginning and have seen 99 variants of sudo script around, like Invoke-Elevated above (or my own that I use every day). Including cmdlet like that in Powershell would be step forward, however, they all feel cumbersome relative to how this works on Linux.

One of the annoying things for me is that it starts a new shell window (not on linux ) which I would like to see implemented in Powershell/Windows, not sure if this is technically possible on Windows tho.

Although I like the idea of another cmdlet ("Invoke-Elevated") which could possibly be use in Windows, but I can't understand why not stick to open PowerShell with 'sudo' if you need to create a script to run with high privilege?

Especially If you're automating a task which will eventually be scheduled to run with some kind of high privilege credentials anyway.
:)

Because that is not the typical workflow. You don't 'sudo' and live there forever, you sudo specific commands and live in non-sudo world. There is no quick way to do so in Windows and powershell itself is terribly slow to start, especially with few profile elements included.

In a typical every day session I sudo 20 times specific commands, other run unprivileged. That is the whole point of sudo, to rise privilege only when necessary and it might be necessary quite often.

My workflow was, run command, it complains about privilege, I sudo -L which wil execute last command again with privilege. Since posh is so slow to start, I just fire up admin shell and live in it constantly, clearly not a good idea.

Thanks @majkinetor!
:)

The sudo should be CLI variant of UAC prompt. Windows, until recently, was never CLI friendly, but now I think we need this. The time has come when you can do 100% Windows things in shell only - I personally just use shell and the browser, almost nothing else.

@majkinetor: As far as I know, the only way to launch an elevated process is through the UAC prompt.
FWIW: You can accomplish this on windows without a powershell change using ShellExecuteEx.
However, if you're expecting to stream back the results; it's a very different story.

As far as I know, the only way to launch an elevated process is through the UAC prompt.

Specific apps can be exluded from UAC which could I suppose then handle elevation in its own way.

Wanted to offer my solution/workaround for Sudo on Windows. Any feedback/criticism would be welcome. If it's not appropriate to post this type of thing here I apologize in advance.

https://github.com/pldmgg/misc-powershell/tree/master/MyModules/Sudo

https://www.powershellgallery.com/packages/Sudo

There are three functions in the Sudo Module:

  • New-SudoSession
  • Remove-SudoSession
  • Start-SudoSession

Start-SudoSession (alias "sudo") is for one-off commands that you need to elevate. It will prompt for credentials and give you a UAC prompt before carrying out the command.

.EXAMPLE

$ModuleToInstall = "PackageManagement"
$LatestVersion = $(Find-Module PackageManagement).Version
# PLEASE NOTE the use of single quotes in the below $InstallModuleExpression string
$InstallModuleExpression = 'Install-Module -Name $ModuleToInstall -RequiredVersion $LatestVersion'
Start-SudoSession -Credentials $MyCreds -Expression $InstallModuleExpression

New-SudoSession if for opening an ElevatedPSSession into which elevated commands can be injected. The idea is that in a longer script with multiple operations that require elevation, you create an ElevatedPSSession at the beginning and receive a UAC prompt ONCE, and then inject those elevated commands using Invoke-Command into that ElevatedPSSession when needed.

.EXAMPLE

PS C:\Users\zeroadmin> $MyElevatedSession = New-SudoSession -UserName zeroadmin -Credentials $MyCreds
PS C:\Users\zeroadmin> Get-PSSession
 Id Name            ComputerName    ComputerType    State         ConfigurationName     Availability
 -- ----            ------------    ------------    -----         -----------------     ------------
  1 ElevatedSess... localhost       RemoteMachine   Opened        Microsoft.PowerShell     Available

PS C:\Users\zeroadmin> Invoke-Command -Session $MyElevatedSession.ElevatedPSSession -Scriptblock {Install-Package Nuget.CommandLine -Source chocolatey}

Finally, the Remove-SudoSession removes the ElevatedPSSession created by the New-SudoSession function. The idea is to place this at the end of your script, at which point you will receive a UAC prompt. So in total, to run any number of elevated operations in a particular script, you only get hit with two UAC prompts - one to open an ElevatedPSSession and one to close it. Remove-PSSession usage:

.EXAMPLE

$MyElevatedSession = New-SudoSession -UserName zeroadmin -Credentials $MyCreds
PS C:\Users\zeroadmin> Get-PSSession
 Id Name            ComputerName    ComputerType    State         ConfigurationName     Availability
 -- ----            ------------    ------------    -----         -----------------     ------------
  1 ElevatedSess... localhost       RemoteMachine   Opened        Microsoft.PowerShell     Available

Remove-SudoSession -Credentials $MyCreds -OriginalConfigInfo $MyElevatedSession.OriginalWSManAndRegistryStatus -SessionToRemove $MyElevatedSession.ElevatedPSSession

Under the hood, here's what it does from a Non-Elevated PowerShell session (if the session is already elevated, it doesn't do anything):

  • Checks to make sure WinRM/WSMan is enabled and configured to allow CredSSP Authentication (if not then
    configuration changes are made)

  • Checks the Local Group Policy Object...

    Computer Configuration -> Administrative Templates -> System -> Credentials Delegation -> Allow Delegating Fresh Credentials

    ...to make sure it is enabled and configured to allow connections via WSMAN/LocalHostFQDN

  • Creates an Elevated PSSession using the New-PSSession cmdlet

  • Runs the expression passed to the -Expression parameter in the Elevated PSSession

  • Removes the Elevated PSSession and reverts all changes made (if any) to Local Group Policy and WSMAN/WinRM config.

EDIT: Updated Remove-SudoSession example typo.

@pldmgg I don't see what license your code is under so we can't even look at what you've done. Can you add a LICENSE file? MIT would be most friendly and allow us to use your code or derive from it. Thanks!

@pldmgg Following up on what @SteveL-MSFT mentioned, a great guide to help you through this process is https://choosealicense.com/.

tl;dr - It's hard to go wrong with the following licenses:

  • Apache 2.0
  • MIT

More details

Apache 2.0 has some additional strengths on it over MIT, but overall, they are very permissive and easily used with other open source licensing and very business friendly. If you pick any copyleft licenses (GPL), the code is unable to be used with other tools without those other tools moving to a GPL license (also known as viral licensing - LGPL being the exception here, where LGPL-licensed modules/binaries can be placed next to other tools without requiring a license change to the other code).

@pldmgg also, very, very cool!

@ferventcoder Thanks for the reference https://choosealicense.com! As you guys (+ @SteveL-MSFT) probably suspected, I wasn't really sure what license to pick. I updated my entire misc-powershell repo to use Apache 2.0, and I updated the Sudo.psd1 to reference Apache 2.0 (in my git repo as well as PowerShell Gallery). Hope this can be of use to folks! All advice/criticism welcome!

@SteveL-MSFT Can you use it if the license is Apache 2.0? If you need it to be MIT, let me know and I'll update.

@pldmgg my biggest problem with your solution is use of CredSSP. That is a less secure method for credential handling and I think exposes a lot of risk to the UAC boundary.

To quote from Powershell Magaize,

"It is a bad idea to use CredSSP to authenticate to a user’s workstation using a domain administrator account; you are essentially giving away the keys to the kingdom."

"Don’t put high trust credentials on low trust computers"

The whole point of UAC is about not trusting the applications on the computer. Even though I may consent to a sudo command that ends up running havoc on my machine, it usually won't have my credentials. If the sudo command now has clear access to my domain credentials, it could do far more damage in compromising my network.

Can your solution be made to work without CredSSP? If not, what problem were you trying to solve in using CredSSP? That information could be useful for the PowerShell team to find a more secure solution.

@pldmgg I believe Apache 2.0 is sufficient. Thanks!

@dragonwolf83 This is a common concern. I actually put forth my whole argument that it's okay in this specific situation in this thread:

https://www.reddit.com/r/PowerShell/comments/6c778m/startsudosession_sudo_for_powershell_written_in/dhsretm/

But, to summarize, I think it's okay here because:

  • It's connecting to the localhost (not remote)

  • Since Windows 8.1 / Server 2012R2, CredSSP no longer sends passwords in clear text

  • Remote Desktop Protocol is still vulnerable to pass-the-hash attacks, just like CredSSP, so if you're worried about that for CredSSP you should also be worried about that for RDP. (Of course, there is RDP Restricted Admin mode or the new "Credential Guard")

P.S. This article has become my goto reference for PowerShell Security (and it's where I learned about Credential Guard).. I highly recommend it.

https://blogs.msdn.microsoft.com/daviddasneves/2017/05/25/powershell-security-at-enterprise-customers

For 6.0.0, I think where we will end up is:

A script function called sudo that only exists on Linux (we're deferring Windows elevation support). If the argument is a cmdlet/scriptblock, then it will sudo powershell with those arguments. This does mean that for now, pipelining objects won't work. If the argument is a native command, we just pass that directly to sudo.

Post-6.0.0, we would like to eventually get to an experience like:

Get-Item foo.txt | sudo Remove-Item

and have it work on both Windows and Linux. cc @joeyaiello

Based on @PowerShell/powershell-committee discussion, this is not required for 6.0.0 and recommendation is to invest in a Invoke-AsUser type cmdlet

To change elevation in general, you would need something with setuid bit under UNIX and that would be sudo itself. sudo is a special binary that cannot be easily emulated and should not be emulated for security's sake. Please let the actual sudo be used to launch a temporary instance of powershell that runs the command in question. Also, sudoing a whole shell is rather unsafe considering that one may forget the shell open on a remote server. sudo has a mechanism to forget that the user elevated after a few minutes which protects the machine in the long run. The resolution fo this issue would allow more people to use powershell in production on Linux servers. As things stand, powershell will remain a sideline novelty since security is paramount in production.

@borgdylan today, you can do sudo pwsh -c foo within PowerShell Core (or just sudo nativecmd). I think the desire is to be able to sudo a cmdlet within an existing PowerShell Core session. We're not trying to recreate sudo here, but rather have some syntactical sugar to make it easier to use.

With #1527 and this issue getting pushed further and further back the milestones, I'm starting to wonder: Is everyone really that comfortable logging in to root sessions to do admin stuff? There is practically no convenient way to invoke PowerShell commands when PS is involved in any way.

@MathiasMagnus I haven't tested this thoroughly, but you can configure common or repeatedly used commands to not require a password on sudo. To test I added this with visudo:

mark ALL=(ALL:ALL) NOPASSWD: /usr/bin/pwsh

I was then able to call sudo pwsh -c 'cat /etc/sudoers' over a PowerShell SSH remoting session. Depending on how you are doing your security and what exactly you configure in sudoers (for example, All=(ALL:ALL) is a bit open...) this could be safe or dangerous.

If you ssh to Linux (i.e to bash shell instead of PowerShell SSH remoting) you can run sudo with normal password prompting within pwsh so far as I can tell.

Its not so much that it's impossible, just that the current workarounds comes with some baggage.

@MathiasMagnus #1527 is still targeted for 6.1.0 as there is no good workaround for that. For cmdlets, the main issue is the complication of pipelining to/from a sudo'd cmdlet. For single operations sudo pwsh -c is viable. Of course if someone from the community submits a PR, we'd be more than happy to take it.

On Windows, this is now an issue that I don't think can be solved without not elevating ssh connections, which then requires a way to elevate from the command line.

I know it is easy to b*tch about things not working and not taking action, but my expertise lay elsewhere. I mostly contribute to C++ and GPGPU libraries and Vcpkg doing lots of CMake porting. I've never written C# and I don't think I'll have the capacity to. However I do administer a small cluster of ~12 machines. It's on the border of being manageable by hand, but sudo capability is missing direly, that is if I don't intend on creating login for the root user on Ubuntu, something that is frowned upon. DSC Core would be a solution, but even though it's been announced a year ago, it's recently been delayed indefinitely.

PowerShell Core on Linux as it currently stands is kinda stuck between the automated way of doing stuff and the ad-hoc style that is familiar to Linux sysadmins. I hope someone will find the time to attend this issue.

@MathiasMagnus this is something everyone wants, but is not a simple problem to solve. Note that using sudo against native commands work fine, it's really just not available to run sudo against cmdlets. Workaround is to invoke pwsh within pwsh:

sudo pwsh -c remove-item something

The main complication is when it's something within a pipeline:

get-item foo* | sudo remove-item

@SteveL-MSFT At least the concept is not that complex. Please tell me what you think.

We simply need a combination of the sudo, su and login binaries, to handle all cases.

It needs to do:

  • Create a unix socket for callbacks and only allow the destination user access to it.
  • Validate that the caller is allowed sudo access (I think one can simply copy the source code of su, sudo and login)

    • If /etc/sudoers exists, it needs to be parsed



      • Only specific commands


      • By using the destination users password


      • Without validating credentials (passwordless)



    • If it does not, one needs to invoke pem to check if the user "knows" the credentials for the user root directly.

    • If he also does not know the destination users credentials, deny access and throw an exception in powershell.

  • If the validation passed, we need to switch the user context into either root, or the destination user.
  • Once we switched the user context the new process needs to establish communication back to the original powershell running by connecting it to the unix socket.
  • If the user enters "exit", we signal over the unix socket, that we're finished and as we exit, the user will automatically return to the callers privileges, so we only need the hosting powershell to display a prompt or execute the next instruction.
  • If instead the host powershell terminates, the unix socket gets closed and the elevated powershell should halt execution and terminate, just like if one closes the terminal.

Execution flow would look like this:
PWSH (creates socket /proc/self/change-user.socket) => PWSH-SU (invoked with the socket and destination user as parameter; PWSH-SU is set suid to run as root itself) => PWSH as destination user connects to the unix socket.

The most time consuming part is to allow the powershell to connect internally over a unix socket. Just redirecting input and output linke other unix applications do is not enough, as we deal with objects and not just with strings when invoking pipes.

Why use all three binaries?
sudo is required to allow multiple users to switch into root context without losing auditability.
su is used to switch into any other user by using the destination users credentials.
login is used to create a whole new login session.
Having all of these functionality also in powershell can be useful in many cases, compared to only have one.

Using pipes could make this work on Windows too in a manner that is less surprising and more convenient - I hate that I get another shell with all "sudo" scripts + UAC clicking but with pipes like this it could be done within the same shell just like on linux by communicating over pipe with another interpreter already running as admin and maybe implementing some real sudo stuff (prompt timeout for example or sudoers file with commands as alternative to custom powershell endpoints)

I'm really happy to see the thoughts on this, but as far as the actual implementation, it seems to me we're getting a little ahead of ourselves. The first thing is the system needs a way to create an elevated process, thread, whatever from an unelevated one. None of the cmdlet concerns can truly be solved if we can't create an elevated instance of PowerShell to start with, without going through UAC. IMO, the first scenario to be addressed here should be - you have a limited SSH session - how do you execute a regular exe with admin permissions?

I started experimenting with this here (currently broken as I've been refactoring it, but the concept works), but I don't think a 3rd-party app is the real solution. I'd like to see Windows ship a 'sudo' exe first. This could be as simple as enabling runas to create elevated process with a credential prompt, but without the first step this is all theoretical.

None of the cmdlet concerns can truly be solved if we can't create an elevated instance of PowerShell to start with, without going through UAC

One possibility to do this involves using scheduled task with option 'run with highest privelege'.

Yeah but to create that, you have to already have admin permissions right? That's what psexec does. As far as I know, right now, you have to at some point go through UAC. I'd like to see that change, and with all SSH sessions being elevated, it's sort of a security concern. If some sketchy software tries to SSH into my Windows machine, say from another computer where I have a private key set up (or the loopback scenario), it can do anything it wants.

@parkovski My solution was Linux/MacOS and all other *NIX OSes only. Windows does not support SUID and GUID.
As sudo does currently also not exist on Windows, it is out of scope of this issue for me.

And to solve the UAC problem, windows should implement SUID and GUID in the future. Everything else is just a dirty workaround for a longstanding issue...

Yeah but to create that, you have to already have admin permissions right?

Right, but it doesn't trigger UAC popup.

UAC can also be skipped the official way with Microsoft's Application Compatibility Toolkit.

Windows does not support SUID and GUID.

Windows doesn't have to support it and concept is not valid on that OS.
Its permission model is based on ACL's and there is no single group ownership.

It also doesn't have to be full sudo replica on windows, just a more friendly way to invoke admin commands.

I think it's fine to defer Windows support as Windows users are probably accustomed to opening an elevated PowerShell session today while Linux users expect to run as non-root and sudo as needed. We just want to make sure any design doesn't preclude future Windows support. I would also probably focus on simply enabling sudo for root rather than any arbitrary user to simplify it and I believe this is 90+% of the usage.

@SteveL-MSFT

would also probably focus on simply enabling sudo for root rather than any arbitrary user

I think this will not make a big difference, but provide the full su/sudo experience for the abstract I've outlined above, as switching user context to root is nearly the same as switching to any other user.

I think it's fine to defer Windows support as Windows users are probably accustomed to opening an elevated PowerShell session today

Majority of the people I worked with just disable UAC if they can.

Unfortunately, that isn't really an option in many environments, and I very much doubt MS is going to up and ditch UAC completely. 😕

This issue is not about UAC. But from my point of view, it should be ditched entirely and either be replaced with a strict two accounts one admin one user (and the admin one cannot be used for logon) philosophy (the default installation forces you to create them) or for the same concept *NIX has, you start as user and elevate as needed by using sudo and SUID/SGID-Flags.

I recently added the following to my $profile. I covered it in more detail over at https://stackoverflow.com/a/56265080/118098

function Invoke-MySudo { & /usr/bin/env sudo pwsh -command "& $args" }
set-alias sudo invoke-mysudo

At least on the face of it, this works for me, and allows "sudo ". This doesn't cover the case of "able to sudo a cmdlet within an existing PowerShell Core session" per https://github.com/PowerShell/PowerShell/issues/3232#issuecomment-354853084

However, I wonder how important it is to give the elevated context the entire session of the calling command. In other shells, sudo still runs the provided command in a new context.

I have implemented a basic sudo that works well for running commands as administrator on Windows. I'm not sure if this would also work on linux/mac, as I don't know if "RunAs" elevates correctly or not on those platforms.

Edit your profile:

PS > notepad $PROFILE

Add the following sudo function:

function sudo {
    Start-Process -Verb RunAs -FilePath "pwsh" -ArgumentList (@("-NoExit", "-Command") + $args)
}

Then invoke in your shell. Supports cmdlets, executables, anything that could normally be typed into a PS prompt:

PS > sudo Remove-Item .\test.txt  # Remove a file
PS > sudo Copy-Item .\test.txt C:\  # Copy a file
PS > sudo net start w3svc  # Start IIS

If you want to pass in a variable or expression that will be evaluated at run time, rather than pre-evaluated, wrap it in braces. For example:

PS > $myvar = "a"
PS > sudo echo $myvar  # $myvar is pre-evaluated, so the command reads: sudo echo "a"
PS > sudo { $PSVersionTable }  # with braces, $PSVersionTable is not evaluated until it is run as administrator

Remove "-NoExit" from the sudo function if you'd prefer to have the administrator window close when complete.

@vsalvino This is a useful workaround when GUI is available and is helpful in the meantime, but this is still not a real sudo because it doesn't work without GUI access. In a remote shell (ssh), literally the only way to make this work is a service and client as I tried to demonstrate here.

To address some common suggestions, because believe me I've looked at every possibility:

  • Disabling UAC is not a solution. It's a workaround that can be made as a personal choice but it's not a general solution to this problem.
  • Anything that pops up UAC (every "sudo" script I've seen) is not a solution, including doing it once to start an elevated remote session.
  • Anything that requires GUI _at all_ is not a solution. Let's assume we're using ssh here and GUI is not available.
  • Anything that requires major changes to Windows is not a solution. We can't count on UAC turning into something better.
  • Even a signed binary from Microsoft is not a solution, because it won't work when UAC is set to high (I got this wrong on the wsudo readme; I'll correct it later).
  • The only real solution to sudo on Windows is a service that elevates user processes on successful authentication. I'd love to hear other ideas but please do your research first.

Basically, somebody is going to have to do a lot of work, no way around it. What we want is something that, once PowerShell supports this on Unix, is a drop in replacement on Windows, and works as you'd expect sudo to work (no GUI, no UAC).

Can we please clarify the scope of this issue first? I think multiple people are talking about different topics right now.
Is this issue:
a) About implementing sudo within powershell for linux/mac systems?
b) Implement a sudo replica into windows?
c) Allow to elevate privileges when psremoting?
d) Allow to impersonate other users on windows?
e) Allow to switch from a non privileged user account to a privileged user account?
f) something completely different?

For a) https://github.com/PowerShell/PowerShell/issues/3232#issuecomment-444849067
For b) Same as a (windows also has unix sockets), but instead of a suid binary it needs to be spawned by a service (running within a user that has "act as part of the operating system" privilege e.g. user system) and that service also needs to check privileges. Or implement SUID/GUID concept on windows.
For c) not required you already have highest privileges when remoting. There is no privilege separation when accessing remote hosts (There have also already been some localhost loopback UAC bypasses that worked this way).
For d) Also the approach from a/b can be taken, but I don't know how that should work when trying to access network resources, without knowing the users credentials or crafting a new windows/activedirectory authentication backend.
For e) Same as b, but credential checking is also required, alternatively the runas api could be loosened to allow one knowing username and password to get a new user token and keep control over that process. (Unlikely considering the UAC security concepts and considerations, so we're back at b).

IMO this issue should be about implementing sudo in PowerShell where the underlying functionality already exists. Discussion about a sudo equivalent for Windows is probably more appropriate in this terminal issue.

Discussion about a sudo equivalent for Windows is probably more appropriate in this terminal issue.

Why would terminal app be a better place to discuss sudo, given that its only yet another frontend to the CLI world ? By the same logic you could file a ticket at ConEmu repository.

IMO this issue should be about implementing sudo in PowerShell where the underlying functionality already exists.

One of the points of the next Powershell is less compatibility issues between systems using it. Regarding that, doing something only on system X is IMO not acceptable.

I as a CLI user couldn't care less if sudo is full blown linux sudo using suders file or some windows alike. Sudo is just an interface to elevation features of the OS. Such an interface could be made to work near identically regardless the 'backend'.

Otherwise, @parkovski point about GUI stands - I would just add Windows Core among the reasons why.

Why would terminal app be a better place to discuss sudo, given that its only yet another frontend to the CLI world ? By the same logic you could file a ticket at ConEmu repository.

Because that repo is not just "a terminal app"; the team that runs it basically owns the text-mode parts of Windows and has already said they're interested in implementing sudo when they can find the time. On the other hand, nobody from the PowerShell team nor ConEmu has offered.

The reason why I think Windows sudo is out of scope here is that we've already determined that doing it right is a pretty big amount of work and is orthogonal to PowerShell itself. PowerShell can use it when it exists, but it's really an independent component from any particular shell.

On the other hand, PowerShell being able to run cmdlets through a sudo binary, regardless of platform or how that binary actually works, is totally a thing that has to be a part of PowerShell, which belongs right here.

I as a CLI user couldn't care less if sudo is full blown linux sudo using suders file or some windows alike. Sudo is just an interface to elevation features of the OS. Such an interface could be made to work near identically regardless the 'backend'.

Yep, it absolutely should. It's just that sudo doesn't exist yet on Windows, is gonna take a lot of work, and is probably not gonna be written by the PowerShell team. When such a thing exists, let's hope PowerShell implements this in a way where it'll just work on Windows too.

Anyways, I'm gonna defer further comments until we get an official response here because this issue is going in all sorts of different directions.

Any opinion on this ?
http://blog.lukesampson.com/sudo-for-windows
Installed with scoop install sudo, its the closest I can think of. It works like unix sudo - run commands with elevation. I use it with pip or Install-Module for all users.

Sudo for Windows

@Restia666Ashdoll If it is renamed to Invoke-ElevatedCommand I'm fine with that.
That's because sudo is not only responsible for elevating commands, but also for impersonating users and "dropping" (sudo -u nobody command) privileges. Also reusing already existing names already has proven to be a bad idea, especially if the functionality and parameters differ.
I already outlined above what a true sudo with impersonation would look like and how it could work.

@Restia666Ashdoll Please read this comment in this thread.

@parkovski Thats just a wrapper for for -Verb RunAs, which only works with a few commands. The one I linked to can be used almost with everything. For example I use it like this - sudo pip install httpie.

You didn't read my post did you?

I don't suppose there's any way to get the title edited to include something like "NOT A SUDO ON WINDOWS DISCUSSION"? I know I'm not personally under any obligation to keep answering this, but people keep showing up saying the same thing without doing their research.

I tried to click this guy's unsubscribe link and it unfortunately won't let me do that without being logged in as him.

I've reported @troymoore to GitHub already

I would like to propose a unique and different solution that I have not seen talked about here. What about using something like named pipes to serialize commands to an elevated process which then returns it's serialized output to the calling process?

Here is a functioning module that demonstrates how this would work on NT: https://github.com/mmillar-bolis/Invoke-AsAdmin

It's not perfect, of course, but it accomplishes elevating simple tasks and piplines without opening another console. I do not intend to pitch this as a sudo-alike per se as I don't believe cloning sudo's design will be the best long-term solution, but I thought that a different approach to this nebulous elevation problem might further constructive discussion.

EDIT: I should also mention, this will not accomplish the request of @parkovski for UACless elevation.

It looks like JEA.
As for serialization, not all modules support this.

It looks like JEA.

Yes, that is the idea.

As for serialization, not all modules support this.

As you probably saw in the code, this is mitigated with text streams that reconstruct the code on the other end of the pipe. I admit that this is slow, but nonetheless a novel workaround. Your mention of JEA was again an influential factor here; if some part of one's code does not need to be elevated, it should not be.

The module is meant to solve a very specific problem of elevating interactive commands within GUI sessions on NT and nothing more. The thing was started like five years ago before anyone imagined native ssh might be a thing for NT. I agree with @parkovski that this an issue related to how NT handles elevation, so without a service listening for and providing a contoured form of command elevation, it is rather difficult to achieve an ease of use case similar to sudo, pkexec or doas.

Yet, instead of being halted by a nirvana fallacy that a sudo-like implementation must exist on NT before PowerShell can support any form of command elevation, why don't we first push for any form of JEA interactive elevation within the shell session?

This would at least promote improved security practice in the NT world. Why not implement both a cmdlet to run interactively, and one to start a separate console session? Or even better, just promote the current ways to start an elevated session alongside a more spartan set of cmdlets with different use cases? It's at least a step forward.

I might also add that even the Python elevate library cannot do what this module does. Have you found another module to not work with it already? Because my main point is that maybe smarter minds than mine can take this module and it's ideas and run with it in a direction that will fit for NT. After that, we may have the beginnings of a platform for NT and *nix to meet in the middle, allowing us to revise a more common implementation for PowerShell to elevate commands.

That's my two cents, at least. But having seen the code, if one feels that the ideas within are no good, I will understand. I just had not seen anyone even try something like this yet.

Gonna step back from my frustrated grievings of explaining the point of sudo for a minute because (a) yes this is a very difficult problem, (b) can really only be solved properly by MS (thanks for not being open source, Windows), (c) it really is cool to see that others are passionate about this too.

I know how hard it is to do this properly because I started down that road. So if the only thing keeping us from that for now is a UAC dialog, so be it. At least this way we can test a cross platform solution with a minor effort.

What I'd personally like to see from PowerShell is comprehensive support for the Unix sudo, but designed to support some form of "pseudo-sudo" script as it is now as well as a future potential real Windows sudo. My thought is that if someone prototypes out how a Windows sudo will eventually work but leaves the UAC restriction, it should be fairly straightforward, give us something that's basically as good as it gets for now, and when we get the real thing it should pretty much just be a drop-in replacement.

Obviously this means someone's going to have to come up with a model that understands or at least translates to both the Unix uid/gid model and the Windows sid/acl model. Hopefully this person likes a challenge. Guessing this will also require some talks with the terminal and windows security teams within MS.

I guess that with as many people having created their own best-effort workarounds, and that supporting something like this could well help design a robust way of doing this, why not?

Sidenote - anyone writing these workaround scripts might consider the timeout feature that sudo has, as annoying as that popup is.

We could think about Start-Process pwsh -NoNewWindow -Credential $cred. It does not work but could.

Obviously this means someone's going to have to come up with a model that understands or at least translates to both the Unix uid/gid model and the Windows sid/acl model. Hopefully this person likes a challenge. Guessing this will also require some talks with the terminal and windows security teams within MS.

Unix also has acls and windows has posix compatibility and at least if it is domain joint there is also a primary group attribute that we could use (as well as posix attributes). It just would need to be implemented for non domain joined windows clients (or for now assumed to be User).

The generic model for unix and windows permissions is therefore basically:
ACLs with an Owning User and an Owning Group with some expected ACEs (user, group and other).

Than we could map the unix permissions as:
uid => Owner SID
gid => The primary-group SID of the user who created the object.
user => Creator Owner ID S-1-3-0
group => Creator Group ID S-1-3-1
other => World/Everyone S-1-1-0
Mapping the uids from the acl list on unix is a bit more complicated as we need to consider that the system may be part of an ldap, active directory, or any other directory. The only two cases I would consider in scope for powershell are no directory and ldap/active directory.
In the first case I'd suggest using S-1-6-1-uid and S-1-6-2-gid (assuming S-1-6 is still available and the responsible team is willing to allocate it for this purpose).
And for the 2nd case we just need to have some sort of resolving the uid though the authentication backend. The ldap/active directory server is than responsible for providing an sid.
And finally there are some special cases to map:
uid 0 => S-1-5-32-544
gid 0 => S-1-6-500 (and S-1-5-21-*-500)
most other well-known sids can be managed through a config file or through an api of some sort (or just drop them as they are most likely not used anyway)

If we do this in the shell build in commands like Get-Acl/Set-Acl would than start to work on unix systems without knowing about how the permissions are stored on disk.

@mmillar-bolis I already suggested an approach using sockets here: https://github.com/PowerShell/PowerShell/issues/3232#issuecomment-444849067

We could think about Start-Process pwsh -NoNewWindow -Credential $cred. It does not work but could.

Update: .Net Core (and I guess Windows API too) doesn't allow to run new process attached to the same console.

So single way we can use is a elevated Windows Service. But we have to create such service process per "sudo" to be secure.
So solution will be New-PSSession (or invoke in PSSession) to localhost with elevated user credentials.

@iSazonov One of the only things that would allow you to attach it to the same console is what I already mentioned here: https://github.com/PowerShell/PowerShell/issues/3232#issuecomment-444849067

Now that windows supports unix sockets, we could use either them or named pipes and the privileged service would be responsible for validating credentials and would need to run all time (compared to be invoked over suid as mentioned in the linked posting for *nix oses).

Maybe lsas would/could need to be extended to provide such authentication api capabilities?
That way we could get full impersonation while still being able to securely attach to the same console and accepting inputs.

@agowa338 Your proposal "de-facto" is PowerShell remoting. It is already implemented.

But

So solution will be New-PSSession (or invoke in PSSession) to localhost with elevated user credentials.

does not work for localhost. It only throws AccessDenied.

Except one of these is the case:

  • UAC is off
  • you try to connect to BUILDIN\Administrator without Admin Approval Mode being enabled.
  • the process (powershell) is already elevated.

Here is a good explanation why that is by @jborean93: https://github.com/PowerShell/Win32-OpenSSH/issues/1308#issuecomment-448430464

Therefore we need a privileged service acting as a broker or one of the APIs need to change, but that's not something we could do within PowerShell/PowerShell and would need to be delegated by the Microsoft people internally.

@agowa338 Comment you referenced is about local Windows API, not PowerShell remoting that was a question there.

@iSazonov: Have you even tried doing powershell remoting to localhost? I did and it does not work for the reasons outlined above. The assignment of the accesstoken is blocked by the os.

PowerShell remoting to localhost does not allow to get elevated privileges on the local computer.

PowerShell remoting however grants you elevated privileges on all other hosts in the network except localhost (assuming you're member of Domain-Admins, etc).

That's the reason why we need a sudo equivalent on windows. If PowerShell remoting would behave that way you think it does this ticket could be closed by writing an example into the docs as the functionality would already exists.

@agowa338 It does not work for you because of security protection. It is not OS feature. You can configure WinRM as described in docs https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_remote_troubleshooting . Issue you referenced also says that this works for SSH (steps are in referenced there article).

as the functionality would already exists.

Request is to get working "sudo Remove-Item foo.txt where foo.txt is owned by root".
It does not works but we would want.
The problem consists of two parts: syntax sugar in language and implementation.

If you think more about your proposal you discover that you need to have per user/per session/per runspace/per scope powershell context. Then you have to address security compliance requirements and you will get "access denied" in default configuration. After that your proposal will the same as already implemented PowerShell remoting.

It does not work for you because of security protection. It is not OS feature. You can configure WinRM as described in docs

@iSazonov Can you elaborate that a bit more? I can remote to that machine and from any machine to any other machine in the network, but from none of them to localhost. And yes I read that page.

Request is to get working "sudo Remove-Item foo.txt where foo.txt is owned by root".

For non windows systems we could use the unix socket approach to implement impersonation/elevation for powershell remoting there.

Can you elaborate that a bit more? I can remote to that machine and from any machine to any other machine in the network, but from none of them to localhost. And yes I read that page.

Most attacks target local elevation. So all configs is "secure by default". WMI, WinRM, IIS loopback and etc - all subsystems disable features which allows local elevations.
It is not so important for the discussion. Even if PowerShell remoting does not allow us to do sudo by default, we could implement it turned off by default or allow only for an interactive session.

You started talking about windows, for non windows systems we could use the unix socket approach to implement impersonation/elevation for powershell remoting there.

We should have the same UX for all platforms. Really there PSRP works over a transport - WinRM or SSH. MSFT said that they like SSH but I do not see any noticeable progress over the past two years. And it's unbelievable that they will want a third protocol in the _near_ future - too much work (the need to maintain compatibility with old systems).

Most attacks target local elevation. So all configs is "secure by default". WMI, WinRM, IIS loopback and etc - all subsystems disable features which allows local elevations.
It is not so important for the discussion. Even if PowerShell remoting does not allow us to do sudo by default, we could implement it turned off by default or allow only for an interactive session.

I tried to enable that a while ago, and I was told repetitively by many others that this is restricted by the os internally and it is not possible in any way without an application hooking deep into windows internals. In fact many have pointed at the above referenced windows api restrictions and used that as argument for why powershell could never provide such capability. And someone even referenced an CVE where loopback elevation was intentionally removed. Therefore apologies going down that rabbit hole a bit deeper, but what do I need to configure for it to work? Is that even documented anywhere?

We should have the same UX for all platforms. Really there PSRP works over a transport - WinRM or SSH. MSFT said that they like SSH but I do not see any noticeable progress over the past two years. And it's unbelievable that they will want a third protocol in the near future - too much work (the need to maintain compatibility with old systems).

Well than we should push forward either of both solutions as both work on any platform.

  • PSRP: SSHing to localhost works for elevation on Windows and Linux, therefore using the psrp subsystem we already have the correct permissions, so only the powershell layer has to be uniformed to allow passing objects. Right?
  • Using unix sockets would also provide a similar functionality like powershell remoting, but as time of writing I assumed it is a hard limitation to do local elevation without any kind of additional service running as local system to perform token swapping...

Therefore as powershell remoting is already there (and also kinda works over ssh already) we should prioritize that solution I think.

And someone even referenced an CVE where loopback elevation was intentionally removed.

I cannot confirm. I guess the CVE could just disable loopback by default but not at all.
See also https://github.com/PowerShell/PowerShell/issues/3874#issuecomment-510715727

@iSazonov: That does not work, it only provides the low privilege access token but not the elevated access token (e.g. Mandatory Label\High Mandatory Level). I do not get Administrative permissions out of a low privilege powershell even though TrustedHosts is set to * for me. The logon token is always of type interactive, even after Enter-PSSession.
I can in fact Enter-PSSession localhost -ScriptBlock {} but passing credentials causes "Access Denied"., nope it always throws "Access Denied" that other system had uac disabled.

But I now tried it also using SSH and that works as expected it provides the elevated token (Mandatory Label\High Mandatory Level) with logon type Network.

Therefore in PSCore we can rely upon psrp for elevation (even locally through Enter-PSSession -HostName localhost that also works with explicit credentials being passed.
Where Enter-PSSession -ComputerName localhost -Credential $foo does not (even if $foo.Username is the same as the current user)

@agowa338 I think we should not discuss bypassing security features of WinRM here (it is compliance sensetive area). I can only indicate (1) that regardless of a protocol, security should remain at the same level, which implies that SSH loopback should behave the same as for WinRM taking in account how Windows internals work, (2) PS sudo implementation should works over any transport.

@iSazonov: I did not ask for an exploit, but only for what needs to be configured to enable it. Also you seam to be the only one that figured out how to configure WinRM in order to allow loopback elevation.
I've tried to enable that for a very long time. All questions (on stackoverflow, reddit, github issues, ...) I come across end in "windows is wird", "don't know what windows does there", "It is not documented anywhere", "Windows does not provide that capability", "Use Linux instead", "Disable UAC", "You need to write a broker service that runs with system privileges". So please if you figured it out, share your knowledge.

I can only indicate (1) that regardless of a protocol, security should remain at the same level

What do you mean with that?

which implies that SSH loopback should behave the same as for WinRM taking in account how Windows internals work

Well SSH has a system service that acts as a broker in the background to do exactly that. It provides a Network access token...

(2) PS sudo implementation should works over any transport.

Well it does not over WinRM for exactly that reason. So if it is true what you said we need documentation for how to enable loopback WinRM.

if you figured it out, share your knowledge.

@agowa338 MSFT team asked me do not discuss security publicly and I follow the CoC. I support your desire to explore this topic deeply, but as part of this discussion, this is a headache for MSFT how to integrate this solution into Windows and keep security compliance.

Well that does not help anyone.

To summon it up:

  • You say windows has sudo like capabilities within WinRM.
  • It's neither documented that it exists nor how to enable/disable it.
  • Disclosing how to use it would be a security risk.

Sorry, but that sounds like a backdoor and not a feature. It is unusable for anyone except you than.
Also security through obscurity has not worked in the past either...

So we're back at it's currently not implemented and we need a broker service than...

@agowa338 We have gathered enough information for MSFT team to conclude. If they find security issues, they will show us an acceptable alternative way.

It was possible but was patched earlier this year https://devblogs.microsoft.com/powershell/windows-security-change-affecting-powershell/ with the patch KB4480116 and any subsequent cumulative updates.. Before this update it was possible to elevate your privileges if you have the LocalAccountTokenFilterPolicy set to 1 which is what winrm quickconfig does (and is required for WinRM really).

There's a note there saying JEA endpoints are not affected so potentially you could create your own PSSessionConfiguration and connect to that but I haven't tested this to verify. Personally I think this patch is silly as this patch just stops the PowerShell client from connecting to localhost but you can easily bypass it if you know what you are doing. For example I can still go from limited to elevated without touching UAC by using SSH or another PSRemoting client like so

PS C:\Users\vagrant> whoami.exe /groups  # prove the current process is limited

GROUP INFORMATION
-----------------

Group Name                                                    Type             SID          Attributes

============================================================= ================ ============ ============================
======================
Everyone                                                      Well-known group S-1-1-0      Mandatory group, Enabled by
default, Enabled group
NT AUTHORITY\Local account and member of Administrators group Well-known group S-1-5-114    Group used for deny only

BUILTIN\Administrators                                        Alias            S-1-5-32-544 Group used for deny only

BUILTIN\Remote Management Users                               Alias            S-1-5-32-580 Mandatory group, Enabled by
default, Enabled group
BUILTIN\Users                                                 Alias            S-1-5-32-545 Mandatory group, Enabled by
default, Enabled group
BUILTIN\Performance Log Users                                 Alias            S-1-5-32-559 Mandatory group, Enabled by
default, Enabled group
NT AUTHORITY\REMOTE INTERACTIVE LOGON                         Well-known group S-1-5-14     Mandatory group, Enabled by
default, Enabled group
NT AUTHORITY\INTERACTIVE                                      Well-known group S-1-5-4      Mandatory group, Enabled by
default, Enabled group
NT AUTHORITY\Authenticated Users                              Well-known group S-1-5-11     Mandatory group, Enabled by
default, Enabled group
NT AUTHORITY\This Organization                                Well-known group S-1-5-15     Mandatory group, Enabled by
default, Enabled group
NT AUTHORITY\Local account                                    Well-known group S-1-5-113    Mandatory group, Enabled by
default, Enabled group
LOCAL                                                         Well-known group S-1-2-0      Mandatory group, Enabled by
default, Enabled group
NT AUTHORITY\NTLM Authentication                              Well-known group S-1-5-64-10  Mandatory group, Enabled by
default, Enabled group
Mandatory Label\Medium Mandatory Level                        Label            S-1-16-8192

PS C:\Users\vagrant> ssh vagrant@localhost whoami.exe /groups  # prove that SSH is elevated
vagrant@localhost's password:

GROUP INFORMATION
-----------------

Group Name                                                    Type             SID          Attributes

============================================================= ================ ============ ============================
===================================
Everyone                                                      Well-known group S-1-1-0      Mandatory group, Enabled by
default, Enabled group
NT AUTHORITY\Local account and member of Administrators group Well-known group S-1-5-114    Mandatory group, Enabled by
default, Enabled group
BUILTIN\Administrators                                        Alias            S-1-5-32-544 Mandatory group, Enabled by
default, Enabled group, Group owner
BUILTIN\Remote Management Users                               Alias            S-1-5-32-580 Mandatory group, Enabled by
default, Enabled group
BUILTIN\Users                                                 Alias            S-1-5-32-545 Mandatory group, Enabled by
default, Enabled group
NT AUTHORITY\NETWORK                                          Well-known group S-1-5-2      Mandatory group, Enabled by
default, Enabled group
NT AUTHORITY\Authenticated Users                              Well-known group S-1-5-11     Mandatory group, Enabled by
default, Enabled group
NT AUTHORITY\This Organization                                Well-known group S-1-5-15     Mandatory group, Enabled by
default, Enabled group
NT AUTHORITY\Local account                                    Well-known group S-1-5-113    Mandatory group, Enabled by
default, Enabled group
NT AUTHORITY\NTLM Authentication                              Well-known group S-1-5-64-10  Mandatory group, Enabled by
default, Enabled group
Mandatory Label\High Mandatory Level                          Label            S-1-16-12288

PS C:\Users\vagrant> python -c "from pypsrp.client import Client; c = Client('localhost', username='vagrant', password='
<password>', ssl=False); print(c.execute_ps('whoami.exe /groups')[0])"

GROUP INFORMATION
-----------------

Group Name                                                    Type             SID          Attributes

============================================================= ================ ============ ============================
===================================
Everyone                                                      Well-known group S-1-1-0      Mandatory group, Enabled by
default, Enabled group
NT AUTHORITY\Local account and member of Administrators group Well-known group S-1-5-114    Mandatory group, Enabled by
default, Enabled group
BUILTIN\Administrators                                        Alias            S-1-5-32-544 Mandatory group, Enabled by
default, Enabled group, Group owner
BUILTIN\Remote Management Users                               Alias            S-1-5-32-580 Mandatory group, Enabled by
default, Enabled group
BUILTIN\Users                                                 Alias            S-1-5-32-545 Mandatory group, Enabled by
default, Enabled group
NT AUTHORITY\NETWORK                                          Well-known group S-1-5-2      Mandatory group, Enabled by
default, Enabled group
NT AUTHORITY\Authenticated Users                              Well-known group S-1-5-11     Mandatory group, Enabled by
default, Enabled group
NT AUTHORITY\This Organization                                Well-known group S-1-5-15     Mandatory group, Enabled by
default, Enabled group
NT AUTHORITY\Local account                                    Well-known group S-1-5-113    Mandatory group, Enabled by
default, Enabled group
NT AUTHORITY\NTLM Authentication                              Well-known group S-1-5-64-10  Mandatory group, Enabled by
default, Enabled group
Mandatory Label\High Mandatory Level                          Label            S-1-16-12288

We can see that using SSH we have an elevated token, we can also see that using a 3rd party library we can still use localhost PSRemoting that creates an elevated token and that the patch is not a total block of this functionality.

I don't see this as a security issue or crossing a security boundary as MS has repeatedly said that UAC is not a security boundary

It might be close or act similar to one but it is not foolproof. One of those ways of bypassing UAC is the known and documented LocalAccountTokenFilterPolicy registry property. The explicit purpose of this property to ensure that network logons are always elevated and not the filtered token and it explicitly says that not having this enabled prevents "loopback" attacks

To better protect those users who are members of the local Administrators group, we implement UAC restrictions on the network. This mechanism helps prevent against "loopback" attacks. This mechanism also helps prevent local malicious software from running remotely with administrative rights.

Ultimately what that means is there is no really official way on Windows to elevate your privileges from limited to an admin in a non-interactive fashion. It's quite simple to use Start-Process ... -Verb Runas but that requires an interactive logon to display the UAC prompt. Having a sudo-like mechanism would help alleviate this problem but to do it properly would require work in Windows itself and not be PowerShell specific. There are "workarounds" but I wouldn't call them official and are just a known byproduct of enabling WinRM.

PowerShell
Windows Security change affecting PowerShell January 9, 2019 The recent (1/8/2019) Windows security patch CVE-2019-0543, has introduced a breaking change for a PowerShell remoting scenario. It is a narrowly scoped scenario that should have low impact for most users. The breaking change only affects local loopback remoting,
Mark's Blog
I introduced the -l switch to PsExec about a year and a half ago as an easy way to execute processes with standard-user rights from an administrative account on Windows XP. In Running as Limited User – The Easy Way I described how PsExec uses the CreateRestrictedToken API to create a security context that’s a...
Engineering Windows 7
Hi, Jon DeVaan here to talk to you about the recent UAC feedback we’ve been receiving. Most of our work finishing Windows 7 is focused on responding to feedback. The UAC feedback is interesting on a few dimensions of engineering decision making process. I thought that exploring those dimensions would make for an interesting e7...

@iSazonov None of these suggestions will accomplish a _user-interactive_ command elevation from _within the same console session_, especially in an environment that _lacks UAC_. It appears that you can speak on behalf of Microsoft in these matters, so would you clarify whether they are simply not interested in in introducing such a feature as I have described it?

If that is the case, as I have interpreted from the above posts, it seems prudent to close this thread, as the rest of us users will have to look elsewhere for solutions such as @parkovski's TokenServer idea.

It appears that you can speak on behalf of Microsoft in these matters

I am a community maintainer of the project, not MSFT member and I can not speak on behalf of Microsoft.

would you clarify whether they are simply not interested in in introducing such a feature as I have described it?

_All proposals have value; none of them are rejected. The discussion is just for collecting all possible proposals._

Currently I am trying to summarize all proposals so that we can move forward and not stagnate.

That I see.
Main scenario is adoption Unix users on Windows.

  • Historically Unix users works in one console and sudo natively helps them to do a work with elevated rights in the _same_ console
  • Historically Windows users open new window with elevated rights console if needed. This works well many years because it’s convenient in a multi-windows environment. (Windows users could benefit from pssudo too taking in account Windows Core and Nano)

So expectations are:

  • pssudo works only in interactive sessions
  • pssudo does not open new console (UAC window is acceptable on Windows, we don't want break Windows security and spirit)
  • pssudo timely cache credentals
  • pssudo does not cache a session state for security
  • the same UX (as possible) is on all platforms
  • pssudo runs native commands
  • pssudo runs PowerShell script blocks/files

Implementation details:

  • PowerShell remoting is most power and functional solution. It is already implemented and works. Others would have to emulate this functionality too to excecute PowerShell script blocks in per user/per session/per runspace/ per scope state.
  • Preferred transport is WinRM because all Windows infrastructure based on it. Some investment is required in WinRM, although MSFT does not want this because it is based on SOAP.
  • SSH transport could be. This is still not the standard for Windows. Requires a large investment for implementation and maintenance. And there is a problem supporting older systems.
  • Other transports like Unix sockets. Requires a large investments not only in infrastructure but in PowerShell too.

@mklement0 I wonder that I do here that you do usually great :-) You rob me of being an opponent :-)

Why not write an windows binary that requires privileges that starts a powershell instance with whatever commands passed to it. It would have to be a console mode app to work properly. Then for linux, we write a script that requires permissions that starts a powershell instance with the commands provided. If this works in practice like it does in theory, powershell will be launched with elevated permissions, runs the commands and exits.

Why not write an windows binary that requires privileges that starts a powershell instance with whatever commands passed to it. It would have to be a console mode app to work properly.

Cause the windows API prevents that and the console app would open in a new window. We already talked about possible workarounds.

One thing to keep in mind is that no matter how this gets implemented, there is always a process hop to and from an elevated process. This means that you'll always have deserialized objects in the pipeline and those limitations will apply. In many cases, this won't be an issue, but if a cmdlet expects a live .NET object, then it won't work.

To support JEA with SSH, we would eventually need a generalized daemon/service that replaces the need for WinRM as that service anyways. At that time, we would evaluate using that to elevate a part of the pipeline.

FYI: https://github.com/gerardog/gsudo

GitHub
A Sudo for Windows - run elevated without spanning a new Console Host Window - gerardog/gsudo

FYI: https://github.com/gerardog/gsudo

GitHubgerardog/gsudoA Sudo for Windows - run elevated without spanning a new Console Host Window - gerardog/gsudo

Even better
http://blog.lukesampson.com/sudo-for-windows

GitHub
A Sudo for Windows - run elevated without spanning a new Console Host Window - gerardog/gsudo
Sudo for Windows

Even better

No.

Gsudo doesnt prompt for password each time and is noticebly faster to install and use.

It looks to me that this issue should be accepted (which means some more time and organization should be given to it) judging from the interest not only from this ticket. Its not correct not to officially recognize it as a work task as currently perceived technical difficulties are not going to be solved without active involvement.

I am using gsudo for a few months now and I can't imagine going back to traditional Windows UAC all the time horror.

@majkinetor this issue got spun off in https://github.com/PowerShell/PowerShell/issues/11343 to further discussion on the design

Was this page helpful?
0 / 5 - 0 ratings