private bool BlockMethodInLanguageMode(object inputObject) { if (base.Context.LanguageMode.Equals(PSLanguageMode.RestrictedLanguage)) { PSInvalidOperationException exception = new PSInvalidOperationException(InternalCommandStrings.NoMethodInvocationInRestrictedLanguageMode); base.WriteError(new ErrorRecord(exception, "NoMethodInvocationInRestrictedLanguageMode", ErrorCategory.InvalidOperation, null)); return true; } if (base.Context.LanguageMode.Equals(PSLanguageMode.ConstrainedLanguage) && !CoreTypes.Contains(PSObject.Base(inputObject).GetType())) { PSInvalidOperationException exception2 = new PSInvalidOperationException(ParserStrings.InvokeMethodConstrainedLanguage); base.WriteError(new ErrorRecord(exception2, "MethodInvocationNotSupportedInConstrainedLanguage", ErrorCategory.InvalidOperation, null)); return true; } return false; }
internal PSInvalidOperationException NewInvalidOperationException( string baseName, string resourceId, params object[] args) { if (string.IsNullOrEmpty(baseName)) { throw this.NewArgumentNullException(nameof(baseName)); } if (string.IsNullOrEmpty(resourceId)) { throw this.NewArgumentNullException(nameof(resourceId)); } PSInvalidOperationException operationException = new PSInvalidOperationException(ResourceManagerCache.FormatResourceString(Assembly.GetCallingAssembly(), baseName, resourceId, args)); this.TraceException((Exception)operationException); return(operationException); }
/// <summary> /// Traces the Message and StackTrace properties of the exception /// and returns the new exception. This variant allows the caller to /// specify alternate template text, but only in assembly S.M.A.Core. /// </summary> /// <param name="innerException"> /// This is the InnerException for the InvalidOperationException /// </param> /// <param name="resourceString"> /// The template string for this error /// </param> /// <param name="args"> /// Objects corresponding to {0}, {1}, etc. in the resource string /// </param> /// <returns>Exception instance ready to throw</returns> internal static PSInvalidOperationException NewInvalidOperationException( Exception innerException, string resourceString, params object[] args) { if (String.IsNullOrEmpty(resourceString)) { throw NewArgumentNullException("resourceString"); } string message = StringUtil.Format(resourceString, args); var e = new PSInvalidOperationException(message, innerException); return e; }
/// <summary> /// Traces the Message and StackTrace properties of the exception /// and returns the new exception /// </summary> /// <returns>Exception instance ready to throw</returns> internal static PSInvalidOperationException NewInvalidOperationException() { #if CORECLR //TODO:CORECLR StackTrace is not in CoreCLR string message = string.Empty; #else string message = StringUtil.Format(AutomationExceptions.InvalidOperation, new System.Diagnostics.StackTrace().GetFrame(1).GetMethod().Name); #endif var e = new PSInvalidOperationException(message); return e; }
/// <summary> /// Check if the language mode is the restrictedLanguageMode before invoking a method. /// Write out error message and return true if we are in restrictedLanguageMode. /// </summary> /// <returns></returns> private bool BlockMethodInLanguageMode(Object inputObject) { // Cannot invoke a method in RestrictedLanguage mode if (Context.LanguageMode == PSLanguageMode.RestrictedLanguage) { PSInvalidOperationException exception = new PSInvalidOperationException(InternalCommandStrings.NoMethodInvocationInRestrictedLanguageMode); WriteError(new ErrorRecord(exception, "NoMethodInvocationInRestrictedLanguageMode", ErrorCategory.InvalidOperation, null)); return true; } // Cannot invoke certain methods in ConstrainedLanguage mode if (Context.LanguageMode == PSLanguageMode.ConstrainedLanguage) { Object baseObject = PSObject.Base(inputObject); if (!CoreTypes.Contains(baseObject.GetType())) { PSInvalidOperationException exception = new PSInvalidOperationException(ParserStrings.InvokeMethodConstrainedLanguage); WriteError(new ErrorRecord(exception, "MethodInvocationNotSupportedInConstrainedLanguage", ErrorCategory.InvalidOperation, null)); return true; } } return false; }
private void CheckLanguageMode() { if (Context.LanguageMode.Equals(PSLanguageMode.RestrictedLanguage)) { string message = String.Format(CultureInfo.InvariantCulture, InternalCommandStrings.OperationNotAllowedInRestrictedLanguageMode, _binaryOperator); PSInvalidOperationException exception = new PSInvalidOperationException(message); ThrowTerminatingError(new ErrorRecord(exception, "OperationNotAllowedInRestrictedLanguageMode", ErrorCategory.InvalidOperation, null)); } }
internal void BindCommandLineParameters(Collection<CommandParameterInternal> arguments) { int num; _tracer.WriteLine("Argument count: {0}", new object[] { arguments.Count }); if (this._commandMetadata.Obsolete != null) { if (this._commandMetadata.Obsolete.IsError) { PSInvalidOperationException exception = new PSInvalidOperationException(this._commandMetadata.Obsolete.Message); exception.SetErrorId("UseOfDeprecatedCmdlet"); exception.ErrorRecord.SetTargetObject(this._commandMetadata.Name); throw exception; } this._commandRuntime.WriteWarning(this._commandMetadata.Obsolete.Message); } this.BindCommandLineParametersNoValidation(arguments); bool isPipelineInputExpected = !this._commandRuntime.IsClosed || !this._commandRuntime.InputPipe.Empty; if (!isPipelineInputExpected) { num = this.ValidateParameterSets(false, true); } else { num = this.ValidateParameterSets(true, false); } if ((num == 1) && !base.DefaultParameterBindingInUse) { this.ApplyDefaultParameterBinding("Mandatory Checking", false); } if ((num > 1) && isPipelineInputExpected) { int num2 = this.FilterParameterSetsTakingNoPipelineInput(); if (num2 != base._currentParameterSetFlag) { base._currentParameterSetFlag = num2; num = this.ValidateParameterSets(true, false); } } IDisposable disposable = ParameterBinderBase.bindingTracer.TraceScope("MANDATORY PARAMETER CHECK on cmdlet [{0}]", new object[] { this._commandMetadata.Name }); try { Collection<MergedCompiledCommandParameter> collection; this.HandleUnboundMandatoryParameters(num, true, isPipelineInputExpected, out collection); if (base.DefaultParameterBinder is ScriptParameterBinder) { base.BindUnboundScriptParameters(); } } catch (ParameterBindingException exception2) { if (!base.DefaultParameterBindingInUse) { throw; } base.ThrowElaboratedBindingException(exception2); } finally { if (disposable != null) { disposable.Dispose(); } } if (!isPipelineInputExpected) { this.VerifyParameterSetSelected(); } base._prePipelineProcessingParameterSetFlags = base._currentParameterSetFlag; }
/// <summary> /// Attempts to open the item in Orca, if installed; otherwise, tries to invoke the "edit" verb on the package. /// </summary> /// <param name="item">The <see cref="PSObject"/> representing a package to open.</param> protected override void ProcessItem(PSObject item) { string path = item.GetPropertyValue<string>("PSPath"); path = this.SessionState.Path.GetUnresolvedProviderPathFromPSPath(path); // Make sure the item is an MSI or MSP package. var type = FileInfo.GetFileTypeInternal(path); if (FileType.Package != type && FileType.Patch != type) { var message = string.Format(CultureInfo.CurrentCulture, Resources.Error_InvalidStorage, path); var ex = new PSInvalidOperationException(message); this.WriteError(ex.ErrorRecord); return; } var info = new ProcessStartInfo() { WorkingDirectory = System.IO.Path.GetDirectoryName(path), }; if (!string.IsNullOrEmpty(this.orcaPath)) { // Open in Orca, if installed. info.FileName = this.orcaPath; info.Arguments = "\"" + path + "\""; } else { // Try to use the edit verb instead. info.FileName = path; info.UseShellExecute = true; info.Verb = "edit"; } Process process = null; try { process = Process.Start(info); if (this.Wait) { process.WaitForExit(); } } catch (Exception ex) { if (ex is InvalidOperationException || ex is Win32Exception) { // Likely the "edit" verb is not supported so terminate. var pse = new PSInvalidOperationException(ex.Message, ex); this.ThrowTerminatingError(pse.ErrorRecord); } else { throw; } } finally { if (null != process) { process.Dispose(); } } }
protected override void BeginProcessing() { if (base.isSddlSpecified && base.showUISpecified) { throw new PSInvalidOperationException(StringUtil.Format(RemotingErrorIdStrings.ShowUIAndSDDLCannotExist, "SecurityDescriptorSddl", "ShowSecurityDescriptorUI")); } if (base.isRunAsCredentialSpecified) { base.WriteWarning(RemotingErrorIdStrings.RunAsSessionConfigurationSecurityWarning); } if (base.isSddlSpecified) { CommonSecurityDescriptor descriptor = new CommonSecurityDescriptor(false, false, base.sddl); SecurityIdentifier sid = new SecurityIdentifier(WellKnownSidType.NetworkSid, null); bool flag = false; AceEnumerator enumerator = descriptor.DiscretionaryAcl.GetEnumerator(); while (enumerator.MoveNext()) { CommonAce current = (CommonAce) enumerator.Current; if ((current.AceQualifier.Equals(AceQualifier.AccessDenied) && current.SecurityIdentifier.Equals(sid)) && (current.AccessMask == 0x10000000)) { flag = true; break; } } switch (base.AccessMode) { case PSSessionConfigurationAccessMode.Local: if (!flag) { descriptor.DiscretionaryAcl.AddAccess(AccessControlType.Deny, sid, 0x10000000, InheritanceFlags.None, PropagationFlags.None); base.sddl = descriptor.GetSddlForm(AccessControlSections.All); } break; case PSSessionConfigurationAccessMode.Remote: if (flag) { descriptor.DiscretionaryAcl.RemoveAccessSpecific(AccessControlType.Deny, sid, 0x10000000, InheritanceFlags.None, PropagationFlags.None); if (descriptor.DiscretionaryAcl.Count == 0) { SecurityIdentifier identifier2 = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null); descriptor.DiscretionaryAcl.AddAccess(AccessControlType.Allow, identifier2, 0x10000000, InheritanceFlags.None, PropagationFlags.None); if ((Environment.OSVersion.Version.Major >= 6) && (Environment.OSVersion.Version.Minor >= 2)) { SecurityIdentifier identifier3 = new SecurityIdentifier("S-1-5-32-580"); descriptor.DiscretionaryAcl.AddAccess(AccessControlType.Allow, identifier3, 0x10000000, InheritanceFlags.None, PropagationFlags.None); } } base.sddl = descriptor.GetSddlForm(AccessControlSections.All); } break; } } if (!base.isSddlSpecified && !base.showUISpecified) { if (base.AccessMode.Equals(PSSessionConfigurationAccessMode.Local)) { base.sddl = PSSessionConfigurationCommandBase.GetLocalSddl(); base.isSddlSpecified = true; } else if (base.AccessMode.Equals(PSSessionConfigurationAccessMode.Remote)) { base.sddl = PSSessionConfigurationCommandBase.GetRemoteSddl(); base.isSddlSpecified = true; } } RemotingCommandUtil.CheckRemotingCmdletPrerequisites(); PSSessionConfigurationCommandUtilities.ThrowIfNotAdministrator(); WSManConfigurationOption transportOption = base.transportOption as WSManConfigurationOption; if (((transportOption != null) && transportOption.ProcessIdleTimeoutSec.HasValue) && !base.isUseSharedProcessSpecified) { PSInvalidOperationException exception = new PSInvalidOperationException(StringUtil.Format(RemotingErrorIdStrings.InvalidConfigurationXMLAttribute, "ProcessIdleTimeoutSec", "UseSharedProcess")); base.ThrowTerminatingError(exception.ErrorRecord); } }
internal void AdjustForProtocolVariations(Version serverProtocolVersion) { if (serverProtocolVersion <= RemotingConstants.ProtocolVersionWin7RTM) { int num; WSManNativeApi.WSManGetSessionOptionAsDword(this.wsManSessionHandle, WSManNativeApi.WSManSessionOption.WSMAN_OPTION_MAX_ENVELOPE_SIZE_KB, out num); if (num == 500) { int num3; int errorCode = WSManNativeApi.WSManSetSessionOption(this.wsManSessionHandle, WSManNativeApi.WSManSessionOption.WSMAN_OPTION_MAX_ENVELOPE_SIZE_KB, new WSManNativeApi.WSManDataDWord(150)); if (errorCode != 0) { PSInvalidOperationException exception = new PSInvalidOperationException(WSManNativeApi.WSManGetErrorMessage(wsManApiStaticData.WSManAPIHandle, errorCode)); throw exception; } WSManNativeApi.WSManGetSessionOptionAsDword(this.wsManSessionHandle, WSManNativeApi.WSManSessionOption.WSMAN_OPTION_SHELL_MAX_DATA_SIZE_PER_MESSAGE_KB, out num3); base.Fragmentor.FragmentSize = num3 << 10; } } }
private void Initialize(Uri connectionUri, WSManConnectionInfo connectionInfo) { WSManNativeApi.BaseWSManAuthenticationCredentials credentials; int num2; this._connectionInfo = connectionInfo; bool isSSLSpecified = false; string originalString = connectionUri.OriginalString; if ((connectionUri == connectionInfo.ConnectionUri) && connectionInfo.UseDefaultWSManPort) { originalString = WSManConnectionInfo.GetConnectionString(connectionInfo.ConnectionUri, out isSSLSpecified); } string str2 = string.Empty; if (PSSessionConfigurationData.IsServerManager) { str2 = ";MSP=7a83d074-bb86-4e52-aa3e-6cc73cc066c8"; } if (string.IsNullOrEmpty(connectionUri.Query)) { originalString = string.Format(CultureInfo.InvariantCulture, "{0}?PSVersion={1}{2}", new object[] { originalString.TrimEnd(new char[] { '/' }), PSVersionInfo.PSVersion, str2 }); } else { originalString = string.Format(CultureInfo.InvariantCulture, "{0};PSVersion={1}{2}", new object[] { originalString, PSVersionInfo.PSVersion, str2 }); } if (connectionInfo.CertificateThumbprint != null) { credentials = new WSManNativeApi.WSManCertificateThumbprintCredentials(connectionInfo.CertificateThumbprint); } else { string userName = null; SecureString pwd = null; if ((connectionInfo.Credential != null) && !string.IsNullOrEmpty(connectionInfo.Credential.UserName)) { userName = connectionInfo.Credential.UserName; pwd = connectionInfo.Credential.Password; } WSManNativeApi.WSManUserNameAuthenticationCredentials credentials2 = new WSManNativeApi.WSManUserNameAuthenticationCredentials(userName, pwd, connectionInfo.WSManAuthenticationMechanism); credentials = credentials2; } WSManNativeApi.WSManUserNameAuthenticationCredentials authCredentials = null; if (connectionInfo.ProxyCredential != null) { WSManNativeApi.WSManAuthenticationMechanism authMechanism = WSManNativeApi.WSManAuthenticationMechanism.WSMAN_FLAG_AUTH_NEGOTIATE; string str5 = null; SecureString password = null; switch (connectionInfo.ProxyAuthentication) { case AuthenticationMechanism.Basic: authMechanism = WSManNativeApi.WSManAuthenticationMechanism.WSMAN_FLAG_AUTH_BASIC; break; case AuthenticationMechanism.Negotiate: authMechanism = WSManNativeApi.WSManAuthenticationMechanism.WSMAN_FLAG_AUTH_NEGOTIATE; break; case AuthenticationMechanism.Digest: authMechanism = WSManNativeApi.WSManAuthenticationMechanism.WSMAN_FLAG_AUTH_DIGEST; break; } if (!string.IsNullOrEmpty(connectionInfo.ProxyCredential.UserName)) { str5 = connectionInfo.ProxyCredential.UserName; password = connectionInfo.ProxyCredential.Password; } authCredentials = new WSManNativeApi.WSManUserNameAuthenticationCredentials(str5, password, authMechanism); } WSManNativeApi.WSManProxyInfo info = (connectionInfo.ProxyAccessType == ProxyAccessType.None) ? null : new WSManNativeApi.WSManProxyInfo(connectionInfo.ProxyAccessType, authCredentials); int errorCode = 0; try { errorCode = WSManNativeApi.WSManCreateSession(wsManApiStaticData.WSManAPIHandle, originalString, 0, (IntPtr) credentials.GetMarshalledObject(), (info == null) ? IntPtr.Zero : ((IntPtr) info), ref this.wsManSessionHandle); } catch(Exception ex) { } finally { if (authCredentials != null) { authCredentials.Dispose(); } if (info != null) { info.Dispose(); } if (credentials != null) { credentials.Dispose(); } } if (errorCode != 0) { PSInvalidOperationException exception = new PSInvalidOperationException(WSManNativeApi.WSManGetErrorMessage(wsManApiStaticData.WSManAPIHandle, errorCode)); throw exception; } WSManNativeApi.WSManGetSessionOptionAsDword(this.wsManSessionHandle, WSManNativeApi.WSManSessionOption.WSMAN_OPTION_SHELL_MAX_DATA_SIZE_PER_MESSAGE_KB, out num2); base.Fragmentor.FragmentSize = num2 << 10; WSManNativeApi.WSManGetSessionOptionAsDword(this.wsManSessionHandle, WSManNativeApi.WSManSessionOption.WSMAN_OPTION_MAX_RETRY_TIME, out this.maxRetryTime); base.dataToBeSent.Fragmentor = base.Fragmentor; this.noCompression = !connectionInfo.UseCompression; this.noMachineProfile = connectionInfo.NoMachineProfile; if (isSSLSpecified) { this.SetWSManSessionOption(WSManNativeApi.WSManSessionOption.WSMAN_OPTION_USE_SSL, 1); } if (connectionInfo.NoEncryption) { this.SetWSManSessionOption(WSManNativeApi.WSManSessionOption.WSMAN_OPTION_UNENCRYPTED_MESSAGES, 1); } if (connectionInfo.AllowImplicitCredentialForNegotiate) { errorCode = WSManNativeApi.WSManSetSessionOption(this.wsManSessionHandle, WSManNativeApi.WSManSessionOption.WSMAN_OPTION_ALLOW_NEGOTIATE_IMPLICIT_CREDENTIALS, new WSManNativeApi.WSManDataDWord(1)); } if (connectionInfo.UseUTF16) { this.SetWSManSessionOption(WSManNativeApi.WSManSessionOption.WSMAN_OPTION_UTF16, 1); } if (connectionInfo.SkipCACheck) { this.SetWSManSessionOption(WSManNativeApi.WSManSessionOption.WSMAN_OPTION_SKIP_CA_CHECK, 1); } if (connectionInfo.SkipCNCheck) { this.SetWSManSessionOption(WSManNativeApi.WSManSessionOption.WSMAN_OPTION_SKIP_CN_CHECK, 1); } if (connectionInfo.SkipRevocationCheck) { this.SetWSManSessionOption(WSManNativeApi.WSManSessionOption.WSMAN_OPTION_SKIP_REVOCATION_CHECK, 1); } if (connectionInfo.IncludePortInSPN) { this.SetWSManSessionOption(WSManNativeApi.WSManSessionOption.WSMAN_OPTION_ENABLE_SPN_SERVER_PORT, 1); } this.SetWSManSessionOption(WSManNativeApi.WSManSessionOption.WSMAN_OPTION_USE_INTERACTIVE_TOKEN, connectionInfo.EnableNetworkAccess ? 1 : 0); string name = connectionInfo.UICulture.Name; if (!string.IsNullOrEmpty(name)) { this.SetWSManSessionOption(WSManNativeApi.WSManSessionOption.WSMAN_OPTION_UI_LANGUAGE, name); } string str9 = connectionInfo.Culture.Name; if (!string.IsNullOrEmpty(str9)) { this.SetWSManSessionOption(WSManNativeApi.WSManSessionOption.WSMAN_OPTION_LOCALE, str9); } this.SetDefaultTimeOut(connectionInfo.OperationTimeout); this.SetConnectTimeOut(connectionInfo.OpenTimeout); this.SetCloseTimeOut(connectionInfo.CancelTimeout); this.SetSignalTimeOut(connectionInfo.CancelTimeout); }
internal void SetWSManSessionOption(WSManNativeApi.WSManSessionOption option, string stringData) { using (WSManNativeApi.WSManData data = new WSManNativeApi.WSManData(stringData)) { int errorCode = WSManNativeApi.WSManSetSessionOption(this.wsManSessionHandle, option, (IntPtr) data); if (errorCode != 0) { PSInvalidOperationException exception = new PSInvalidOperationException(WSManNativeApi.WSManGetErrorMessage(wsManApiStaticData.WSManAPIHandle, errorCode)); throw exception; } } }
internal void SetWSManSessionOption(WSManNativeApi.WSManSessionOption option, int dwordData) { int errorCode = WSManNativeApi.WSManSetSessionOption(this.wsManSessionHandle, option, new WSManNativeApi.WSManDataDWord(dwordData)); if (errorCode != 0) { PSInvalidOperationException exception = new PSInvalidOperationException(WSManNativeApi.WSManGetErrorMessage(wsManApiStaticData.WSManAPIHandle, errorCode)); throw exception; } }
internal void SetSignalTimeOut(int milliseconds) { using (BaseClientTransportManager.tracer.TraceMethod("Setting SignalShell timeout: {0} milliseconds", new object[] { milliseconds })) { int errorCode = WSManNativeApi.WSManSetSessionOption(this.wsManSessionHandle, WSManNativeApi.WSManSessionOption.WSMAN_OPTION_TIMEOUTMS_SIGNAL_SHELL, new WSManNativeApi.WSManDataDWord(milliseconds)); if (errorCode != 0) { PSInvalidOperationException exception = new PSInvalidOperationException(WSManNativeApi.WSManGetErrorMessage(wsManApiStaticData.WSManAPIHandle, errorCode)); throw exception; } } }
internal void Remove(string[] path, bool recurse, ProviderRuntime runtime) { GlobAndInvoke<ContainerCmdletProvider>(path, runtime, (curPath, provider) => { // TODO: I think Powershell checks whether we are currently in the path we want to remove // (or a subpath). Check this and throw an error if it's true if (provider.HasChildItems(curPath, runtime) && !recurse) { // TODO: I think Powershell invokes ShouldContinue here and asks whether to remove // items recursively or not. We should somehow do this too. Maybe by getting // access to runtime._cmdlet, or by implementing a wrapper function in ProviderRuntime var msg = String.Format("The item at path '{0}' has child items. Use recursion to remove it", curPath); var invOpEx = new PSInvalidOperationException(msg, "CannotRemoveItemWithChildrenWithoutRecursion", ErrorCategory.InvalidOperation, null); // FIXME: In this case, Powershell does throw a CmdletInvocationException. Maybe because // this check is done directly inside the Remove-Item cmdlet, or maybe it only // happens if ShouldContinue doesn't work in a non-interactive environment. // Anyway, it feels right that the work is done here and we will simply throw this // kind of exception for compatability. Maybe when the TODO before is approach we should // keep in mind that this kind of exception is required to be thrown throw new CmdletInvocationException(invOpEx.Message, invOpEx); } provider.RemoveItem(curPath, recurse, runtime); } ); }
private void CheckLanguageMode() { if (base.Context.LanguageMode.Equals(PSLanguageMode.RestrictedLanguage)) { PSInvalidOperationException exception = new PSInvalidOperationException(string.Format(CultureInfo.InvariantCulture, InternalCommandStrings.OperationNotAllowedInRestrictedLanguageMode, new object[] { this._binaryOperator })); base.ThrowTerminatingError(new ErrorRecord(exception, "OperationNotAllowedInRestrictedLanguageMode", ErrorCategory.InvalidOperation, null)); } }
/// <summary> /// /// </summary> /// <exception cref="InvalidOperationException"> /// 1. Either both "AssemblyName" and "ConfigurationTypeName" must be specified /// or both must not be specified. /// </exception> 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); } } }
protected override void ProcessRecord() { Collection<string> collection = UpdateData.Glob(base.PrependPath, "FormatPrependPathException", this); Collection<string> collection2 = UpdateData.Glob(base.AppendPath, "FormatAppendPathException", this); if (((base.PrependPath.Length <= 0) && (base.AppendPath.Length <= 0)) || ((collection.Count != 0) || (collection2.Count != 0))) { string updateFormatDataAction = UpdateDataStrings.UpdateFormatDataAction; string updateTarget = UpdateDataStrings.UpdateTarget; if (base.Context.RunspaceConfiguration != null) { for (int i = collection.Count - 1; i >= 0; i--) { string target = string.Format(Thread.CurrentThread.CurrentCulture, updateTarget, new object[] { collection[i] }); if (base.ShouldProcess(target, updateFormatDataAction)) { base.Context.RunspaceConfiguration.Formats.Prepend(new FormatConfigurationEntry(collection[i])); } } foreach (string str4 in collection2) { string str5 = string.Format(Thread.CurrentThread.CurrentCulture, updateTarget, new object[] { str4 }); if (base.ShouldProcess(str5, updateFormatDataAction)) { base.Context.RunspaceConfiguration.Formats.Append(new FormatConfigurationEntry(str4)); } } try { base.Context.CurrentRunspace.RunspaceConfiguration.Formats.Update(true); return; } catch (RuntimeException exception) { base.WriteError(new ErrorRecord(exception, "FormatXmlUpdateException", ErrorCategory.InvalidOperation, null)); return; } } if (base.Context.InitialSessionState != null) { if (base.Context.InitialSessionState.DisableFormatUpdates) { throw new PSInvalidOperationException(UpdateDataStrings.FormatUpdatesDisabled); } HashSet<string> set = new HashSet<string>(StringComparer.CurrentCultureIgnoreCase); Collection<SessionStateFormatEntry> collection3 = new Collection<SessionStateFormatEntry>(); for (int j = collection.Count - 1; j >= 0; j--) { string str6 = string.Format(Thread.CurrentThread.CurrentCulture, updateTarget, new object[] { collection[j] }); if (base.ShouldProcess(str6, updateFormatDataAction) && !set.Contains(collection[j])) { set.Add(collection[j]); collection3.Add(new SessionStateFormatEntry(collection[j])); } } foreach (SessionStateFormatEntry entry in base.Context.InitialSessionState.Formats) { if (entry.FileName != null) { if (!set.Contains(entry.FileName)) { set.Add(entry.FileName); collection3.Add(entry); } } else { collection3.Add(entry); } } foreach (string str7 in collection2) { string str8 = string.Format(Thread.CurrentThread.CurrentCulture, updateTarget, new object[] { str7 }); if (base.ShouldProcess(str8, updateFormatDataAction) && !set.Contains(str7)) { set.Add(str7); collection3.Add(new SessionStateFormatEntry(str7)); } } try { base.Context.InitialSessionState.Formats.Clear(); Collection<PSSnapInTypeAndFormatErrors> mshsnapins = new Collection<PSSnapInTypeAndFormatErrors>(); foreach (SessionStateFormatEntry entry2 in collection3) { string fileName = entry2.FileName; PSSnapInInfo pSSnapIn = entry2.PSSnapIn; if ((pSSnapIn != null) && !string.IsNullOrEmpty(pSSnapIn.Name)) { fileName = pSSnapIn.Name; } if (entry2.Formattable != null) { PSInvalidOperationException exception2 = new PSInvalidOperationException(UpdateDataStrings.CannotUpdateFormatWithFormatTable); base.WriteError(new ErrorRecord(exception2, "CannotUpdateFormatWithFormatTable", ErrorCategory.InvalidOperation, null)); } else { if (entry2.FormatData != null) { mshsnapins.Add(new PSSnapInTypeAndFormatErrors(fileName, entry2.FormatData)); } else { mshsnapins.Add(new PSSnapInTypeAndFormatErrors(fileName, entry2.FileName)); } base.Context.InitialSessionState.Formats.Add(entry2); } } if (mshsnapins.Count > 0) { base.Context.FormatDBManager.UpdateDataBase(mshsnapins, base.Context.AuthorizationManager, base.Context.EngineHostInterface, false); FormatAndTypeDataHelper.ThrowExceptionOnError("ErrorsUpdatingFormats", null, mshsnapins, RunspaceConfigurationCategory.Formats); } } catch (RuntimeException exception3) { base.WriteError(new ErrorRecord(exception3, "FormatXmlUpdateException", ErrorCategory.InvalidOperation, null)); } } } }