Skip to content

Computer cmdlets should fail with error when not run via sudo on Unix #19824

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 23 commits into from
Jul 17, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
3e3a51c
Computer cmdlets should fail with error when not run via sudo on Unix
SteveL-MSFT Jun 19, 2023
59aa58b
add tracing for test failure
SteveL-MSFT Jun 26, 2023
97210bc
fix test to skip if running as root
SteveL-MSFT Jun 26, 2023
c34bbe0
add test tracing to see if running as root
SteveL-MSFT Jun 26, 2023
9a6c5a6
change to use group id and add more traces
SteveL-MSFT Jun 26, 2023
df0337f
add back tracing of error
SteveL-MSFT Jun 27, 2023
488877e
clear the error var
SteveL-MSFT Jun 27, 2023
2553820
explicitly use out-string for error
SteveL-MSFT Jun 27, 2023
f9b68e4
add additional path to search for shutdown command, move error messag…
SteveL-MSFT Jun 27, 2023
c4c8870
trace if shutdown is found
SteveL-MSFT Jun 27, 2023
f78c1ee
add path to output
SteveL-MSFT Jun 28, 2023
cd1937c
update RunCommand for shutdown, remove unneeded string
SteveL-MSFT Jul 1, 2023
72e4b99
Update src/Microsoft.PowerShell.Commands.Management/commands/manageme…
SteveL-MSFT Jul 10, 2023
2426a18
Update src/Microsoft.PowerShell.Commands.Management/commands/manageme…
SteveL-MSFT Jul 10, 2023
c8fe455
Update src/Microsoft.PowerShell.Commands.Management/resources/Compute…
SteveL-MSFT Jul 10, 2023
63daba6
address Ilya's feedback
SteveL-MSFT Jul 10, 2023
f9a04ba
change to using command discovery
SteveL-MSFT Jul 10, 2023
f347ffb
skip test if shutdown command is not available
SteveL-MSFT Jul 10, 2023
6fd2b60
fix test
SteveL-MSFT Jul 10, 2023
69f4c07
Update src/Microsoft.PowerShell.Commands.Management/commands/manageme…
SteveL-MSFT Jul 17, 2023
702093c
Update src/Microsoft.PowerShell.Commands.Management/resources/Compute…
SteveL-MSFT Jul 17, 2023
95594d7
address Dongbo's feedback
SteveL-MSFT Jul 17, 2023
57808f5
Update src/Microsoft.PowerShell.Commands.Management/commands/manageme…
daxian-dbw Jul 17, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,13 @@

using System;
using System.Diagnostics;
using System.IO;
using System.Management.Automation;
using System.Management.Automation.Internal;
using System.Runtime.InteropServices;

#nullable enable

namespace Microsoft.PowerShell.Commands
{
#region Restart-Computer
Expand Down Expand Up @@ -36,13 +39,13 @@ protected override void BeginProcessing()
{
string errMsg = StringUtil.Format("Command returned 0x{0:X}", retVal);
ErrorRecord error = new ErrorRecord(
new InvalidOperationException(errMsg), "Command Failed", ErrorCategory.OperationStopped, "localhost");
new InvalidOperationException(errMsg), "CommandFailed", ErrorCategory.OperationStopped, "localhost");
WriteError(error);
}
return;
}

RunCommand("/sbin/shutdown", "-r now");
RunShutdown("-r now");
}
#endregion "Overrides"
}
Expand Down Expand Up @@ -78,13 +81,13 @@ protected override void BeginProcessing()
{
string errMsg = StringUtil.Format("Command returned 0x{0:X}", retVal);
ErrorRecord error = new ErrorRecord(
new InvalidOperationException(errMsg), "Command Failed", ErrorCategory.OperationStopped, "localhost");
new InvalidOperationException(errMsg), "CommandFailed", ErrorCategory.OperationStopped, "localhost");
WriteError(error);
}
return;
}

RunCommand("/sbin/shutdown", args);
RunShutdown(args);
}
#endregion "Overrides"
}
Expand All @@ -95,7 +98,7 @@ protected override void BeginProcessing()
public class CommandLineCmdletBase : PSCmdlet, IDisposable
{
#region Private Members
private Process _process = null;
private Process? _process = null;
#endregion

#region "IDisposable Members"
Expand Down Expand Up @@ -150,22 +153,52 @@ protected override void StopProcessing()

#region "Internals"

private static string? shutdownPath;

/// <summary>
/// Run a command.
/// Run shutdown command.
/// </summary>
protected void RunCommand(String command, String args) {
protected void RunShutdown(String args)
{
if (shutdownPath is null)
{
CommandInfo cmdinfo = CommandDiscovery.LookupCommandInfo(
"shutdown", CommandTypes.Application,
SearchResolutionOptions.None, CommandOrigin.Internal, this.Context);

if (cmdinfo is not null)
{
shutdownPath = cmdinfo.Definition;
}
else
{
ErrorRecord error = new ErrorRecord(
new InvalidOperationException(ComputerResources.ShutdownCommandNotFound), "CommandNotFound", ErrorCategory.ObjectNotFound, targetObject: null);
ThrowTerminatingError(error);
}
}

_process = new Process()
{
StartInfo = new ProcessStartInfo
{
FileName = "/sbin/shutdown",
FileName = shutdownPath,
Arguments = string.Empty,
RedirectStandardOutput = false,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true,
}
};
_process.Start();
_process.WaitForExit();
if (_process.ExitCode != 0)
{
string stderr = _process.StandardError.ReadToEnd();
ErrorRecord error = new ErrorRecord(
new InvalidOperationException(stderr), "CommandFailed", ErrorCategory.OperationStopped, null);
ThrowTerminatingError(error);
}
}
#endregion
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -387,4 +387,7 @@
<data name="InvalidParameterForCoreClr" xml:space="preserve">
<value>The {0} parameter is not supported for CoreCLR.</value>
</data>
<data name="ShutdownCommandNotFound" xml:space="preserve">
<value>The required native command 'shutdown' was not found.</value>
</data>
</root>
Original file line number Diff line number Diff line change
Expand Up @@ -164,9 +164,6 @@ End time: {0:yyyyMMddHHmmss}
<data name="DebuggerSourceCodeFormat" xml:space="preserve">
<value>{0}:{1,-3} {2}</value>
</data>
<data name="CommandFailed" xml:space="preserve">
<value>An error occurred while running '{0}': {1}</value>
</data>
<data name="SessionDoesNotSupportDebugger" xml:space="preserve">
<value>
The current session does not support debugging; execution will continue.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -107,3 +107,16 @@ finally
Disable-Testhook -testhookName $restartTesthookName
Set-TesthookResult -testhookName $restartTesthookResultName -value 0
}

Describe 'Non-admin on Unix' {
BeforeAll {
$skip = $false
if ($IsWindows -or [environment]::IsPrivilegedProcess -or ($null -eq (Get-Command shutdown -CommandType Application -ErrorAction Ignore))) {
$skip = $true
}
}

It 'Reports error if not run under sudo' -Skip:($skip) {
{ Restart-Computer -ErrorAction Stop } | Should -Throw -ErrorId "CommandFailed,Microsoft.PowerShell.Commands.RestartComputerCommand"
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -58,3 +58,16 @@ finally
Disable-Testhook -testhookName $stopTesthook
Set-TesthookResult -testhookName $stopTesthookResultName -Value $DefaultResultValue
}

Describe 'Non-admin on Unix' {
BeforeAll {
$skip = $false
if ($IsWindows -or [environment]::IsPrivilegedProcess -or ($null -eq (Get-Command shutdown -CommandType Application -ErrorAction Ignore))) {
$skip = $true
}
}

It 'Reports error if not run under sudo' -Skip:($skip) {
{ Stop-Computer -ErrorAction Stop } | Should -Throw -ErrorId "CommandFailed,Microsoft.PowerShell.Commands.StopComputerCommand"
}
}