// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IO;
using System.Management.Automation;
using System.Management.Automation.Internal;
using System.Management.Automation.Language;
using System.Management.Automation.Remoting;
using System.Management.Automation.Runspaces;
using System.Security;
using System.Security.AccessControl;
using System.Security.Principal;
using System.Text;
using System.Threading;
using Dbg = System.Management.Automation.Diagnostics;
using PowerShellApi = System.Management.Automation.PowerShell;
using WSManNativeApi = System.Management.Automation.Remoting.Client.WSManNativeApi;
namespace Microsoft.PowerShell.Commands
{
#region Register-PSSessionConfiguration cmdlet
///
/// Class implementing Register-PSSessionConfiguration.
///
[Cmdlet(VerbsLifecycle.Register, RemotingConstants.PSSessionConfigurationNoun,
DefaultParameterSetName = PSSessionConfigurationCommandBase.NameParameterSetName,
SupportsShouldProcess = true,
ConfirmImpact = ConfirmImpact.Medium, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096793")]
public sealed class RegisterPSSessionConfigurationCommand : PSSessionConfigurationCommandBase
{
#region Private Data
// To Escape " -- ""
private const string newPluginSbFormat = @"
function Register-PSSessionConfiguration
{{
[CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact=""Medium"")]
param(
[string] $filepath,
[string] $pluginName,
[bool] $shouldShowUI,
[bool] $force,
[string] $restartWSManTarget,
[string] $restartWSManAction,
[string] $restartWSManRequired,
[string] $runAsUserName,
[system.security.securestring] $runAsPassword,
[System.Management.Automation.Runspaces.PSSessionConfigurationAccessMode] $accessMode,
[bool] $isSddlSpecified,
[string] $configTableSddl,
[bool] $noRestart
)
begin
{{
## Construct SID for network users
[system.security.principal.wellknownsidtype]$evst = ""NetworkSid""
$networkSID = new-object system.security.principal.securityidentifier $evst,$null
## If all session configurations have Network Access disabled,
## then we create this endpoint as Local as well.
$newSDDL = $null
$foundRemoteEndpoint = $false;
Get-PSSessionConfiguration -Force:$force | Foreach-Object {{
if ($_.Enabled)
{{
$sddl = $null
if ($_.psobject.members[""SecurityDescriptorSddl""])
{{
$sddl = $_.psobject.members[""SecurityDescriptorSddl""].Value
}}
if($sddl)
{{
# See if it has 'Disable Network Access'
$sd = new-object system.security.accesscontrol.commonsecuritydescriptor $false,$false,$sddl
$disableNetworkExists = $false
$sd.DiscretionaryAcl | ForEach-Object {{
if (($_.acequalifier -eq ""accessdenied"") -and ($_.securityidentifier -match $networkSID) -and ($_.AccessMask -eq 268435456))
{{
$disableNetworkExists = $true
}}
}}
if(-not $disableNetworkExists) {{ $foundRemoteEndpoint = $true }}
}}
}}
}}
if(-not $foundRemoteEndpoint)
{{
$newSDDL = ""{1}""
}}
}}
process
{{
if ($force)
{{
if (Test-Path (Join-Path WSMan:\localhost\Plugin ""$pluginName""))
{{
Unregister-PSSessionConfiguration -name ""$pluginName"" -force
}}
}}
try
{{
new-item -path WSMan:\localhost\Plugin -file ""$filepath"" -name ""$pluginName""
}}
catch [System.InvalidOperationException] # WS2012/R2 WinRM w/o WMF has limitation where MaxConcurrentUsers can't be greater than 100
{{
$xml = [xml](get-content ""$filepath"")
$xml.PlugInConfiguration.Quotas.MaxConcurrentUsers = 100
Set-Content -path ""$filepath"" -Value $xml.OuterXml
new-item -path WSMan:\localhost\Plugin -file ""$filepath"" -name ""$pluginName""
}}
if ($? -and $runAsUserName)
{{
try {{
$runAsCredential = new-object system.management.automation.PSCredential($runAsUserName, $runAsPassword)
$pluginWsmanRunAsUserPath = [System.IO.Path]::Combine(""WSMan:\localhost\Plugin"", ""$pluginName"", ""RunAsUser"")
set-item -WarningAction SilentlyContinue $pluginWsmanRunAsUserPath $runAsCredential -confirm:$false
}} catch {{
remove-item (Join-Path WSMan:\localhost\Plugin ""$pluginName"") -recurse -force
write-error $_
# Do not add anymore clean up code after Write-Error, because if EA=Stop is set by user
# any code at this point will not execute.
return
}}
}}
## Replace the SDDL with any groups or restrictions defined in the PSSessionConfigurationFile
if($? -and $configTableSddl -and (-not $isSddlSpecified))
{{
$null = Set-PSSessionConfiguration -Name $pluginName -SecurityDescriptorSddl $configTableSddl -NoServiceRestart:$noRestart -Force:$force
}}
if ($? -and $shouldShowUI)
{{
$null = winrm configsddl ""{0}$pluginName""
# if AccessMode is Disabled OR the winrm configsddl failed, we just return
if ([System.Management.Automation.Runspaces.PSSessionConfigurationAccessMode]::Disabled.Equals($accessMode) -or !$?)
{{
return
}}
}} # end of if ($shouldShowUI)
if ($?)
{{
# if AccessMode is Local or Remote, we need to check the SDDL the user set in the UI or passed in to the cmdlet.
$newSDDL = $null
$curPlugin = Get-PSSessionConfiguration -Name $pluginName -Force:$force
$curSDDL = $curPlugin.SecurityDescriptorSddl
if (!$curSDDL)
{{
if ([System.Management.Automation.Runspaces.PSSessionConfigurationAccessMode]::Local.Equals($accessMode))
{{
$newSDDL = ""{1}""
}}
}}
else
{{
# Construct SID for network users
[system.security.principal.wellknownsidtype]$evst = ""NetworkSid""
$networkSID = new-object system.security.principal.securityidentifier $evst,$null
$sd = new-object system.security.accesscontrol.commonsecuritydescriptor $false,$false,$curSDDL
$haveDisableACE = $false
$securityIdentifierToPurge = $null
$sd.DiscretionaryAcl | ForEach-Object {{
if (($_.acequalifier -eq ""accessdenied"") -and ($_.securityidentifier -match $networkSID) -and ($_.AccessMask -eq 268435456))
{{
$haveDisableACE = $true
$securityIdentifierToPurge = $_.securityidentifier
}}
}}
if (([System.Management.Automation.Runspaces.PSSessionConfigurationAccessMode]::Local.Equals($accessMode) -or
[System.Management.Automation.Runspaces.PSSessionConfigurationAccessMode]::Remote.Equals($accessMode)) -and $haveDisableACE)
{{
# Add network deny ACE for local access or remote access with PSRemoting disabled.
$sd.DiscretionaryAcl.AddAccess(""deny"", $networkSID, 268435456, ""None"", ""None"")
$newSDDL = $sd.GetSddlForm(""all"")
}}
if ([System.Management.Automation.Runspaces.PSSessionConfigurationAccessMode]::Remote.Equals($accessMode) -and $haveDisableACE)
{{
# Remove the specific ACE
$sd.discretionaryacl.RemoveAccessSpecific('Deny', $securityIdentifierToPurge, 268435456, 'none', 'none')
# if there is no discretionaryacl..add Builtin Administrators and Remote Management Users
# to the DACL group as this is the default WSMan behavior
if ($sd.discretionaryacl.count -eq 0)
{{
[system.security.principal.wellknownsidtype]$bast = ""BuiltinAdministratorsSid""
$basid = new-object system.security.principal.securityidentifier $bast,$null
$sd.DiscretionaryAcl.AddAccess('Allow',$basid, 268435456, 'none', 'none')
# Remote Management Users, Win8+ only
if ([System.Environment]::OSVersion.Version -ge ""6.2.0.0"")
{{
$rmSidId = new-object system.security.principal.securityidentifier ""{2}""
$sd.DiscretionaryAcl.AddAccess('Allow', $rmSidId, 268435456, 'none', 'none')
}}
# Interactive Users
$iaSidId = new-object system.security.principal.securityidentifier ""{3}""
$sd.DiscretionaryAcl.AddAccess('Allow', $iaSidId, 268435456, 'none', 'none')
}}
$newSDDL = $sd.GetSddlForm(""all"")
}}
}} # end of if(!$curSDDL)
}} # end of if ($?)
if ($? -and $newSDDL)
{{
try {{
if ($runAsUserName)
{{
$runAsCredential = new-object system.management.automation.PSCredential($runAsUserName, $runAsPassword)
$null = Set-PSSessionConfiguration -Name $pluginName -SecurityDescriptorSddl $newSDDL -NoServiceRestart:$noRestart -Force:$force -WarningAction 0 -RunAsCredential $runAsCredential
}}
else
{{
$null = Set-PSSessionConfiguration -Name $pluginName -SecurityDescriptorSddl $newSDDL -NoServiceRestart:$noRestart -Force:$force -WarningAction 0
}}
}} catch {{
remove-item (Join-Path WSMan:\localhost\Plugin ""$pluginName"") -recurse -force
write-error $_
# Do not add anymore clean up code after Write-Error, because if EA=Stop is set by user
# any code at this point will not execute.
return
}}
}}
if ($?){{
try{{
$s = New-PSSession -ComputerName localhost -ConfigurationName $pluginName -ErrorAction Stop
# session is ok, no need to restart WinRM service
Remove-PSSession $s -Confirm:$false
}}catch{{
# session is NOT ok, we need to restart winrm if -Force was specified, otherwise show a warning
if ($force){{
Restart-Service -Name WinRM -Force -Confirm:$false
}}else{{
$warningWSManRestart = [Microsoft.PowerShell.Commands.Internal.RemotingErrorResources]::WinRMRestartWarning -f $PSCmdlet.MyInvocation.MyCommand.Name
Write-Warning $warningWSManRestart
}}
}}
}}
}}
}}
if ($null -eq $args[15])
{{
Register-PSSessionConfiguration -filepath $args[0] -pluginName $args[1] -shouldShowUI $args[2] -force $args[3] -whatif:$args[4] -confirm:$args[5] -restartWSManTarget $args[6] -restartWSManAction $args[7] -restartWSManRequired $args[8] -runAsUserName $args[9] -runAsPassword $args[10] -accessMode $args[11] -isSddlSpecified $args[12] -configTableSddl $args[13] -noRestart $args[14]
}}
else
{{
Register-PSSessionConfiguration -filepath $args[0] -pluginName $args[1] -shouldShowUI $args[2] -force $args[3] -whatif:$args[4] -confirm:$args[5] -restartWSManTarget $args[6] -restartWSManAction $args[7] -restartWSManRequired $args[8] -runAsUserName $args[9] -runAsPassword $args[10] -accessMode $args[11] -isSddlSpecified $args[12] -configTableSddl $args[13] -noRestart $args[14] -erroraction $args[15]
}}
";
private static readonly ScriptBlock s_newPluginSb;
private const string pluginXmlFormat = @"
{3}
{5}
{11}
";
private const string architectureAttribFormat = @"
Architecture='{0}'";
private const string sharedHostAttribFormat = @"
UseSharedProcess='{0}'";
private const string runasVirtualAccountAttribFormat = @"
RunAsVirtualAccount='{0}'";
private const string runAsVirtualAccountGroupsAttribFormat = @"
RunAsVirtualAccountGroups='{0}'";
private const string allowRemoteShellAccessFormat = @"
Enabled='{0}'";
private const string initParamFormat = @"
{2}";
private const string privateDataFormat = @"{0}";
private const string securityElementFormat = "";
private const string SessionConfigDataFormat = @"{0}";
private string _gmsaAccount;
private string _configTableSDDL;
// true if there are errors running the wsman's configuration
// command
private bool _isErrorReported;
#endregion
#region Parameters
///
/// Parameter used to specify the Processor Architecture that this shell targets.
/// On a 64bit base OS, specifying a value of 32 means that the shell is configured
/// to launch like a 32bit process (WOW64).
///
[Parameter()]
[Alias("PA")]
[ValidateNotNullOrEmpty]
[ValidateSet("x86", "amd64")]
public string ProcessorArchitecture { get; set; }
#endregion
#region Constructors
static RegisterPSSessionConfigurationCommand()
{
string localSDDL = GetLocalSddl();
// compile the script block statically and reuse the same instance
// every time the command is run..This will save on parsing time.
string newPluginSbString = string.Format(CultureInfo.InvariantCulture,
newPluginSbFormat,
WSManNativeApi.ResourceURIPrefix, localSDDL, RemoteManagementUsersSID, InteractiveUsersSID);
s_newPluginSb = ScriptBlock.Create(newPluginSbString);
s_newPluginSb.LanguageMode = PSLanguageMode.FullLanguage;
}
#endregion
#region Cmdlet Overrides
///
///
///
/// 1. Either both "AssemblyName" and "ConfigurationTypeName" must be specified
/// or both must not be specified.
///
protected override void BeginProcessing()
{
if (isSddlSpecified && showUISpecified)
{
string message = StringUtil.Format(RemotingErrorIdStrings.ShowUIAndSDDLCannotExist,
"SecurityDescriptorSddl",
"ShowSecurityDescriptorUI");
throw new PSInvalidOperationException(message);
}
if (isRunAsCredentialSpecified)
{
WriteWarning(RemotingErrorIdStrings.RunAsSessionConfigurationSecurityWarning);
}
if (isSddlSpecified)
{
// Constructor call should succeed. The sddl is check in the property setter
CommonSecurityDescriptor descriptor = new CommonSecurityDescriptor(false, false, sddl);
SecurityIdentifier networkSidIdentifier = new SecurityIdentifier(WellKnownSidType.NetworkSid, null);
bool networkDenyAllExists = false;
foreach (CommonAce ace in descriptor.DiscretionaryAcl)
{
if (ace.AceQualifier.Equals(AceQualifier.AccessDenied) && ace.SecurityIdentifier.Equals(networkSidIdentifier) && ace.AccessMask == 268435456)
{
networkDenyAllExists = true;
break;
}
}
switch (AccessMode)
{
case PSSessionConfigurationAccessMode.Local:
if (!networkDenyAllExists)
{
descriptor.DiscretionaryAcl.AddAccess(AccessControlType.Deny, networkSidIdentifier, 268435456, InheritanceFlags.None, PropagationFlags.None);
sddl = descriptor.GetSddlForm(AccessControlSections.All);
}
break;
case PSSessionConfigurationAccessMode.Remote:
if (networkDenyAllExists)
{
// Remove the specific ACE
descriptor.DiscretionaryAcl.RemoveAccessSpecific(AccessControlType.Deny, networkSidIdentifier, 268435456, InheritanceFlags.None, PropagationFlags.None);
// If the discretionaryAcl becomes empty, add the BA and RM which is the default WinRM behavior
if (descriptor.DiscretionaryAcl.Count == 0)
{
// BA
SecurityIdentifier baSidIdentifier = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null);
descriptor.DiscretionaryAcl.AddAccess(AccessControlType.Allow, baSidIdentifier, 268435456, InheritanceFlags.None, PropagationFlags.None);
// Only for Win8+
if (Environment.OSVersion.Version >= new Version(6, 2))
{
// Remote Management Users
SecurityIdentifier rmSidIdentifier = new SecurityIdentifier(RemoteManagementUsersSID);
descriptor.DiscretionaryAcl.AddAccess(AccessControlType.Allow, rmSidIdentifier, 268435456, InheritanceFlags.None, PropagationFlags.None);
}
// Interactive Users
SecurityIdentifier iaSidIdentifier = new SecurityIdentifier(InteractiveUsersSID);
descriptor.DiscretionaryAcl.AddAccess(AccessControlType.Allow, iaSidIdentifier, 268435456, InheritanceFlags.None, PropagationFlags.None);
}
sddl = descriptor.GetSddlForm(AccessControlSections.All);
}
break;
case PSSessionConfigurationAccessMode.Disabled:
break;
}
}
if (!isSddlSpecified && !showUISpecified)
{
if (AccessMode.Equals(PSSessionConfigurationAccessMode.Local))
{
// If AccessMode is Local or Disabled and no SDDL specified, use the default local SDDL
sddl = GetLocalSddl();
}
else if (AccessMode.Equals(PSSessionConfigurationAccessMode.Remote))
{
// If AccessMode is Remote and no SDDL specified then use the default remote SDDL
sddl = GetRemoteSddl();
}
}
// check if we have compatible WSMan
RemotingCommandUtil.CheckRemotingCmdletPrerequisites();
PSSessionConfigurationCommandUtilities.ThrowIfNotAdministrator();
WSManConfigurationOption wsmanOption = transportOption as WSManConfigurationOption;
if (wsmanOption != null)
{
if (wsmanOption.ProcessIdleTimeoutSec != null && !isUseSharedProcessSpecified)
{
PSInvalidOperationException ioe = new PSInvalidOperationException(
StringUtil.Format(RemotingErrorIdStrings.InvalidConfigurationXMLAttribute, "ProcessIdleTimeoutSec",
"UseSharedProcess"));
ThrowTerminatingError(ioe.ErrorRecord);
}
}
string pluginPath = PSSessionConfigurationCommandUtilities.GetWinrmPluginDllPath();
pluginPath = Environment.ExpandEnvironmentVariables(pluginPath);
if (!System.IO.File.Exists(pluginPath))
{
PSInvalidOperationException ioe = new PSInvalidOperationException(
StringUtil.Format(RemotingErrorIdStrings.PluginDllMissing, RemotingConstants.PSPluginDLLName));
ThrowTerminatingError(ioe.ErrorRecord);
}
}
///
/// For each record, execute it, and push the results into the
/// success stream.
///
protected override void ProcessRecord()
{
WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.NcsScriptMessageV, newPluginSbFormat));
if (!force)
{
string shouldProcessAction = StringUtil.Format(RemotingErrorIdStrings.CSShouldProcessAction,
this.CommandInfo.Name);
string shouldProcessTarget;
if (isSddlSpecified)
{
shouldProcessTarget = StringUtil.Format(RemotingErrorIdStrings.NcsShouldProcessTargetSDDL, Name, sddl);
}
else
{
shouldProcessTarget = StringUtil.Format(RemotingErrorIdStrings.CSShouldProcessTargetAdminEnable, Name);
}
string action = StringUtil.Format(RemotingErrorIdStrings.CSShouldProcessAction,
this.CommandInfo.Name);
WriteWarning(StringUtil.Format(RemotingErrorIdStrings.WinRMRestartWarning, action));
if (!ShouldProcess(shouldProcessTarget, shouldProcessAction))
{
return;
}
}
// Configuration file copy information.
string srcConfigFilePath;
string destConfigFilePath;
// construct plugin config file.
string pluginContent = ConstructPluginContent(out srcConfigFilePath, out destConfigFilePath);
// Create temporary file with the content.
string file = ConstructTemporaryFile(pluginContent);
// Move the WinRM service to its own service host if the endpoint is given elevated credentials.
if (isRunAsCredentialSpecified || RunAsVirtualAccountSpecified)
{
PSSessionConfigurationCommandUtilities.MoveWinRmToIsolatedServiceHost(RunAsVirtualAccountSpecified);
}
// Use the Group Managed Service Account if provided.
if (!isRunAsCredentialSpecified && !string.IsNullOrEmpty(_gmsaAccount))
{
runAsCredential = PSSessionConfigurationCommandUtilities.CreateGMSAAccountCredentials(_gmsaAccount);
}
try
{
// restart-service winrm to make the changes effective.
string restartServiceAction = RemotingErrorIdStrings.RestartWSManServiceAction;
string restartServiceTarget = StringUtil.Format(RemotingErrorIdStrings.RestartWSManServiceTarget, "WinRM");
string restartWSManRequiredForUI = StringUtil.Format(RemotingErrorIdStrings.RestartWSManRequiredShowUI,
string.Create(CultureInfo.InvariantCulture, $"Set-PSSessionConfiguration {shellName} -ShowSecurityDescriptorUI"));
// gather -WhatIf, -Confirm parameter data and pass it to the script block
bool whatIf = false;
// confirm is always true to start with
bool confirm = true;
PSSessionConfigurationCommandUtilities.CollectShouldProcessParameters(this, out whatIf, out confirm);
// gather -ErrorAction parameter data and pass it to the script block. if -ErrorAction is not set, pass $null in
object errorAction = null;
if (Context.CurrentCommandProcessor.CommandRuntime.IsErrorActionSet)
{
errorAction = Context.CurrentCommandProcessor.CommandRuntime.ErrorAction;
}
ArrayList errorList = (ArrayList)Context.DollarErrorVariable;
int errorCountBefore = errorList.Count;
if (force &&
this.Context != null &&
this.Context.EngineHostInterface != null &&
this.Context.EngineHostInterface.ExternalHost != null &&
this.Context.EngineHostInterface.ExternalHost is System.Management.Automation.Remoting.ServerRemoteHost)
{
WriteWarning(RemotingErrorIdStrings.WinRMForceRestartWarning);
}
s_newPluginSb.InvokeUsingCmdlet(
contextCmdlet: this,
useLocalScope: true,
errorHandlingBehavior: ScriptBlock.ErrorHandlingBehavior.WriteToCurrentErrorPipe,
dollarUnder: AutomationNull.Value,
input: Array.Empty