// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Management.Automation.Internal;
using System.Management.Automation.Runspaces;
using System.Management.Automation.Tracing;
using System.Reflection;
using System.Threading;
using System.Xml;
using Microsoft.PowerShell.Commands;
using Microsoft.Win32;
using Dbg = System.Management.Automation.Diagnostics;
namespace System.Management.Automation.Remoting
{
#region WSMan endpoint configuration
///
/// This struct is used to represent contents from configuration xml. The
/// XML is passed to plugins by WSMan API.
/// This helper does not validate XML content as it is already validated
/// by WSMan.
///
internal class ConfigurationDataFromXML
{
#region Config XML Constants
internal const string INITPARAMETERSTOKEN = "InitializationParameters";
internal const string PARAMTOKEN = "Param";
internal const string NAMETOKEN = "Name";
internal const string VALUETOKEN = "Value";
internal const string APPBASETOKEN = "applicationbase";
internal const string ASSEMBLYTOKEN = "assemblyname";
internal const string SHELLCONFIGTYPETOKEN = "pssessionconfigurationtypename";
internal const string STARTUPSCRIPTTOKEN = "startupscript";
internal const string MAXRCVDOBJSIZETOKEN = "psmaximumreceivedobjectsizemb";
internal const string MAXRCVDOBJSIZETOKEN_CamelCase = "PSMaximumReceivedObjectSizeMB";
internal const string MAXRCVDCMDSIZETOKEN = "psmaximumreceiveddatasizepercommandmb";
internal const string MAXRCVDCMDSIZETOKEN_CamelCase = "PSMaximumReceivedDataSizePerCommandMB";
internal const string THREADOPTIONSTOKEN = "pssessionthreadoptions";
internal const string THREADAPTSTATETOKEN = "pssessionthreadapartmentstate";
internal const string SESSIONCONFIGTOKEN = "sessionconfigurationdata";
internal const string PSVERSIONTOKEN = "PSVersion";
internal const string MAXPSVERSIONTOKEN = "MaxPSVersion";
internal const string MODULESTOIMPORT = "ModulesToImport";
internal const string HOSTMODE = "hostmode";
internal const string CONFIGFILEPATH = "configfilepath";
internal const string CONFIGFILEPATH_CamelCase = "ConfigFilePath";
#endregion
#region Fields
internal string StartupScript;
// this field is used only by an Out-Of-Process (IPC) server process
internal string InitializationScriptForOutOfProcessRunspace;
internal string ApplicationBase;
internal string AssemblyName;
internal string EndPointConfigurationTypeName;
internal Type EndPointConfigurationType;
internal int? MaxReceivedObjectSizeMB;
internal int? MaxReceivedCommandSizeMB;
// Used to set properties on the RunspacePool created for this shell.
internal PSThreadOptions? ShellThreadOptions;
internal ApartmentState? ShellThreadApartmentState;
internal PSSessionConfigurationData SessionConfigurationData;
internal string ConfigFilePath;
#endregion
#region Methods
///
/// Using optionName and optionValue updates the current object.
///
///
///
///
/// 1. "optionName" is not valid in "InitializationParameters" section.
/// 2. "startupscript" must specify a PowerShell script file that ends with extension ".ps1".
///
private void Update(string optionName, string optionValue)
{
switch (optionName.ToLowerInvariant())
{
case APPBASETOKEN:
AssertValueNotAssigned(APPBASETOKEN, ApplicationBase);
// this is a folder pointing to application base of the plugin shell
// allow the folder path to use environment variables.
ApplicationBase = Environment.ExpandEnvironmentVariables(optionValue);
break;
case ASSEMBLYTOKEN:
AssertValueNotAssigned(ASSEMBLYTOKEN, AssemblyName);
AssemblyName = optionValue;
break;
case SHELLCONFIGTYPETOKEN:
AssertValueNotAssigned(SHELLCONFIGTYPETOKEN, EndPointConfigurationTypeName);
EndPointConfigurationTypeName = optionValue;
break;
case STARTUPSCRIPTTOKEN:
AssertValueNotAssigned(STARTUPSCRIPTTOKEN, StartupScript);
if (!optionValue.EndsWith(".ps1", StringComparison.OrdinalIgnoreCase))
{
throw PSTraceSource.NewArgumentException(STARTUPSCRIPTTOKEN,
RemotingErrorIdStrings.StartupScriptNotCorrect,
STARTUPSCRIPTTOKEN);
}
// allow the script file to exist in any path..and support
// environment variable expansion.
StartupScript = Environment.ExpandEnvironmentVariables(optionValue);
break;
case MAXRCVDOBJSIZETOKEN:
AssertValueNotAssigned(MAXRCVDOBJSIZETOKEN, MaxReceivedObjectSizeMB);
MaxReceivedObjectSizeMB = GetIntValueInBytes(optionValue);
break;
case MAXRCVDCMDSIZETOKEN:
AssertValueNotAssigned(MAXRCVDCMDSIZETOKEN, MaxReceivedCommandSizeMB);
MaxReceivedCommandSizeMB = GetIntValueInBytes(optionValue);
break;
case THREADOPTIONSTOKEN:
AssertValueNotAssigned(THREADOPTIONSTOKEN, ShellThreadOptions);
ShellThreadOptions = (PSThreadOptions)LanguagePrimitives.ConvertTo(
optionValue, typeof(PSThreadOptions), CultureInfo.InvariantCulture);
break;
case THREADAPTSTATETOKEN:
AssertValueNotAssigned(THREADAPTSTATETOKEN, ShellThreadApartmentState);
ShellThreadApartmentState = (ApartmentState)LanguagePrimitives.ConvertTo(
optionValue, typeof(ApartmentState), CultureInfo.InvariantCulture);
break;
case SESSIONCONFIGTOKEN:
{
AssertValueNotAssigned(SESSIONCONFIGTOKEN, SessionConfigurationData);
SessionConfigurationData = PSSessionConfigurationData.Create(optionValue);
}
break;
case CONFIGFILEPATH:
{
AssertValueNotAssigned(CONFIGFILEPATH, ConfigFilePath);
ConfigFilePath = optionValue;
}
break;
default:
// we dont need to evaluate PSVersion and other custom authz
// related tokens
break;
}
}
///
/// Checks if the originalValue is empty. If not throws an exception.
///
///
///
///
/// 1. "optionName" is already defined
///
private static void AssertValueNotAssigned(string optionName, object originalValue)
{
if (originalValue != null)
{
throw PSTraceSource.NewArgumentException(optionName,
RemotingErrorIdStrings.DuplicateInitializationParameterFound, optionName, INITPARAMETERSTOKEN);
}
}
///
/// Converts the value specified by to int.
/// Multiplies the value by 1MB (1024*1024) to get the number in bytes.
///
///
///
/// If value is specified, specified value as int . otherwise null.
///
private static int? GetIntValueInBytes(string optionValueInMB)
{
int? result = null;
try
{
double variableValue = (double)LanguagePrimitives.ConvertTo(optionValueInMB,
typeof(double), System.Globalization.CultureInfo.InvariantCulture);
result = unchecked((int)(variableValue * 1024 * 1024)); // Multiply by 1MB
}
catch (InvalidCastException)
{
}
if (result < 0)
{
result = null;
}
return result;
}
///
/// Creates the struct from initialization parameters xml.
///
///
/// Initialization Parameters xml passed by WSMan API. This data is read from the config
/// xml and is in the following format:
///
///
///
/// 1. "optionName" is already defined
///
/*
...
*/
/* The following extensions have been added in V3 providing the user
* the ability to pass data to the session configuration for initialization
*
*
* The session configuration data blob can be defined as under
...
*/
internal static ConfigurationDataFromXML Create(string initializationParameters)
{
ConfigurationDataFromXML result = new ConfigurationDataFromXML();
if (string.IsNullOrEmpty(initializationParameters))
{
return result;
}
XmlReaderSettings readerSettings = new XmlReaderSettings();
readerSettings.CheckCharacters = false;
readerSettings.IgnoreComments = true;
readerSettings.IgnoreProcessingInstructions = true;
readerSettings.MaxCharactersInDocument = 10000;
readerSettings.ConformanceLevel = ConformanceLevel.Fragment;
using (XmlReader reader = XmlReader.Create(new StringReader(initializationParameters), readerSettings))
{
// read the header
if (reader.ReadToFollowing(INITPARAMETERSTOKEN))
{
bool isParamFound = reader.ReadToDescendant(PARAMTOKEN);
while (isParamFound)
{
if (!reader.MoveToAttribute(NAMETOKEN))
{
throw PSTraceSource.NewArgumentException(initializationParameters,
RemotingErrorIdStrings.NoAttributesFoundForParamElement,
NAMETOKEN, VALUETOKEN, PARAMTOKEN);
}
string optionName = reader.Value;
if (!reader.MoveToAttribute(VALUETOKEN))
{
throw PSTraceSource.NewArgumentException(initializationParameters,
RemotingErrorIdStrings.NoAttributesFoundForParamElement,
NAMETOKEN, VALUETOKEN, PARAMTOKEN);
}
string optionValue = reader.Value;
result.Update(optionName, optionValue);
// move to next Param token.
isParamFound = reader.ReadToFollowing(PARAMTOKEN);
}
}
}
// assign defaults after parsing the xml content.
result.MaxReceivedObjectSizeMB ??= BaseTransportManager.MaximumReceivedObjectSize;
result.MaxReceivedCommandSizeMB ??= BaseTransportManager.MaximumReceivedDataSize;
return result;
}
///
///
///
///
/// 1. Unable to load type "{0}" specified in "InitializationParameters" section.
///
internal PSSessionConfiguration CreateEndPointConfigurationInstance()
{
try
{
return (PSSessionConfiguration)Activator.CreateInstance(EndPointConfigurationType);
}
catch (TypeLoadException)
{
}
catch (ArgumentException)
{
}
catch (MissingMethodException)
{
}
catch (InvalidCastException)
{
}
catch (TargetInvocationException)
{
}
// if we are here, that means we are unable to load the type specified
// in the config xml.. notify the same.
throw PSTraceSource.NewArgumentException("typeToLoad", RemotingErrorIdStrings.UnableToLoadType,
EndPointConfigurationTypeName, ConfigurationDataFromXML.INITPARAMETERSTOKEN);
}
#endregion
}
///
/// InitialSessionStateProvider is used by 3rd parties to provide shell configuration
/// on the remote server.
///
public abstract class PSSessionConfiguration : IDisposable
{
#region tracer
///
/// Tracer for Server Remote session.
///
[TraceSource("ServerRemoteSession", "ServerRemoteSession")]
private static readonly PSTraceSource s_tracer = PSTraceSource.GetTracer("ServerRemoteSession", "ServerRemoteSession");
#endregion tracer
#region public interfaces
///
/// Derived classes must override this to supply an InitialSessionState
/// to be used to construct a Runspace for the user.
///
///
/// User Identity for which this information is requested
///
///
public abstract InitialSessionState GetInitialSessionState(PSSenderInfo senderInfo);
///
///
///
///
///
///
public virtual InitialSessionState GetInitialSessionState(PSSessionConfigurationData sessionConfigurationData,
PSSenderInfo senderInfo, string configProviderId)
{
throw new NotImplementedException();
}
///
/// Maximum size (in bytes) of a deserialized object received from a remote machine.
/// If null, then the size is unlimited. Default is 10MB.
///
///
/// User Identity for which this information is requested
///
///
public virtual int? GetMaximumReceivedObjectSize(PSSenderInfo senderInfo)
{
return BaseTransportManager.MaximumReceivedObjectSize;
}
///
/// Total data (in bytes) that can be received from a remote machine
/// targeted towards a command. If null, then the size is unlimited.
/// Default is 50MB.
///
///
/// User Identity for which this information is requested
///
///
public virtual int? GetMaximumReceivedDataSizePerCommand(PSSenderInfo senderInfo)
{
return BaseTransportManager.MaximumReceivedDataSize;
}
///
/// Derived classes can override this method to provide application private data
/// that is going to be sent to the client and exposed via
/// ,
/// and
///
///
///
/// User Identity for which this information is requested
///
/// Application private data or
public virtual PSPrimitiveDictionary GetApplicationPrivateData(PSSenderInfo senderInfo)
{
return null;
}
#endregion
#region IDisposable Overrides
///
/// Dispose this configuration object. This will be called when a Runspace/RunspacePool
/// created using InitialSessionState from this object is Closed.
///
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
///
///
///
protected virtual void Dispose(bool isDisposing)
{
}
#endregion
#region GetInitialSessionState from 3rd party shell ids
///
///
///
///
/// Initialization Parameters xml passed by WSMan API. This data is read from the config
/// xml and is in the following format:
///
///
///
/// 1. Non existent InitialSessionState provider for the shellID
///
/*
...
*/
internal static ConfigurationDataFromXML LoadEndPointConfiguration(
string shellId,
string initializationParameters)
{
ConfigurationDataFromXML configData = null;
if (!s_ssnStateProviders.ContainsKey(initializationParameters))
{
LoadRSConfigProvider(shellId, initializationParameters);
}
lock (s_syncObject)
{
if (!s_ssnStateProviders.TryGetValue(initializationParameters, out configData))
{
throw PSTraceSource.NewInvalidOperationException(RemotingErrorIdStrings.NonExistentInitialSessionStateProvider, shellId);
}
}
return configData;
}
private static void LoadRSConfigProvider(string shellId, string initializationParameters)
{
ConfigurationDataFromXML configData = ConfigurationDataFromXML.Create(initializationParameters);
Type endPointConfigType = LoadAndAnalyzeAssembly(shellId,
configData.ApplicationBase,
configData.AssemblyName,
configData.EndPointConfigurationTypeName);
Dbg.Assert(endPointConfigType != null, "EndPointConfiguration type cannot be null");
configData.EndPointConfigurationType = endPointConfigType;
lock (s_syncObject)
{
if (!s_ssnStateProviders.ContainsKey(initializationParameters))
{
s_ssnStateProviders.Add(initializationParameters, configData);
}
}
}
///
///
///
/// shellId for which the assembly is getting loaded
///
///
///
///
/// type which is supplying the configuration.
///
///
///
///
/// Type instance representing the EndPointConfiguration to load.
/// This Type can be instantiated when needed.
///
private static Type LoadAndAnalyzeAssembly(string shellId, string applicationBase,
string assemblyName, string typeToLoad)
{
if ((string.IsNullOrEmpty(assemblyName) && !string.IsNullOrEmpty(typeToLoad)) ||
(!string.IsNullOrEmpty(assemblyName) && string.IsNullOrEmpty(typeToLoad)))
{
throw PSTraceSource.NewInvalidOperationException(RemotingErrorIdStrings.TypeNeedsAssembly,
ConfigurationDataFromXML.ASSEMBLYTOKEN,
ConfigurationDataFromXML.SHELLCONFIGTYPETOKEN,
ConfigurationDataFromXML.INITPARAMETERSTOKEN);
}
Assembly assembly = null;
if (!string.IsNullOrEmpty(assemblyName))
{
PSEtwLog.LogAnalyticVerbose(PSEventId.LoadingPSCustomShellAssembly,
PSOpcode.Connect, PSTask.None, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic,
assemblyName, shellId);
assembly = LoadSsnStateProviderAssembly(applicationBase, assemblyName);
if (assembly == null)
{
throw PSTraceSource.NewArgumentException(nameof(assemblyName), RemotingErrorIdStrings.UnableToLoadAssembly,
assemblyName, ConfigurationDataFromXML.INITPARAMETERSTOKEN);
}
}
// configuration xml specified an assembly and typetoload.
if (assembly != null)
{
try
{
PSEtwLog.LogAnalyticVerbose(PSEventId.LoadingPSCustomShellType,
PSOpcode.Connect, PSTask.None, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic,
typeToLoad, shellId);
Type type = assembly.GetType(typeToLoad, true, true);
if (type == null)
{
throw PSTraceSource.NewArgumentException(nameof(typeToLoad), RemotingErrorIdStrings.UnableToLoadType,
typeToLoad, ConfigurationDataFromXML.INITPARAMETERSTOKEN);
}
return type;
}
catch (ReflectionTypeLoadException)
{
}
catch (TypeLoadException)
{
}
catch (ArgumentException)
{
}
catch (MissingMethodException)
{
}
catch (InvalidCastException)
{
}
catch (TargetInvocationException)
{
}
// if we are here, that means we are unable to load the type specified
// in the config xml.. notify the same.
throw PSTraceSource.NewArgumentException(nameof(typeToLoad), RemotingErrorIdStrings.UnableToLoadType,
typeToLoad, ConfigurationDataFromXML.INITPARAMETERSTOKEN);
}
// load the default PowerShell since plugin config
// did not specify a typename to load.
return typeof(DefaultRemotePowerShellConfiguration);
}
///
/// Sets the application's current working directory to and
/// loads the assembly . Once the assembly is loaded, the application's
/// current working directory is set back to the original value.
///
///
///
///
// TODO: Send the exception message back to the client.
[SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods", MessageId = "System.Reflection.Assembly.LoadFrom")]
private static Assembly LoadSsnStateProviderAssembly(string applicationBase, string assemblyName)
{
Dbg.Assert(!string.IsNullOrEmpty(assemblyName), "AssemblyName cannot be null.");
string originalDirectory = string.Empty;
if (!string.IsNullOrEmpty(applicationBase))
{
// changing current working directory allows CLR loader to load dependent assemblies
try
{
originalDirectory = Directory.GetCurrentDirectory();
Directory.SetCurrentDirectory(applicationBase);
}
catch (ArgumentException e)
{
s_tracer.TraceWarning("Not able to change current working directory to {0}: {1}",
applicationBase, e.Message);
}
catch (PathTooLongException e)
{
s_tracer.TraceWarning("Not able to change current working directory to {0}: {1}",
applicationBase, e.Message);
}
catch (FileNotFoundException e)
{
s_tracer.TraceWarning("Not able to change current working directory to {0}: {1}",
applicationBase, e.Message);
}
catch (IOException e)
{
s_tracer.TraceWarning("Not able to change current working directory to {0}: {1}",
applicationBase, e.Message);
}
catch (System.Security.SecurityException e)
{
s_tracer.TraceWarning("Not able to change current working directory to {0}: {1}",
applicationBase, e.Message);
}
catch (UnauthorizedAccessException e)
{
s_tracer.TraceWarning("Not able to change current working directory to {0}: {1}",
applicationBase, e.Message);
}
}
// Even if there is error changing current working directory..try to load the assembly
// This is to allow assembly loading from GAC
Assembly result = null;
try
{
try
{
result = Assembly.Load(new AssemblyName(assemblyName));
}
catch (FileLoadException e)
{
s_tracer.TraceWarning("Not able to load assembly {0}: {1}", assemblyName, e.Message);
}
catch (BadImageFormatException e)
{
s_tracer.TraceWarning("Not able to load assembly {0}: {1}", assemblyName, e.Message);
}
catch (FileNotFoundException e)
{
s_tracer.TraceWarning("Not able to load assembly {0}: {1}", assemblyName, e.Message);
}
if (result != null)
{
return result;
}
s_tracer.WriteLine("Loading assembly from path {0}", applicationBase);
try
{
string assemblyPath;
if (!Path.IsPathRooted(assemblyName))
{
if (!string.IsNullOrEmpty(applicationBase) && Directory.Exists(applicationBase))
{
assemblyPath = Path.Combine(applicationBase, assemblyName);
}
else
{
assemblyPath = Path.Combine(Directory.GetCurrentDirectory(), assemblyName);
}
}
else
{
// Rooted path of dll is provided.
assemblyPath = assemblyName;
}
result = Assembly.LoadFrom(assemblyPath);
}
catch (FileLoadException e)
{
s_tracer.TraceWarning("Not able to load assembly {0}: {1}", assemblyName, e.Message);
}
catch (BadImageFormatException e)
{
s_tracer.TraceWarning("Not able to load assembly {0}: {1}", assemblyName, e.Message);
}
catch (FileNotFoundException e)
{
s_tracer.TraceWarning("Not able to load assembly {0}: {1}", assemblyName, e.Message);
}
}
finally
{
if (!string.IsNullOrEmpty(applicationBase))
{
// set the application's directory back to the original directory
Directory.SetCurrentDirectory(originalDirectory);
}
}
return result;
}
// TODO: I think this should be moved to Utils..this way all versioning related
// logic will be in one place.
private static RegistryKey GetConfigurationProvidersRegistryKey()
{
try
{
RegistryKey monadRootKey = PSSnapInReader.GetMonadRootKey();
RegistryKey versionRoot = PSSnapInReader.GetVersionRootKey(monadRootKey, Utils.GetCurrentMajorVersion());
RegistryKey configProviderKey = versionRoot.OpenSubKey(configProvidersKeyName);
return configProviderKey;
}
catch (ArgumentException)
{
}
catch (System.Security.SecurityException)
{
}
return null;
}
///
/// Read value from the property for registry
/// as string.
///
///
/// Registry key from which the value is read.
/// Caller should make sure this is not null.
///
///
/// Name of the property.
/// Caller should make sure this is not null.
///
///
/// True, if the property should exist.
/// False, otherwise.
///
///
/// Value of the property.
///
///
///
///
///
private static string
ReadStringValue(RegistryKey registryKey, string name, bool mandatory)
{
Dbg.Assert(!string.IsNullOrEmpty(name), "caller should validate the name parameter");
Dbg.Assert(registryKey != null, "Caller should validate the registryKey parameter");
object value = registryKey.GetValue(name);
if (value == null && mandatory)
{
s_tracer.TraceError("Mandatory property {0} not specified for registry key {1}",
name, registryKey.Name);
throw PSTraceSource.NewArgumentException(nameof(name), RemotingErrorIdStrings.MandatoryValueNotPresent, name, registryKey.Name);
}
string s = value as string;
if (string.IsNullOrEmpty(s) && mandatory)
{
s_tracer.TraceError("Value is null or empty for mandatory property {0} in {1}",
name, registryKey.Name);
throw PSTraceSource.NewArgumentException(nameof(name), RemotingErrorIdStrings.MandatoryValueNotInCorrectFormat, name, registryKey.Name);
}
return s;
}
private const string configProvidersKeyName = "PSConfigurationProviders";
private const string configProviderApplicationBaseKeyName = "ApplicationBase";
private const string configProviderAssemblyNameKeyName = "AssemblyName";
private static readonly Dictionary s_ssnStateProviders =
new Dictionary(StringComparer.OrdinalIgnoreCase);
private static readonly object s_syncObject = new object();
#endregion
}
///
/// Provides Default InitialSessionState.
///
internal sealed class DefaultRemotePowerShellConfiguration : PSSessionConfiguration
{
#region Method overrides
///
///
///
///
public override InitialSessionState GetInitialSessionState(PSSenderInfo senderInfo)
{
InitialSessionState result = InitialSessionState.CreateDefault2();
// TODO: Remove this after RDS moved to $using
if (senderInfo.ConnectionString != null && senderInfo.ConnectionString.Contains("MSP=7a83d074-bb86-4e52-aa3e-6cc73cc066c8"))
{
PSSessionConfigurationData.IsServerManager = true;
}
return result;
}
public override InitialSessionState GetInitialSessionState(PSSessionConfigurationData sessionConfigurationData, PSSenderInfo senderInfo, string configProviderId)
{
ArgumentNullException.ThrowIfNull(sessionConfigurationData);
ArgumentNullException.ThrowIfNull(senderInfo);
ArgumentNullException.ThrowIfNull(configProviderId);
InitialSessionState sessionState = InitialSessionState.CreateDefault2();
// now get all the modules in the specified path and import the same
if (sessionConfigurationData != null && sessionConfigurationData.ModulesToImportInternal != null)
{
foreach (var module in sessionConfigurationData.ModulesToImportInternal)
{
var moduleName = module as string;
if (moduleName != null)
{
moduleName = Environment.ExpandEnvironmentVariables(moduleName);
sessionState.ImportPSModule(new[] { moduleName });
}
else
{
var moduleSpec = module as ModuleSpecification;
if (moduleSpec != null)
{
var modulesToImport = new Collection { moduleSpec };
sessionState.ImportPSModule(modulesToImport);
}
}
}
}
// TODO: Remove this after RDS moved to $using
if (senderInfo.ConnectionString != null && senderInfo.ConnectionString.Contains("MSP=7a83d074-bb86-4e52-aa3e-6cc73cc066c8"))
{
PSSessionConfigurationData.IsServerManager = true;
}
return sessionState;
}
#endregion
}
#endregion
#region Declarative InitialSession Configuration
#region Supporting types
///
/// Specifies type of initial session state to use. Valid values are Empty and Default.
///
public enum SessionType
{
///
/// Empty session state.
///
Empty,
///
/// Restricted remote server.
///
RestrictedRemoteServer,
///
/// Default session state.
///
Default
}
///
/// Configuration type entry.
///
internal class ConfigTypeEntry
{
internal delegate bool TypeValidationCallback(string key, object obj, PSCmdlet cmdlet, string path);
internal string Key;
internal TypeValidationCallback ValidationCallback;
///
///
///
///
internal ConfigTypeEntry(string key, TypeValidationCallback callback)
{
this.Key = key;
this.ValidationCallback = callback;
}
}
#endregion
#region ConfigFileConstants
///
/// Configuration file constants.
///
internal static class ConfigFileConstants
{
internal static readonly string AliasDefinitions = "AliasDefinitions";
internal static readonly string AliasDescriptionToken = "Description";
internal static readonly string AliasNameToken = "Name";
internal static readonly string AliasOptionsToken = "Options";
internal static readonly string AliasValueToken = "Value";
internal static readonly string AssembliesToLoad = "AssembliesToLoad";
internal static readonly string Author = "Author";
internal static readonly string CompanyName = "CompanyName";
internal static readonly string Copyright = "Copyright";
internal static readonly string Description = "Description";
internal static readonly string EnforceInputParameterValidation = "EnforceInputParameterValidation";
internal static readonly string EnvironmentVariables = "EnvironmentVariables";
internal static readonly string ExecutionPolicy = "ExecutionPolicy";
internal static readonly string FormatsToProcess = "FormatsToProcess";
internal static readonly string FunctionDefinitions = "FunctionDefinitions";
internal static readonly string FunctionNameToken = "Name";
internal static readonly string FunctionOptionsToken = "Options";
internal static readonly string FunctionValueToken = "ScriptBlock";
internal static readonly string GMSAAccount = "GroupManagedServiceAccount";
internal static readonly string Guid = "GUID";
internal static readonly string LanguageMode = "LanguageMode";
internal static readonly string ModulesToImport = "ModulesToImport";
internal static readonly string MountUserDrive = "MountUserDrive";
internal static readonly string PowerShellVersion = "PowerShellVersion";
internal static readonly string RequiredGroups = "RequiredGroups";
internal static readonly string RoleDefinitions = "RoleDefinitions";
internal static readonly string SchemaVersion = "SchemaVersion";
internal static readonly string ScriptsToProcess = "ScriptsToProcess";
internal static readonly string SessionType = "SessionType";
internal static readonly string RoleCapabilities = "RoleCapabilities";
internal static readonly string RoleCapabilityFiles = "RoleCapabilityFiles";
internal static readonly string RunAsVirtualAccount = "RunAsVirtualAccount";
internal static readonly string RunAsVirtualAccountGroups = "RunAsVirtualAccountGroups";
internal static readonly string TranscriptDirectory = "TranscriptDirectory";
internal static readonly string TypesToProcess = "TypesToProcess";
internal static readonly string UserDriveMaxSize = "UserDriveMaximumSize";
internal static readonly string VariableDefinitions = "VariableDefinitions";
internal static readonly string VariableNameToken = "Name";
internal static readonly string VariableValueToken = "Value";
internal static readonly string VisibleAliases = "VisibleAliases";
internal static readonly string VisibleCmdlets = "VisibleCmdlets";
internal static readonly string VisibleFunctions = "VisibleFunctions";
internal static readonly string VisibleProviders = "VisibleProviders";
internal static readonly string VisibleExternalCommands = "VisibleExternalCommands";
internal static readonly ConfigTypeEntry[] ConfigFileKeys = new ConfigTypeEntry[] {
new ConfigTypeEntry(AliasDefinitions, new ConfigTypeEntry.TypeValidationCallback(AliasDefinitionsTypeValidationCallback)),
new ConfigTypeEntry(AssembliesToLoad, new ConfigTypeEntry.TypeValidationCallback(StringArrayTypeValidationCallback)),
new ConfigTypeEntry(Author, new ConfigTypeEntry.TypeValidationCallback(StringTypeValidationCallback)),
new ConfigTypeEntry(CompanyName, new ConfigTypeEntry.TypeValidationCallback(StringTypeValidationCallback)),
new ConfigTypeEntry(Copyright, new ConfigTypeEntry.TypeValidationCallback(StringTypeValidationCallback)),
new ConfigTypeEntry(Description, new ConfigTypeEntry.TypeValidationCallback(StringTypeValidationCallback)),
new ConfigTypeEntry(EnforceInputParameterValidation, new ConfigTypeEntry.TypeValidationCallback(BooleanTypeValidationCallback)),
new ConfigTypeEntry(EnvironmentVariables, new ConfigTypeEntry.TypeValidationCallback(HashtableTypeValidationCallback)),
new ConfigTypeEntry(ExecutionPolicy, new ConfigTypeEntry.TypeValidationCallback(ExecutionPolicyValidationCallback)),
new ConfigTypeEntry(FormatsToProcess, new ConfigTypeEntry.TypeValidationCallback(StringArrayTypeValidationCallback)),
new ConfigTypeEntry(FunctionDefinitions, new ConfigTypeEntry.TypeValidationCallback(FunctionDefinitionsTypeValidationCallback)),
new ConfigTypeEntry(GMSAAccount, new ConfigTypeEntry.TypeValidationCallback(StringTypeValidationCallback)),
new ConfigTypeEntry(Guid, new ConfigTypeEntry.TypeValidationCallback(StringTypeValidationCallback)),
new ConfigTypeEntry(LanguageMode, new ConfigTypeEntry.TypeValidationCallback(LanguageModeValidationCallback)),
new ConfigTypeEntry(ModulesToImport, new ConfigTypeEntry.TypeValidationCallback(StringOrHashtableArrayTypeValidationCallback)),
new ConfigTypeEntry(MountUserDrive, new ConfigTypeEntry.TypeValidationCallback(BooleanTypeValidationCallback)),
new ConfigTypeEntry(PowerShellVersion, new ConfigTypeEntry.TypeValidationCallback(StringTypeValidationCallback)),
new ConfigTypeEntry(RequiredGroups, new ConfigTypeEntry.TypeValidationCallback(HashtableTypeValidationCallback)),
new ConfigTypeEntry(RoleCapabilities, new ConfigTypeEntry.TypeValidationCallback(StringArrayTypeValidationCallback)),
new ConfigTypeEntry(RoleCapabilityFiles, new ConfigTypeEntry.TypeValidationCallback(StringArrayTypeValidationCallback)),
new ConfigTypeEntry(RoleDefinitions, new ConfigTypeEntry.TypeValidationCallback(HashtableTypeValidationCallback)),
new ConfigTypeEntry(RunAsVirtualAccount, new ConfigTypeEntry.TypeValidationCallback(BooleanTypeValidationCallback)),
new ConfigTypeEntry(RunAsVirtualAccountGroups, new ConfigTypeEntry.TypeValidationCallback(StringArrayTypeValidationCallback)),
new ConfigTypeEntry(SchemaVersion, new ConfigTypeEntry.TypeValidationCallback(StringTypeValidationCallback)),
new ConfigTypeEntry(ScriptsToProcess, new ConfigTypeEntry.TypeValidationCallback(StringArrayTypeValidationCallback)),
new ConfigTypeEntry(SessionType, new ConfigTypeEntry.TypeValidationCallback(ISSValidationCallback)),
new ConfigTypeEntry(TranscriptDirectory, new ConfigTypeEntry.TypeValidationCallback(StringTypeValidationCallback)),
new ConfigTypeEntry(TypesToProcess, new ConfigTypeEntry.TypeValidationCallback(StringArrayTypeValidationCallback)),
new ConfigTypeEntry(UserDriveMaxSize, new ConfigTypeEntry.TypeValidationCallback(IntegerTypeValidationCallback)),
new ConfigTypeEntry(VariableDefinitions, new ConfigTypeEntry.TypeValidationCallback(VariableDefinitionsTypeValidationCallback)),
new ConfigTypeEntry(VisibleAliases, new ConfigTypeEntry.TypeValidationCallback(StringArrayTypeValidationCallback)),
new ConfigTypeEntry(VisibleCmdlets, new ConfigTypeEntry.TypeValidationCallback(StringArrayTypeValidationCallback)),
new ConfigTypeEntry(VisibleFunctions, new ConfigTypeEntry.TypeValidationCallback(StringArrayTypeValidationCallback)),
new ConfigTypeEntry(VisibleProviders, new ConfigTypeEntry.TypeValidationCallback(StringArrayTypeValidationCallback)),
new ConfigTypeEntry(VisibleExternalCommands, new ConfigTypeEntry.TypeValidationCallback(StringArrayTypeValidationCallback)),
};
///
/// Checks if the given key is a valid key.
///
///
///
///
///
internal static bool IsValidKey(DictionaryEntry de, PSCmdlet cmdlet, string path)
{
bool validKey = false;
foreach (ConfigTypeEntry configEntry in ConfigFileKeys)
{
if (string.Equals(configEntry.Key, de.Key.ToString(), StringComparison.OrdinalIgnoreCase))
{
validKey = true;
if (configEntry.ValidationCallback(de.Key.ToString(), de.Value, cmdlet, path))
{
return true;
}
}
}
if (!validKey)
{
cmdlet.WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.DISCInvalidKey, de.Key.ToString(), path));
}
return false;
}
///
///
///
///
///
///
///
private static bool ISSValidationCallback(string key, object obj, PSCmdlet cmdlet, string path)
{
string value = obj as string;
if (!string.IsNullOrEmpty(value))
{
try
{
Enum.Parse(typeof(SessionType), value, true);
return true;
}
catch (ArgumentException)
{
// Do nothing here
}
}
cmdlet.WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustBeValidEnum, key, typeof(SessionType).FullName,
LanguagePrimitives.EnumSingleTypeConverter.EnumValues(typeof(SessionType)), path));
return false;
}
///
///
///
///
///
///
///
private static bool LanguageModeValidationCallback(string key, object obj, PSCmdlet cmdlet, string path)
{
string value = obj as string;
if (!string.IsNullOrEmpty(value))
{
try
{
Enum.Parse(typeof(PSLanguageMode), value, true);
return true;
}
catch (ArgumentException)
{
// Do nothing here
}
}
cmdlet.WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustBeValidEnum, key, typeof(PSLanguageMode).FullName,
LanguagePrimitives.EnumSingleTypeConverter.EnumValues(typeof(PSLanguageMode)), path));
return false;
}
///
///
///
///
///
///
///
private static bool ExecutionPolicyValidationCallback(string key, object obj, PSCmdlet cmdlet, string path)
{
string value = obj as string;
if (!string.IsNullOrEmpty(value))
{
try
{
Enum.Parse(DISCUtils.ExecutionPolicyType, value, true);
return true;
}
catch (ArgumentException)
{
// Do nothing here
}
}
cmdlet.WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustBeValidEnum, key, DISCUtils.ExecutionPolicyType.FullName,
LanguagePrimitives.EnumSingleTypeConverter.EnumValues(DISCUtils.ExecutionPolicyType), path));
return false;
}
///
///
///
///
///
///
///
private static bool HashtableTypeValidationCallback(string key, object obj, PSCmdlet cmdlet, string path)
{
Hashtable hash = obj as Hashtable;
if (hash == null)
{
cmdlet.WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustBeHashtable, key, path));
return false;
}
return true;
}
///
///
///
///
///
///
///
private static bool AliasDefinitionsTypeValidationCallback(string key, object obj, PSCmdlet cmdlet, string path)
{
Hashtable[] hashtables = DISCPowerShellConfiguration.TryGetHashtableArray(obj);
if (hashtables == null)
{
cmdlet.WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustBeHashtableArray, key, path));
return false;
}
foreach (Hashtable hashtable in hashtables)
{
if (!hashtable.ContainsKey(AliasNameToken))
{
cmdlet.WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustContainKey, key, AliasNameToken, path));
return false;
}
if (!hashtable.ContainsKey(AliasValueToken))
{
cmdlet.WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustContainKey, key, AliasValueToken, path));
return false;
}
foreach (string aliasKey in hashtable.Keys)
{
if (!string.Equals(aliasKey, AliasNameToken, StringComparison.OrdinalIgnoreCase) &&
!string.Equals(aliasKey, AliasValueToken, StringComparison.OrdinalIgnoreCase) &&
!string.Equals(aliasKey, AliasDescriptionToken, StringComparison.OrdinalIgnoreCase) &&
!string.Equals(aliasKey, AliasOptionsToken, StringComparison.OrdinalIgnoreCase))
{
cmdlet.WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.DISCTypeContainsInvalidKey, aliasKey, key, path));
return false;
}
}
}
return true;
}
///
///
///
///
///
///
///
private static bool FunctionDefinitionsTypeValidationCallback(string key, object obj, PSCmdlet cmdlet, string path)
{
Hashtable[] hashtables = DISCPowerShellConfiguration.TryGetHashtableArray(obj);
if (hashtables == null)
{
cmdlet.WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustBeHashtableArray, key, path));
return false;
}
foreach (Hashtable hashtable in hashtables)
{
if (!hashtable.ContainsKey(FunctionNameToken))
{
cmdlet.WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustContainKey, key, FunctionNameToken, path));
return false;
}
if (!hashtable.ContainsKey(FunctionValueToken))
{
cmdlet.WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustContainKey, key, FunctionValueToken, path));
return false;
}
if (hashtable[FunctionValueToken] is not ScriptBlock)
{
cmdlet.WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.DISCKeyMustBeScriptBlock, FunctionValueToken, key, path));
return false;
}
foreach (string functionKey in hashtable.Keys)
{
if (!string.Equals(functionKey, FunctionNameToken, StringComparison.OrdinalIgnoreCase) &&
!string.Equals(functionKey, FunctionValueToken, StringComparison.OrdinalIgnoreCase) &&
!string.Equals(functionKey, FunctionOptionsToken, StringComparison.OrdinalIgnoreCase))
{
cmdlet.WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.DISCTypeContainsInvalidKey, functionKey, key, path));
return false;
}
}
}
return true;
}
///
///
///
///
///
///
///
private static bool VariableDefinitionsTypeValidationCallback(string key, object obj, PSCmdlet cmdlet, string path)
{
Hashtable[] hashtables = DISCPowerShellConfiguration.TryGetHashtableArray(obj);
if (hashtables == null)
{
cmdlet.WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustBeHashtableArray, key, path));
return false;
}
foreach (Hashtable hashtable in hashtables)
{
if (!hashtable.ContainsKey(VariableNameToken))
{
cmdlet.WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustContainKey, key, VariableNameToken, path));
return false;
}
if (!hashtable.ContainsKey(VariableValueToken))
{
cmdlet.WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustContainKey, key, VariableValueToken, path));
return false;
}
foreach (string variableKey in hashtable.Keys)
{
if (!string.Equals(variableKey, VariableNameToken, StringComparison.OrdinalIgnoreCase) &&
!string.Equals(variableKey, VariableValueToken, StringComparison.OrdinalIgnoreCase))
{
cmdlet.WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.DISCTypeContainsInvalidKey, variableKey, key, path));
return false;
}
}
}
return true;
}
///
/// Verifies a string type.
///
///
///
///
///
///
private static bool StringTypeValidationCallback(string key, object obj, PSCmdlet cmdlet, string path)
{
if (obj is not string)
{
cmdlet.WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustBeString, key, path));
return false;
}
return true;
}
///
/// Verifies a string array type.
///
///
///
///
///
///
private static bool StringArrayTypeValidationCallback(string key, object obj, PSCmdlet cmdlet, string path)
{
if (DISCPowerShellConfiguration.TryGetStringArray(obj) == null)
{
cmdlet.WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustBeStringArray, key, path));
return false;
}
return true;
}
private static bool BooleanTypeValidationCallback(string key, object obj, PSCmdlet cmdlet, string path)
{
if (obj is not bool)
{
cmdlet.WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustBeBoolean, key, path));
return false;
}
return true;
}
private static bool IntegerTypeValidationCallback(string key, object obj, PSCmdlet cmdlet, string path)
{
if (obj is not int && obj is not long)
{
cmdlet.WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustBeInteger, key, path));
return false;
}
return true;
}
///
/// Verifies that an array contains only string or hashtable elements.
///
///
///
///
///
///
private static bool StringOrHashtableArrayTypeValidationCallback(string key, object obj, PSCmdlet cmdlet, string path)
{
if (DISCPowerShellConfiguration.TryGetObjectsOfType