/* * /// <summary> * /// If true then PolicyID is a user ID. * /// </summary> * private bool IsUser * { * get { return Request.Path.EndsWith( "UserDetails.aspx" ); } * } */ #endregion #region Public Methods /// <summary> /// Gets the Disable Sharing for current iFolder. /// </summary> /// <param name="policy">iFolder policy object</param> /*public void GetDisableSharingPolicy( iFolderPolicy policy ) * { * /// write the code to obtain and display the policy for this ifolder * }*/ /// <summary> /// Gets the Disable Sharing policy for the system. /// </summary> /// <param name="policy">System policy object</param> public void GetDisableSharingPolicy(SystemPolicy policy) { int DisableStatus = policy.DisableSharingStatus; disableSharingOn.Checked = enforcedDisableSharing.Checked = disablePastSharing.Checked = false; disableSharingOn.Enabled = true; enforcedDisableSharing.Enabled = false; // check for Disable sharing and/or Enforce disable sharing if (DisableStatus == (int)DisableShare.DisableSharing) { disableSharingOn.Checked = true; enforcedDisableSharing.Enabled = true; } else { // check for enforce disabling of sharing if ((DisableStatus & (int)DisableShare.DisableSharing) == (int)DisableShare.DisableSharing) { disableSharingOn.Checked = true; enforcedDisableSharing.Enabled = true; if ((DisableStatus & (int)DisableShare.EnforcedDisableSharing) == (int)DisableShare.EnforcedDisableSharing) { //disableSharingOn.Checked = true; disableSharingOn.Enabled = false; enforcedDisableSharing.Enabled = true; enforcedDisableSharing.Checked = true; } } } }
protected Runspace CreateRunspace() { Runspace runspace = null; if (this.rsConfig != null) { runspace = RunspaceFactory.CreateRunspace(this.host, this.rsConfig); } else { runspace = RunspaceFactory.CreateRunspaceFromSessionStateNoClone(this.host, this._initialSessionState); } runspace.ThreadOptions = (this.ThreadOptions == PSThreadOptions.Default) ? PSThreadOptions.ReuseThread : this.ThreadOptions; runspace.ApartmentState = this.ApartmentState; this.PropagateApplicationPrivateData(runspace); runspace.Open(); if (SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce) { runspace.ExecutionContext.LanguageMode = PSLanguageMode.ConstrainedLanguage; } runspace.Events.ForwardEvent += new EventHandler <PSEventArgs>(this.OnRunspaceForwardEvent); lock (this.runspaceList) { this.runspaceList.Add(runspace); this.totalRunspaces = this.runspaceList.Count; } lock (this.syncObject) { this.cleanupTimer.Change(this.CleanupInterval, this.CleanupInterval); } this.RunspaceCreated.SafeInvoke <RunspaceCreatedEventArgs>(this, new RunspaceCreatedEventArgs(runspace)); return(runspace); }
} // CoreBeginProcessing /// <summary> /// Create a throttle operation using NewProcessConnectionInfo /// ie., Out-Of-Process runspace. /// </summary> protected override void CreateHelpersForSpecifiedComputerNames() { // If we're in ConstrainedLanguage mode and the system is in lockdown mode, // ensure that they haven't specified a ScriptBlock or InitScript - as // we can't protect that boundary if ((Context.LanguageMode == PSLanguageMode.ConstrainedLanguage) && (SystemPolicy.GetSystemLockdownPolicy() != SystemEnforcementMode.Enforce) && ((ScriptBlock != null) || (InitializationScript != null))) { ThrowTerminatingError( new ErrorRecord( new PSNotSupportedException(RemotingErrorIdStrings.CannotStartJobInconsistentLanguageMode), "CannotStartJobInconsistentLanguageMode", ErrorCategory.PermissionDenied, Context.LanguageMode)); } NewProcessConnectionInfo connectionInfo = new NewProcessConnectionInfo(this.Credential); connectionInfo.RunAs32 = _shouldRunAs32; connectionInfo.InitializationScript = _initScript; connectionInfo.AuthenticationMechanism = this.Authentication; connectionInfo.PSVersion = this.PSVersion; RemoteRunspace remoteRunspace = (RemoteRunspace)RunspaceFactory.CreateRunspace(connectionInfo, this.Host, Utils.GetTypeTableFromExecutionContextTLS()); remoteRunspace.Events.ReceivedEvents.PSEventReceived += OnRunspacePSEventReceived; Pipeline pipeline = CreatePipeline(remoteRunspace); IThrottleOperation operation = new ExecutionCmdletHelperComputerName(remoteRunspace, pipeline); Operations.Add(operation); }
/// <summary> /// Creates a local runspace with the autoloading turned on. /// </summary> /// <returns></returns> internal static Runspace CreateLocalActivityRunspace(PSLanguageMode?languageMode = null, bool useCurrentThreadForExecution = true) { InitialSessionState iss = GetInitialSessionStateWithSharedTypesAndNoFormat(); if (SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce) { iss.LanguageMode = PSLanguageMode.ConstrainedLanguage; } if (languageMode != null && languageMode.HasValue) { iss.LanguageMode = languageMode.Value; } // Add a variable indicating that we're in Workflow endpoint. This enables the // autoloading feature. SessionStateVariableEntry ssve = new SessionStateVariableEntry("RunningInPSWorkflowEndpoint", true, "True if we're in a Workflow Endpoint", ScopedItemOptions.Constant); iss.Variables.Add(ssve); Runspace runspace = RunspaceFactory.CreateRunspace(iss); if (useCurrentThreadForExecution) { runspace.ThreadOptions = PSThreadOptions.UseCurrentThread; } return(runspace); }
/// <summary> /// Gets the file size policy for the system. /// </summary> /// <param name="policy">System policy</param> public void GetFileSizePolicy(SystemPolicy policy) { EffectiveLimit = 0; Enabled.Checked = LimitValue.Enabled = (policy.FileSizeLimit > 0); LimitValue.Text = (Enabled.Checked) ? Utils.ConvertToMBString(policy.FileSizeLimit, false, rm) : String.Empty; EffectiveTag.Visible = EffectiveValue.Visible = EffectiveUnits.Visible = false; }
/// <summary> /// Gets the disk quota policy for the system. /// </summary> /// <param name="policy">System policy object</param> public void GetDiskSpacePolicy(SystemPolicy policy) { EffectiveSpace = 0; Enabled.Checked = LimitValue.Enabled = (policy.SpaceLimitUser >= 0); LimitValue.Text = Enabled.Checked ? Utils.ConvertToMBString(policy.SpaceLimitUser, false, rm) : String.Empty; UsedTag.Visible = UsedValue.Visible = false; AvailableTag.Visible = AvailableValue.Visible = false; EffectiveTag.Visible = EffectiveValue.Visible = EffectiveUnits.Visible = false; }
/// <summary> /// Creates a stateful list of file type filters. /// </summary> /// <param name="policy">System policy object</param> /// <returns>A hashtable containing the file type filters.</returns> private Hashtable CreateFileTypeSource(SystemPolicy policy) { // Keep the state in a hashtable. Hashtable ht = new Hashtable(); foreach (string s in policy.FileTypesExcludes) { ht[s] = new FileTypeInfo(s, Utils.ConvertFromRegEx(s), false, true); } return(ht); }
/// <summary> /// Gets the file type policy for the system. /// </summary> /// <param name="policy">System policy.</param> public void GetFileTypePolicy(SystemPolicy policy) { // Show new file type controls NewFileTypeName.Visible = AddButton.Visible = true; // Create a list from the file type policy. FileTypeSource = CreateFileTypeSource(policy); // Build the data view from the table. FileTypeList.DataSource = CreateFileTypeListView(); FileTypeList.DataBind(); SetPageButtonState(); }
/// <summary> /// Sets the file type policy for the system. /// </summary> /// <param name="policy">System policy that the new file type filter will be set.</param> public void SetFileTypePolicy(SystemPolicy policy) { // Build a list of checked file types. ArrayList filterList = new ArrayList(); foreach (FileTypeInfo fti in FileTypeSource.Values) { filterList.Add(fti.RegExFileName); } // Set the user current system policy. policy.FileTypesExcludes = filterList.ToArray(typeof(string)) as string[]; }
/// <summary> /// Gets the iFolderLimit policy for the system. /// </summary> /// <param name="policy">System policy object</param> public void GetiFolderLimitPolicy(SystemPolicy policy) { Enabled.Checked = LimitValue.Enabled = (policy.NoiFoldersLimit >= 0); limit = (policy.NoiFoldersLimit == -1) ? DefaultiFolderLimit : policy.NoiFoldersLimit; if (policy.NoiFoldersLimit >= 0) { LimitValue.Text = limit.ToString(); } else { LimitValue.Text = string.Empty; } }
/// <summary> /// Gets the system policies. /// </summary> public void GetSystemPolicies() { SystemPolicy policy = web.GetSystemPolicy(); AccountEnabled.GetAccountPolicy(policy); iFolderEnabled.GetiFolderEnabledPolicy(policy); iFolderLimit.GetiFolderLimitPolicy(policy); DiskQuota.GetDiskSpacePolicy(policy); SecurityState.GetEncryptionPolicy(policy); FileSize.GetFileSizePolicy(policy); FileType.GetFileTypePolicy(policy); SyncInterval.GetSyncPolicy(policy); Sharing.GetSharingPolicy(policy); }
private void ReadScriptContents() { if (this._scriptContents == null) { try { using (FileStream stream = new FileStream(this._path, FileMode.Open, FileAccess.Read)) { using (StreamReader reader = new StreamReader(stream, Encoding.Default)) { this._scriptContents = reader.ReadToEnd(); this._originalEncoding = reader.CurrentEncoding; if (SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce) { if (SystemPolicy.GetLockdownPolicy(this._path, stream.SafeFileHandle) != SystemEnforcementMode.Enforce) { base.DefiningLanguageMode = (PSLanguageMode)0; } else { base.DefiningLanguageMode = (PSLanguageMode)3; } } else if (base.Context != null) { base.DefiningLanguageMode = new PSLanguageMode?(base.Context.LanguageMode); } } } } catch (ArgumentException exception) { ThrowCommandNotFoundException(exception); } catch (IOException exception2) { ThrowCommandNotFoundException(exception2); } catch (NotSupportedException exception3) { ThrowCommandNotFoundException(exception3); } catch (UnauthorizedAccessException exception4) { ThrowCommandNotFoundException(exception4); } } }
/// <summary> /// Gets the account policy for the current user. /// </summary> /// <param name="policy">User policy object</param> public void GetEncryptionPolicy(UserPolicy policy) { int securityStatus = policy.EncryptionStatus; encryption.Checked = enforceEncryption.Checked = ssl.Checked = enforceSSL.Checked = false; SystemPolicy SystemPolicy = web.GetSystemPolicy(); int SysEncrPolicy = SystemPolicy.EncryptionStatus; int GroupEncrPolicy = web.GetGroupEncryptionPolicy(policy.UserID); int DerivedStatus = 0; Session["SharingWasEnforced"] = "false"; Session["EncryptionWasChecked"] = "false"; DerivedStatus = DeriveStatus(SysEncrPolicy, GroupEncrPolicy, securityStatus, securityStatus); if (DerivedStatus != 0) { if ((DerivedStatus & (int)Encryption.Encrypt) == (int)Encryption.Encrypt) { encryption.Enabled = false; Session["EncryptionWasChecked"] = "true"; if ((DerivedStatus & (int)Encryption.EnforceEncrypt) == (int)Encryption.EnforceEncrypt) { encryption.Checked = enforceEncryption.Checked = true; enforceEncryption.Enabled = true; } else { encryption.Checked = true; enforceEncryption.Checked = false; enforceEncryption.Enabled = true; } // next check for bug id 296014 , where if this user has created an encrypted iFolder then disable // the encryption check box for him. if (IsUser) { if (web.IsPassPhraseSetForUser(Request.Params["ID"])) { encryption.Enabled = false; } } } else if ((DerivedStatus & (int)Encryption.EnforceSSL) == (int)Encryption.EnforceSSL) { // this is the case of enforceSharing for the particular user on userlevel policy encryption.Checked = enforceEncryption.Checked = false; Session["SharingWasEnforced"] = "true"; } } }
/// <summary> /// Gets the sync policy for the system. /// </summary> /// <param name="policy">System policy.</param> public void GetSyncPolicy(SystemPolicy policy) { EffectiveInterval = 0; Enabled.Checked = LimitValue.Enabled = (policy.SyncInterval > 0); if (Enabled.Checked) { int syncInterval = policy.SyncInterval / 60; LimitValue.Text = syncInterval.ToString(); } else { LimitValue.Text = String.Empty; } EffectiveTag.Visible = EffectiveValue.Visible = EffectiveUnits.Visible = false; }
private void CommonInitialization() { if (SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce) { if (SystemPolicy.GetLockdownPolicy(this._path, null) != SystemEnforcementMode.Enforce) { base.DefiningLanguageMode = (PSLanguageMode)0; } else { base.DefiningLanguageMode = (PSLanguageMode)3; } } else { base.DefiningLanguageMode = PSLanguageMode.FullLanguage; } }
/// <summary> /// Sets the policy for the user. /// </summary> /// <param name="policy">User policy where the information will be set.</param> public void SetDisableSharingPolicy(UserPolicy policy, string PolicyID) { int DisableSharingStatus = 0; int UserDisableStatus = policy.DisableSharingStatus; SystemPolicy systemPolicy = web.GetSystemPolicy(); int SystemDisableStatus = systemPolicy.DisableSharingStatus; if (((UserDisableStatus & (int)DisableShare.EnableSharing) == (int)DisableShare.EnableSharing) && disableSharingOn.Checked == false) { /// it means for this user , admin has enable the sharing on UserDetails page, so retain that DisableSharingStatus += (int)DisableShare.EnableSharing; //8 } /// if for this user disable sharing was "on" (either on user level or system level) and now admin has unchecked the checkbox then also store enable sharing -- 8 else if ((((SystemDisableStatus & (int)DisableShare.DisableSharing) == (int)DisableShare.DisableSharing) || ((UserDisableStatus & (int)DisableShare.DisableSharing) == (int)DisableShare.DisableSharing)) && disableSharingOn.Checked == false) { DisableSharingStatus += (int)DisableShare.EnableSharing; //8 } if (disableSharingOn.Checked && UserDisableStatus != 0) { /// add this value only if on user level some policy was set DisableSharingStatus += (int)DisableShare.DisableSharing; //1; } else if (disableSharingOn.Checked && (SystemDisableStatus == 0)) { DisableSharingStatus += (int)DisableShare.DisableSharing; //1; } if (enforcedDisableSharing.Checked) { DisableSharingStatus += (int)DisableShare.EnforcedDisableSharing; //4; } policy.DisableSharingStatus = DisableSharingStatus; /// Next change is to remove the past sharing if (disablePastSharing.Checked) { /// pass the userID web.DisableUserPastSharing(PolicyID); disablePastSharing.Checked = false; } }
/// <summary> /// Sets the policy for the user. /// </summary> /// <param name="policy">iFolder policy where the information will be set.</param> public void SetDisableSharingPolicy(iFolderPolicy policy, string PolicyID) { int DisableSharingStatus = 0; iFolder ifolder = web.GetiFolder(PolicyID); string OwnerID = ifolder.OwnerID; SystemPolicy systemPolicy = web.GetSystemPolicy(); UserPolicy userPolicy = web.GetUserPolicy(OwnerID); int iFolderDisableStatus = policy.DisableSharingStatus; int UserDisableStatus = userPolicy.DisableSharingStatus; int SystemDisableStatus = systemPolicy.DisableSharingStatus; if (((iFolderDisableStatus & (int)DisableShare.EnableSharing) == (int)DisableShare.EnableSharing) && disableSharingOn.Checked == false) { /// it means for this iFolder , admin had earlier enabled the sharing on iFolderDetails page, so retain that DisableSharingStatus += (int)DisableShare.EnableSharing; //8 } else if ((((SystemDisableStatus & (int)DisableShare.DisableSharing) == (int)DisableShare.DisableSharing) || ((UserDisableStatus & (int)DisableShare.DisableSharing) == (int)DisableShare.DisableSharing) || ((iFolderDisableStatus & (int)DisableShare.DisableSharing) == (int)DisableShare.DisableSharing)) && disableSharingOn.Checked == false) { /// if for this iFolder , disable sharing was "on" (either iFolder, user or system level) , and now admin has unchecked the box , then also store enable sharing -- 8 DisableSharingStatus += (int)DisableShare.EnableSharing; //8 } if (disableSharingOn.Checked && iFolderDisableStatus != 0) { /// consider the case when no disable of sharing on iFolder level but disable past sharing is applied. DisableSharingStatus += (int)DisableShare.DisableSharing; //1; } else if (disableSharingOn.Checked && (UserDisableStatus == 0 || ((UserDisableStatus & (int)DisableShare.EnableSharing) == (int)DisableShare.EnableSharing))) { /// if on user level, it was enabled and then if on iFolder level it is disabled , then for that case DisableSharingStatus += (int)DisableShare.DisableSharing; //1; } policy.DisableSharingStatus = DisableSharingStatus; /// Next change is to remove the past sharing , if (disablePastSharing.Checked) { /// pass the iFolderID web.DisableiFolderPastSharing(PolicyID); disablePastSharing.Checked = false; } }
/// <summary> /// Common initialization for all constructors. /// </summary> private void CommonInitialization() { // Assume external scripts are untrusted by default (for Get-Command, etc) // until we've actually parsed their script block. if (SystemPolicy.GetSystemLockdownPolicy() != SystemEnforcementMode.None) { // Get the lock down policy with no handle. This only impacts command discovery, // as the real language mode assignment will be done when we read the script // contents. SystemEnforcementMode scriptSpecificPolicy = SystemPolicy.GetLockdownPolicy(_path, null); if (scriptSpecificPolicy != SystemEnforcementMode.Enforce) { this.DefiningLanguageMode = PSLanguageMode.FullLanguage; } else { this.DefiningLanguageMode = PSLanguageMode.ConstrainedLanguage; } } }
/// <summary> /// Gets the account policy for the system. /// </summary> /// <param name="policy">System policy object</param> public void GetEncryptionPolicy(SystemPolicy policy) { int securityStatus = policy.EncryptionStatus; encryption.Checked = enforceEncryption.Checked = ssl.Checked = enforceSSL.Checked = false; int status = securityStatus & (int)Encryption.Encrypt; if (status == (int)Encryption.Encrypt) { encryption.Checked = true; /// next line for bug id 296014 , where if the encryption check box is enabled (irrespective of enforce checkbox) once on system level, it should be disabled. encryption.Enabled = false; encryption.Enabled = false; enforceEncryption.Enabled = true; status = securityStatus & (int)Encryption.EnforceEncrypt; if (status == (int)Encryption.EnforceEncrypt) { enforceEncryption.Checked = true; } } else { enforceEncryption.Checked = false; enforceEncryption.Enabled = false; } /*status = securityStatus & (int) Encryption.SSL; * if( status == (int)Encryption.SSL ) * { * ssl.Checked = true; * enforceSSL.Enabled = true; * status = securityStatus & (int) Encryption.EnforceSSL; * if( status == (int)Encryption.EnforceSSL) * enforceSSL.Checked = true; * } * else * { * enforceSSL.Checked = false; * enforceSSL.Enabled = false; * }*/ }
/// <summary> /// Sets the policy for the system. /// </summary> /// <param name="policy">System policy where the account information will be set.</param> public void SetSharingPolicy(SystemPolicy policy) { int SharingStatus = 0; if (SharingOn.Checked) { SharingStatus += (int)Share.Sharing; //1; } else { SharingStatus += (int)Share.DisableSharing; //8 } if (enforcedSharing.Checked) { SharingStatus += (int)Share.EnforcedSharing; //4; } policy.SharingStatus = SharingStatus; /// Next change is to remove the past sharing , if (disablePastSharing.Checked) { iFolderServer [] iFolderServers = web.GetServers(); foreach (iFolderServer server in iFolderServers) { if (server.PublicUrl != null) { remoteweb.Url = server.PublicUrl + "/iFolderAdmin.asmx"; } try { remoteweb.DisableSystemPastSharing(); } catch (Exception ex) { throw new ArgumentException(GetString("REVERTSHARINGCONNECTFAILED")); } } disablePastSharing.Checked = false; } }
/// <summary> /// Sets the policy for the system. /// </summary> /// <param name="policy">System policy where the account information will be set.</param> public void SetDisableSharingPolicy(SystemPolicy policy) { int DisableSharingStatus = 0; if (disableSharingOn.Checked) { DisableSharingStatus += (int)DisableShare.DisableSharing; //1; } if (enforcedDisableSharing.Checked) { DisableSharingStatus += (int)DisableShare.EnforcedDisableSharing; //4; } policy.DisableSharingStatus = DisableSharingStatus; /// Next change is to remove the past sharing , if (disablePastSharing.Checked) { web.DisableSystemPastSharing(); disablePastSharing.Checked = false; } }
/// <summary> /// Sets the disk space policy for the system. /// </summary> /// <param name="policy">System policy that the new disk space quota will be set.</param> public void SetDiskSpacePolicy(SystemPolicy policy) { // Verify that the disk space quota value is valid. if (Enabled.Checked) { string limitString = LimitValue.Text; if ((limitString != null) && (limitString != String.Empty)) { try { decimal limit = Convert.ToDecimal(limitString); if (limit >= 0) { // Convert from megabytes back to bytes. policy.SpaceLimitUser = Convert.ToInt64(Decimal.Round(limit, 2) * 1048576); } else { throw new ArgumentException(GetString("ERRORINVALIDQUOTA")); } } catch (FormatException) { throw new ArgumentException(GetString("ERRORINVALIDQUOTA")); } catch (OverflowException) { throw new ArgumentException(GetString("ERRORINVALIDQUOTA")); } } else { throw new ArgumentException(GetString("ERRORNOQUOTA")); } } else { policy.SpaceLimitUser = -1; } }
/// <summary> /// Sets the file size policy for the system. /// </summary> /// <param name="policy">System policy that the new file size filter will be set.</param> public void SetFileSizePolicy(SystemPolicy policy) { // Verify that the file size value is valid. if (Enabled.Checked) { string limitString = LimitValue.Text; if ((limitString != null) && (limitString != String.Empty)) { try { decimal limit = Convert.ToDecimal(limitString); if (limit >= 1) { // Convert megabytes to bytes. policy.FileSizeLimit = Convert.ToInt64(Decimal.Round(limit, 2) * 1048576); } else { throw new ArgumentException(GetString("ERRORINVALIDFILESIZE")); } } catch (FormatException) { throw new ArgumentException(GetString("ERRORINVALIDFILESIZE")); } catch (OverflowException) { throw new ArgumentException(GetString("ERRORINVALIDFILESIZE")); } } else { throw new ArgumentException(GetString("ERRORNOFILESIZE")); } } else { policy.FileSizeLimit = 0; } }
/// <summary> /// Sets the synchronization policy for the system. /// </summary> /// <param name="policy">System policy that the new sync interval will be set.</param> public void SetSyncPolicy(SystemPolicy policy) { // Verify that the file size value is valid. if (Enabled.Checked) { string limitString = LimitValue.Text; if ((limitString != null) && (limitString != String.Empty)) { try { int limit = Convert.ToInt32(limitString); if (limit >= 5 && limit <= 999) { // Convert the interval from minutes to seconds. policy.SyncInterval = limit * 60; } else { throw new ArgumentException(GetString("ERRORINVALIDSYNCINTERVAL")); } } catch (FormatException) { throw new ArgumentException(GetString("ERRORINVALIDSYNCINTERVAL")); } catch (OverflowException) { throw new ArgumentException(GetString("ERRORINVALIDSYNCINTERVAL")); } } else { throw new ArgumentException(GetString("ERRORNOSYNCINTERVAL")); } } else { policy.SyncInterval = 0; } }
/// <summary> /// Sets the account policy for the user. /// </summary> /// <param name="policy">User policy where the account information will be set.</param> public void SetEncryptionPolicy(SystemPolicy policy) { int securityStatus = 0; if (encryption.Checked) { securityStatus += (int)Encryption.Encrypt; //1; } if (enforceEncryption.Checked) { securityStatus += (int)Encryption.EnforceEncrypt; //2; } if (ssl.Checked) { securityStatus += (int)Encryption.SSL; //4; } if (enforceSSL.Checked) { securityStatus += (int)Encryption.EnforceSSL; //8; } policy.EncryptionStatus = securityStatus; }
/// <summary> /// Sets the iFolderLimite policy for the system. /// </summary> /// <param name="policy">System policy that the iFolderLimit will be set.</param> public void SetiFolderLimitPolicy(SystemPolicy policy) { // Verify that iFolderLimit value is valid. if (Enabled.Checked) { string limitString = LimitValue.Text; if ((limitString != null) && (limitString != String.Empty)) { try { long value = Convert.ToInt64(limitString); if (value >= 0) { policy.NoiFoldersLimit = value; } else { throw new ArgumentException(GetString("ERRORINVALIDIFOLDERLIMIT")); } } catch (FormatException) { throw new ArgumentException(GetString("ERRORINVALIDIFOLDERLIMIT")); } catch (OverflowException) { throw new ArgumentException(GetString("ERRORINVALIDIFOLDERLIMIT")); } } else { throw new ArgumentException(GetString("ERRORNOIFOLDERLIMIT")); } } else { policy.NoiFoldersLimit = -1; } }
internal static Runspace CreateLocalActivityRunspace(PSLanguageMode?languageMode = null, bool useCurrentThreadForExecution = true) { InitialSessionState initialSessionStateWithSharedTypesAndNoFormat = LocalRunspaceProvider.GetInitialSessionStateWithSharedTypesAndNoFormat(); if (SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce) { initialSessionStateWithSharedTypesAndNoFormat.LanguageMode = PSLanguageMode.ConstrainedLanguage; } if (languageMode.HasValue && languageMode.HasValue) { initialSessionStateWithSharedTypesAndNoFormat.LanguageMode = languageMode.Value; } SessionStateVariableEntry sessionStateVariableEntry = new SessionStateVariableEntry("RunningInPSWorkflowEndpoint", (object)((bool)1), "True if we're in a Workflow Endpoint", ScopedItemOptions.Constant); initialSessionStateWithSharedTypesAndNoFormat.Variables.Add(sessionStateVariableEntry); Runspace runspace = RunspaceFactory.CreateRunspace(initialSessionStateWithSharedTypesAndNoFormat); if (useCurrentThreadForExecution) { runspace.ThreadOptions = PSThreadOptions.UseCurrentThread; } return(runspace); }
public void ApplyPolicy(MainGame game, SystemPolicy policy) { //TODO(v0.8) remove previous policy buildings var playerProc = game.Derivates[this.Owner]; var playerTechs = game.States.DevelopmentAdvances.Of[this.Owner].ToDictionary(x => x.Topic.IdCode, x => (double)x.Level); var comparer = new ConstructionComparer(); foreach (var colony in game.States.Colonies.AtStar[this.Location, this.Owner]) { var plan = game.Orders[this.Owner].ConstructionPlans[colony]; plan.SpendingRatio = policy.SpendingRatio; var colonyProc = game.Derivates[colony]; var colonyVars = colonyProc.LocalEffects(game.Statics). UnionWith(playerProc.TechLevels).Get; //TODO(0.8) conver Statics.Constructables to dictionary foreach (var project in policy.Queue.Select(x => game.Statics.Constructables.First(p => p.IdCode == x))) { if (plan.Queue.All(x => !comparer.Compare(x, project)) && Prerequisite.AreSatisfied(project.Prerequisites, 0, playerTechs) && project.Condition.Evaluate(colonyVars) >= 0) { plan.Queue.Add(new StaticProject(project)); } } colonyProc.CalculateSpending(game, playerProc); } this.CalculateSpending(game); foreach (var colony in game.States.Colonies.AtStar[this.Location, this.Owner]) { game.Derivates[colony].CalculateDerivedEffects(game.Statics, playerProc); } }
/// <summary> /// End Processing. /// </summary> protected override void EndProcessing() { // Check if system is in locked down mode, in which case this cmdlet is disabled. if (SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce) { WriteError( new ErrorRecord( new PSSecurityException(RemotingErrorIdStrings.EnterPSHostProcessCmdletDisabled), "EnterPSHostProcessCmdletDisabled", ErrorCategory.SecurityError, null)); return; } // Check for host that supports interactive remote sessions. _interactiveHost = this.Host as IHostSupportsInteractiveSession; if (_interactiveHost == null) { WriteError( new ErrorRecord( new ArgumentException(RemotingErrorIdStrings.HostDoesNotSupportIASession), "EnterPSHostProcessHostDoesNotSupportIASession", ErrorCategory.InvalidArgument, null)); return; } // Check selected process for existence, and whether it hosts PowerShell. Runspace namedPipeRunspace = null; switch (ParameterSetName) { case ProcessIdParameterSet: Process = GetProcessById(Id); VerifyProcess(Process); namedPipeRunspace = CreateNamedPipeRunspace(Process.Id, AppDomainName); break; case ProcessNameParameterSet: Process = GetProcessByName(Name); VerifyProcess(Process); namedPipeRunspace = CreateNamedPipeRunspace(Process.Id, AppDomainName); break; case PSHostProcessInfoParameterSet: Process = GetProcessByHostProcessInfo(HostProcessInfo); VerifyProcess(Process); // Create named pipe runspace for selected process and open. namedPipeRunspace = CreateNamedPipeRunspace(Process.Id, AppDomainName); break; case PipeNameParameterSet: VerifyPipeName(CustomPipeName); namedPipeRunspace = CreateNamedPipeRunspace(CustomPipeName); break; } // Set runspace prompt. The runspace is closed on pop so we don't // have to reverse this change. PrepareRunspace(namedPipeRunspace); try { // Push runspace onto host. _interactiveHost.PushRunspace(namedPipeRunspace); } catch (Exception e) { namedPipeRunspace.Close(); ThrowTerminatingError( new ErrorRecord( e, "EnterPSHostProcessCannotPushRunspace", ErrorCategory.InvalidOperation, this)); } }
private bool CheckPolicy(ExternalScriptInfo script, PSHost host, out Exception reason) { bool policyCheckPassed = false; reason = null; string path = script.Path; string reasonMessage; // path is assumed to be fully qualified here if (path.IndexOf(System.IO.Path.DirectorySeparatorChar) < 0) { throw PSTraceSource.NewArgumentException("path"); } if (path.LastIndexOf(System.IO.Path.DirectorySeparatorChar) == (path.Length - 1)) { throw PSTraceSource.NewArgumentException("path"); } FileInfo fi = new FileInfo(path); // Return false if the file does not exist, so that // we don't introduce a race condition if (!fi.Exists) { reason = new FileNotFoundException(path); return(false); } // Quick exit if we don't support the file type if (!IsSupportedExtension(fi.Extension)) { return(true); } // Get the execution policy _executionPolicy = SecuritySupport.GetExecutionPolicy(_shellId); // See if they want to bypass the authorization manager if (_executionPolicy == ExecutionPolicy.Bypass) { return(true); } // Always check the SAFER APIs if code integrity isn't being handled system-wide through // WLDP or AppLocker. In those cases, the scripts will be run in ConstrainedLanguage. // Otherwise, block. // SAFER APIs are not on CSS or OneCore if (SystemPolicy.GetSystemLockdownPolicy() != SystemEnforcementMode.Enforce) { SaferPolicy saferPolicy = SaferPolicy.Disallowed; int saferAttempt = 0; bool gotSaferPolicy = false; // We need to put in a retry workaround, as the SAFER APIs fail when under stress. while ((!gotSaferPolicy) && (saferAttempt < 5)) { try { saferPolicy = SecuritySupport.GetSaferPolicy(path, null); gotSaferPolicy = true; } catch (System.ComponentModel.Win32Exception) { if (saferAttempt > 4) { throw; } saferAttempt++; System.Threading.Thread.Sleep(100); } } // If the script is disallowed via AppLocker, block the file // unless the system-wide lockdown policy is "Enforce" (where all PowerShell // scripts are in blocked). If the system policy is "Enforce", then the // script will be allowed (but ConstrainedLanguage will be applied). if (saferPolicy == SaferPolicy.Disallowed) { reasonMessage = StringUtil.Format(Authenticode.Reason_DisallowedBySafer, path); reason = new UnauthorizedAccessException(reasonMessage); return(false); } } if (_executionPolicy == ExecutionPolicy.Unrestricted) { // Product binaries are always trusted // This avoids signature and security zone checks if (SecuritySupport.IsProductBinary(path)) { return(true); } // We need to give the "Remote File" warning // if the file originated from the internet if (!IsLocalFile(fi.FullName)) { // Get the signature of the file. if (String.IsNullOrEmpty(script.ScriptContents)) { reasonMessage = StringUtil.Format(Authenticode.Reason_FileContentUnavailable, path); reason = new UnauthorizedAccessException(reasonMessage); return(false); } Signature signature = GetSignatureWithEncodingRetry(path, script); // The file is signed, with a publisher that // we trust if (signature.Status == SignatureStatus.Valid) { // The file is signed by a trusted publisher if (IsTrustedPublisher(signature, path)) { policyCheckPassed = true; } } // We don't care about the signature. If you distrust them, // or the signature does not exist, we prompt you only // because it's remote. if (!policyCheckPassed) { RunPromptDecision decision = RunPromptDecision.DoNotRun; // Get their remote prompt answer, allowing them to // enter nested prompts, if wanted. do { decision = RemoteFilePrompt(path, host); if (decision == RunPromptDecision.Suspend) { host.EnterNestedPrompt(); } } while (decision == RunPromptDecision.Suspend); switch (decision) { case RunPromptDecision.RunOnce: policyCheckPassed = true; break; case RunPromptDecision.DoNotRun: default: policyCheckPassed = false; reasonMessage = StringUtil.Format(Authenticode.Reason_DoNotRun, path); reason = new UnauthorizedAccessException(reasonMessage); break; } } } else { policyCheckPassed = true; } } // Don't need to check the signature if the file is local // and we're in "RemoteSigned" mode else if ((IsLocalFile(fi.FullName)) && (_executionPolicy == ExecutionPolicy.RemoteSigned)) { policyCheckPassed = true; } else if ((_executionPolicy == ExecutionPolicy.AllSigned) || (_executionPolicy == ExecutionPolicy.RemoteSigned)) { // if policy requires signature verification, // make it so. // Get the signature of the file. if (String.IsNullOrEmpty(script.ScriptContents)) { reasonMessage = StringUtil.Format(Authenticode.Reason_FileContentUnavailable, path); reason = new UnauthorizedAccessException(reasonMessage); return(false); } Signature signature = GetSignatureWithEncodingRetry(path, script); // The file is signed. if (signature.Status == SignatureStatus.Valid) { // The file is signed by a trusted publisher if (IsTrustedPublisher(signature, path)) { policyCheckPassed = true; } // The file is signed by an unknown publisher, // So prompt. else { policyCheckPassed = SetPolicyFromAuthenticodePrompt(path, host, ref reason, signature); } } // The file is UnknownError, NotSigned, HashMismatch, // NotTrusted, NotSupportedFileFormat else { policyCheckPassed = false; if (signature.Status == SignatureStatus.NotTrusted) { reason = new UnauthorizedAccessException( StringUtil.Format(Authenticode.Reason_NotTrusted, path, signature.SignerCertificate.SubjectName.Name)); } else { reason = new UnauthorizedAccessException( StringUtil.Format(Authenticode.Reason_Unknown, path, signature.StatusMessage)); } } } else // if(executionPolicy == ExecutionPolicy.Restricted) { // Deny everything policyCheckPassed = false; // But accept mshxml files from publishers that we // trust, or files in the system protected directories bool reasonSet = false; if (String.Equals(fi.Extension, ".ps1xml", StringComparison.OrdinalIgnoreCase)) { string[] trustedDirectories = new string[] { Platform.GetFolderPath(Environment.SpecialFolder.System), Platform.GetFolderPath(Environment.SpecialFolder.ProgramFiles) }; foreach (string trustedDirectory in trustedDirectories) { if (fi.FullName.StartsWith(trustedDirectory, StringComparison.OrdinalIgnoreCase)) { policyCheckPassed = true; } } if (!policyCheckPassed) { // Get the signature of the file. Signature signature = GetSignatureWithEncodingRetry(path, script); // The file is signed by a trusted publisher if (signature.Status == SignatureStatus.Valid) { if (IsTrustedPublisher(signature, path)) { policyCheckPassed = true; } // The file is signed by an unknown publisher, // So prompt. else { policyCheckPassed = SetPolicyFromAuthenticodePrompt(path, host, ref reason, signature); reasonSet = true; } } } } if (!policyCheckPassed && !reasonSet) { reason = new UnauthorizedAccessException( StringUtil.Format(Authenticode.Reason_RestrictedMode, path)); } } return(policyCheckPassed); }