Example #1
0
        private void CheckSessionOverBudget()
        {
            OverBudgetException exception;

            if (WSManBudgetManager.Instance.CheckOverBudget(this.currentAuthZUserToken, CostType.ActiveRunspace, out exception))
            {
                LocalizedString message = AuthZPluginHelper.HandleUserOverBudgetException(exception, this.currentAuthZUserToken);
                throw new AuthorizationException(message);
            }
            if (this.currentAuthZUserToken.OrgId != null && WSManTenantBudgetManager.Instance.CheckOverBudget(this.currentAuthZUserToken, CostType.ActiveRunspace, out exception))
            {
                LocalizedString message2 = AuthZPluginHelper.HandleTenantOverBudgetException(exception, this.currentAuthZUserToken);
                throw new AuthorizationException(message2);
            }
            if (AppSettings.Current.MaxPowershellAppPoolConnections > 0 && WSManBudgetManager.Instance.TotalActiveRunspaces >= AppSettings.Current.MaxPowershellAppPoolConnections)
            {
                string windowsLiveId = this.currentAuthZUserToken.WindowsLiveId;
                if (!string.IsNullOrEmpty(windowsLiveId))
                {
                    FailFastUserCache.Instance.AddUserToCache(windowsLiveId, BlockedType.NewSession, TimeSpan.Zero);
                }
                AuthZLogger.SafeAppendColumn(RpsCommonMetadata.ContributeToFailFast, "AuthZ-Machine", LoggerHelper.GetContributeToFailFastValue("AllUsers", "-1", "NewSesion", -1.0));
                FailFastUserCache.Instance.AddAllUsersToCache(BlockedType.NewSession, TimeSpan.Zero);
                LocalizedString localizedString = Strings.ErrorMaxConnectionLimit(AppSettings.Current.VDirName);
                ExTraceGlobals.RunspaceConfigTracer.TraceError(0L, localizedString);
                TaskLogger.LogRbacEvent(TaskEventLogConstants.Tuple_ReachedMaxPSConnectionLimit, null, new object[]
                {
                    AppSettings.Current.VDirName,
                    AppSettings.Current.MaxPowershellAppPoolConnections
                });
                throw new AuthorizationException(localizedString);
            }
        }
Example #2
0
        private static void RemoveCmdletParams(RoleEntryInfo entry, IList <string> paramList, IList <RoleEntryInfo> cmdletTobeRemoved, IList <RoleEntryInfo> cmdletTobeAdded, bool fNewCmdlet)
        {
            if (paramList == null || paramList.Count == 0)
            {
                return;
            }
            if (cmdletTobeRemoved == null)
            {
                return;
            }
            if (cmdletTobeAdded == null)
            {
                return;
            }
            cmdletTobeRemoved.Add(entry);
            IEnumerable <string> source = entry.RoleEntry.Parameters.Except(paramList);
            RoleEntryInfo        roleEntryInfo;

            if (entry.RoleAssignment == null)
            {
                roleEntryInfo = new RoleEntryInfo(entry.RoleEntry.Clone(source.ToList <string>()));
            }
            else
            {
                roleEntryInfo = new RoleEntryInfo(entry.RoleEntry.Clone(source.ToList <string>()), entry.RoleAssignment);
            }
            roleEntryInfo.ScopeSet = entry.ScopeSet;
            cmdletTobeAdded.Add(roleEntryInfo);
            if (fNewCmdlet)
            {
                AuthZLogger.SafeAppendColumn(RpsAuthZMetadata.CmdletFlightDisabled, entry.RoleEntry.Name, string.Join(" ", paramList));
            }
        }
Example #3
0
 private static void RemoveCmdlet(RoleEntryInfo entry, IList <RoleEntryInfo> cmdletTobeRemoved, bool fNewCmdlet)
 {
     cmdletTobeRemoved.Add(entry);
     if (fNewCmdlet)
     {
         AuthZLogger.SafeAppendColumn(RpsAuthZMetadata.CmdletFlightDisabled, entry.RoleEntry.Name, "*");
     }
 }
        // Token: 0x060012F3 RID: 4851 RVA: 0x0003DE30 File Offset: 0x0003C030
        internal static LocalizedString HandleTenantOverBudgetException(OverBudgetException exception, AuthZPluginUserToken userToken)
        {
            string policyPart    = exception.PolicyPart;
            string orgIdInString = userToken.OrgIdInString;
            string userName      = userToken.UserName;
            string windowsLiveId = userToken.WindowsLiveId;

            ExTraceGlobals.PublicPluginAPITracer.TraceError <string, string, string>(0L, "Get Tenant OverBudgetException for user {0}, Organization {1}. Message: {2}", userName, orgIdInString, exception.ToString());
            AuthZLogger.SafeAppendGenericError("Tenant_OverBudgetException", exception.ToString(), false);
            TimeSpan blockedTime = TimeSpan.FromMilliseconds((double)exception.BackoffTime);

            if (windowsLiveId != null)
            {
                FailFastUserCache.Instance.AddUserToCache(windowsLiveId, BlockedType.NewSession, blockedTime);
                AuthZLogger.SafeAppendColumn(RpsCommonMetadata.ContributeToFailFast, "AuthZ-UserOrg", LoggerHelper.GetContributeToFailFastValue("User", windowsLiveId, "NewSession", blockedTime.TotalMilliseconds));
            }
            if (!string.IsNullOrEmpty(orgIdInString))
            {
                FailFastUserCache.Instance.AddTenantToCache(orgIdInString, BlockedType.NewSession, blockedTime);
                AuthZLogger.SafeAppendColumn(RpsCommonMetadata.ContributeToFailFast, "AuthZ-Org", LoggerHelper.GetContributeToFailFastValue("Tenant", orgIdInString, "NewSession", blockedTime.TotalMilliseconds));
                foreach (string text in userToken.DomainsToBlockTogether)
                {
                    FailFastUserCache.Instance.AddTenantToCache(text, BlockedType.NewSession, blockedTime);
                    AuthZLogger.SafeAppendColumn(RpsCommonMetadata.ContributeToFailFast, "AuthZ-AcceptedDomain-" + text, LoggerHelper.GetContributeToFailFastValue("Tenant", text, "NewSession", blockedTime.TotalMilliseconds));
                }
            }
            IThrottlingPolicy throttlingPolicy = userToken.GetThrottlingPolicy();
            LocalizedString   value;

            if (policyPart == "MaxTenantConcurrency")
            {
                value = Strings.ErrorMaxTenantPSConnectionLimit(orgIdInString);
                TaskLogger.LogRbacEvent(TaskEventLogConstants.Tuple_ReachedMaxTenantPSConnectionLimit, null, new object[]
                {
                    userName,
                    orgIdInString,
                    throttlingPolicy.PowerShellMaxTenantConcurrency
                });
            }
            else
            {
                if (!(policyPart == "MaxTenantRunspaces"))
                {
                    throw new NotSupportedException(string.Format("DEV bug. The exception policy part {0} is not expected.", policyPart));
                }
                value = Strings.ErrorTenantMaxRunspacesTarpitting(orgIdInString, exception.BackoffTime / 1000);
                TaskLogger.LogRbacEvent(TaskEventLogConstants.Tuple_ReachedMaxTenantPSRunspaceInTimePeriodLimit, null, new object[]
                {
                    userName,
                    orgIdInString,
                    throttlingPolicy.PowerShellMaxTenantRunspaces,
                    throttlingPolicy.PowerShellMaxRunspacesTimePeriod,
                    exception.BackoffTime
                });
            }
            return(new LocalizedString(value + string.Format("{2}Policy: {0}; {2}Snapshot: {1}", exception.ThrottlingPolicyDN, exception.Snapshot, Environment.NewLine)));
        }
 // Token: 0x060012F4 RID: 4852 RVA: 0x0003E08C File Offset: 0x0003C28C
 internal static void TriggerFailFastForAuthZFailure(string windowsLiveId)
 {
     if (string.IsNullOrEmpty(windowsLiveId))
     {
         return;
     }
     FailFastUserCache.Instance.AddUserToCache(windowsLiveId, BlockedType.NewSession, TimeSpan.Zero);
     AuthZLogger.SafeAppendColumn(RpsCommonMetadata.ContributeToFailFast, "AuthZ-UserSelf", LoggerHelper.GetContributeToFailFastValue("User", windowsLiveId, "NewSession", -1.0));
 }
        // Token: 0x060012F2 RID: 4850 RVA: 0x0003DC08 File Offset: 0x0003BE08
        internal static LocalizedString HandleUserOverBudgetException(OverBudgetException exception, AuthZPluginUserToken userToken)
        {
            string policyPart    = exception.PolicyPart;
            string userName      = userToken.UserName;
            string windowsLiveId = userToken.WindowsLiveId;

            ExTraceGlobals.PublicPluginAPITracer.TraceError <string, string>(0L, "Get User OverBudgetException for user {0}. Message: {1}", userName, exception.ToString());
            AuthZLogger.SafeAppendGenericError("User_OverBudgetException", exception.ToString(), false);
            if (!string.IsNullOrEmpty(windowsLiveId))
            {
                BlockedType blockedType = (policyPart == "PowerShellMaxCmdlets") ? BlockedType.NewRequest : BlockedType.NewSession;
                FailFastUserCache.Instance.AddUserToCache(userToken.WindowsLiveId, blockedType, TimeSpan.Zero);
                AuthZLogger.SafeAppendColumn(RpsCommonMetadata.ContributeToFailFast, "AuthZ-UserSelf", LoggerHelper.GetContributeToFailFastValue("User", userToken.WindowsLiveId, blockedType.ToString(), -1.0));
            }
            IThrottlingPolicy throttlingPolicy = userToken.GetThrottlingPolicy();
            LocalizedString   value;

            if (policyPart == "MaxConcurrency")
            {
                value = Strings.ErrorMaxRunspacesLimit(throttlingPolicy.PowerShellMaxConcurrency.ToString(), policyPart);
                TaskLogger.LogRbacEvent(TaskEventLogConstants.Tuple_ReachedMaxUserPSConnectionLimit, null, new object[]
                {
                    userName,
                    throttlingPolicy.PowerShellMaxConcurrency
                });
            }
            else if (policyPart == "MaxRunspacesTimePeriod")
            {
                value = Strings.ErrorMaxRunspacesTarpitting(exception.BackoffTime / 1000);
                TaskLogger.LogRbacEvent(TaskEventLogConstants.Tuple_ReachedMaxPSRunspaceInTimePeriodLimit, null, new object[]
                {
                    userName,
                    throttlingPolicy.PowerShellMaxRunspaces,
                    throttlingPolicy.PowerShellMaxRunspacesTimePeriod,
                    exception.BackoffTime
                });
            }
            else
            {
                if (!(policyPart == "PowerShellMaxCmdlets"))
                {
                    throw new NotSupportedException(string.Format("DEV bug. The exception policy part {0} is not expected.", policyPart));
                }
                value = Strings.ErrorOperationTarpitting(exception.BackoffTime / 1000);
                TaskLogger.LogRbacEvent(TaskEventLogConstants.Tuple_ReachedMaxPowershellCmdletLimit, null, new object[]
                {
                    userName,
                    throttlingPolicy.PowerShellMaxCmdlets,
                    throttlingPolicy.PowerShellMaxCmdletsTimePeriod,
                    exception.BackoffTime
                });
            }
            return(new LocalizedString(value + string.Format("{2}Policy: {0}; {2}Snapshot: {1}", exception.ThrottlingPolicyDN, exception.Snapshot, Environment.NewLine)));
        }
Example #7
0
        internal static VariantConfigurationSnapshot GetSnapshot(ADRawEntry executingUser, IEnumerable <KeyValuePair <string, string> > additionalConstraints)
        {
            if (executingUser == null)
            {
                return(null);
            }
            VariantConfigurationSnapshot variantConfigurationSnapshot = null;
            MiniRecipient miniRecipient = new MiniRecipient();

            try
            {
                try
                {
                    miniRecipient[MiniRecipientSchema.UserPrincipalName]         = executingUser[ADUserSchema.UserPrincipalName];
                    miniRecipient[ADObjectSchema.OrganizationId]                 = executingUser[ADObjectSchema.OrganizationId];
                    miniRecipient[MiniRecipientSchema.ExternalDirectoryObjectId] = executingUser[ADRecipientSchema.ExternalDirectoryObjectId];
                    miniRecipient[MiniRecipientSchema.Languages]                 = executingUser[ADOrgPersonSchema.Languages];
                }
                catch (DataValidationException ex)
                {
                    AuthZLogger.SafeAppendColumn(RpsAuthZMetadata.VariantConfigurationSnapshot, "DataValidationException", ex.Message);
                }
                ConstraintCollection constraintCollection = null;
                if (additionalConstraints != null)
                {
                    constraintCollection = ConstraintCollection.CreateEmpty();
                    foreach (KeyValuePair <string, string> keyValuePair in additionalConstraints)
                    {
                        constraintCollection.Add(keyValuePair.Key, keyValuePair.Value);
                    }
                }
                variantConfigurationSnapshot = VariantConfiguration.GetSnapshot(miniRecipient.GetContext(null), constraintCollection, null);
                AuthZLogger.SafeAppendColumn(RpsAuthZMetadata.VariantConfigurationSnapshot, "Flights", string.Join(" ", variantConfigurationSnapshot.Flights));
            }
            catch (Exception ex2)
            {
                AuthZLogger.SafeAppendGenericError("VariantConfigurationSnapshot.Exception", ex2.Message, false);
            }
            finally
            {
                AuthZLogger.SafeAppendColumn(RpsAuthZMetadata.VariantConfigurationSnapshot, "User", executingUser[ADUserSchema.UserPrincipalName].ToString());
                AuthZLogger.SafeAppendColumn(RpsAuthZMetadata.VariantConfigurationSnapshot, "Org", executingUser[ADObjectSchema.OrganizationId].ToString());
            }
            return(variantConfigurationSnapshot);
        }
Example #8
0
        private static void BuildParamFlightingList(RoleEntryInfo entry, ICmdletSettings cmdletSettings, ref IList <string> paramFlightingList)
        {
            IEnumerable <string> enumerable = cmdletSettings.Params0.Union(cmdletSettings.Params1);

            enumerable = enumerable.Union(cmdletSettings.Params2);
            enumerable = enumerable.Union(cmdletSettings.Params3);
            enumerable = enumerable.Union(cmdletSettings.Params4);
            enumerable = enumerable.Union(cmdletSettings.Params5);
            enumerable = enumerable.Union(cmdletSettings.Params6);
            enumerable = enumerable.Union(cmdletSettings.Params7);
            enumerable = enumerable.Union(cmdletSettings.Params8);
            enumerable = enumerable.Union(cmdletSettings.Params9);
            if (enumerable != null)
            {
                paramFlightingList = enumerable.ToList <string>();
                AuthZLogger.SafeAppendColumn(RpsAuthZMetadata.CmdletFlightEnabled, entry.RoleEntry.Name, string.Join(" ", paramFlightingList));
            }
        }
Example #9
0
 // Token: 0x060012E1 RID: 4833 RVA: 0x0003D75C File Offset: 0x0003B95C
 internal static void EndLogging(bool shouldCommit)
 {
     Microsoft.Exchange.Diagnostics.Components.Configuration.Core.ExTraceGlobals.InstrumentationTracer.TraceDebug(0L, "[AuthZLogHelper.EndLogging] End logging.");
     try
     {
         if (AuthZLogHelper.latencyTracker != null)
         {
             long num = Diagnostics.ExecuteAndLog <long>("AuthZLogHelper.StopLatencyTracker", false, null, Constants.CoreEventLogger, Microsoft.Exchange.Configuration.Core.EventLog.TaskEventLogConstants.Tuple_NonCrashingException, Microsoft.Exchange.Diagnostics.Components.Configuration.Core.ExTraceGlobals.InstrumentationTracer, null, delegate(Exception ex)
             {
                 AuthZLogHelper.LogException(ex, "AuthZLogHelper.StopLatencyTracker", false);
             }, -1L, new Func <long>(AuthZLogHelper.StopLatencyTracker));
             AuthZLogger.SafeSetLogger(ConfigurationCoreMetadata.TotalTime, num);
             AuthZLogHelper.latencyTracker.PushLatencyDetailsToLog(AuthZLogHelper.funcNameToLogMetadataDic, new Action <Enum, double>(AuthZLogger.UpdateLatency), delegate(string funcName, string totalLatency)
             {
                 AuthZLogger.SafeAppendColumn(RpsCommonMetadata.GenericLatency, funcName, totalLatency);
             });
         }
         else
         {
             AuthZLogger.SafeAppendColumn(RpsCommonMetadata.GenericLatency, "LatencyMissed", "AuthZLogHelper.latencyTracker is null");
         }
     }
     finally
     {
         try
         {
             if (shouldCommit)
             {
                 AuthZLogger.AsyncCommit(true);
             }
         }
         finally
         {
             AuthZLogHelper.latencyTracker = null;
         }
     }
 }
Example #10
0
        // Token: 0x060012DD RID: 4829 RVA: 0x0003D4C8 File Offset: 0x0003B6C8
        internal static T ExecuteWSManPluginAPI <T>(string funcName, bool throwException, bool trackLatency, T defaultReturnValue, Func <T> func)
        {
            ExWatson.IsExceptionInteresting isExceptionInteresting = null;
            T result;

            try
            {
                AuthZLogger.SafeAppendColumn(RpsCommonMetadata.GenericLatency, funcName, DateTime.UtcNow.ToString());
                string                funcName2       = funcName;
                bool                  throwException2 = throwException;
                LatencyTracker        latencyTracker  = trackLatency ? AuthZLogHelper.latencyTracker : null;
                ExEventLog            rbacEventLogger = AuthZLogHelper.RbacEventLogger;
                ExEventLog.EventTuple tuple_RemotePSPublicAPIFailed = Microsoft.Exchange.Configuration.ObjectModel.EventLog.TaskEventLogConstants.Tuple_RemotePSPublicAPIFailed;
                Trace                 publicPluginAPITracer         = Microsoft.Exchange.Diagnostics.Components.Authorization.ExTraceGlobals.PublicPluginAPITracer;
                if (isExceptionInteresting == null)
                {
                    isExceptionInteresting = ((object ex) => AuthZPluginHelper.IsFatalException(ex as Exception));
                }
                result = Diagnostics.ExecuteAndLog <T>(funcName2, throwException2, latencyTracker, rbacEventLogger, tuple_RemotePSPublicAPIFailed, publicPluginAPITracer, isExceptionInteresting, delegate(Exception ex)
                {
                    AuthZLogHelper.LogException(ex, funcName, throwException);
                }, defaultReturnValue, () => AuthZLogHelper.HandleExceptionAndRetry <T>(funcName, func, throwException, defaultReturnValue));
            }
            catch (Exception ex)
            {
                string arg = (AuthZLogger.ActivityScope != null) ? AuthZLogger.ActivityScope.ActivityId.ToString() : null;
                AuthZLogHelper.EndLogging(true);
                Exception              ex3;
                string                 str     = string.Format("[FailureCategory={0}] ", FailureCategory.AuthZ + "-" + ex3.GetType().Name);
                string                 str2    = string.Format("[AuthZRequestId={0}]", arg);
                LocalizedString        message = new LocalizedString(str2 + str + ex3.Message);
                AuthorizationException ex2     = new AuthorizationException(message, ex3);
                throw ex2;
            }
            return(result);
        }
Example #11
0
 // Token: 0x060012DF RID: 4831 RVA: 0x0003D670 File Offset: 0x0003B870
 internal static bool StartLogging(string funcName, out bool latencyTrackerStartedByMe)
 {
     AuthZLogger.SafeAppendColumn(RpsCommonMetadata.GenericLatency, funcName, DateTime.UtcNow.ToString());
     latencyTrackerStartedByMe = false;
     if (AuthZLogHelper.latencyTracker == null)
     {
         Diagnostics.ExecuteAndLog("AuthZLogHelper.StartLatencyTracker", false, null, Constants.CoreEventLogger, Microsoft.Exchange.Configuration.Core.EventLog.TaskEventLogConstants.Tuple_NonCrashingException, Microsoft.Exchange.Diagnostics.Components.Configuration.Core.ExTraceGlobals.InstrumentationTracer, null, delegate(Exception ex)
         {
             AuthZLogHelper.LogException(ex, "AuthZLogHelper.StartLatencyTracker", false);
         }, delegate()
         {
             AuthZLogHelper.StartLatencyTracker(funcName);
         });
         latencyTrackerStartedByMe = (AuthZLogHelper.latencyTracker != null);
     }
     if (AuthZLogger.LoggerNotDisposed)
     {
         return(false);
     }
     InitializeLoggerSettingsHelper.InitLoggerSettings();
     AuthZLogger.InitializeRequestLogger();
     AuthZLogger.SafeSetLogger(RpsAuthZMetadata.Function, funcName);
     return(true);
 }
Example #12
0
        internal static void FilterCmdletsAndParams(VariantConfigurationSnapshot configurationSnapshot, List <RoleEntryInfo> cmdletList)
        {
            if (configurationSnapshot == null)
            {
                return;
            }
            IDictionary <string, ICmdletSettings> dictionary = null;

            try
            {
                dictionary = configurationSnapshot.GetObjectsOfType <ICmdletSettings>("CmdletInfra.settings.ini");
            }
            catch (KeyNotFoundException ex)
            {
                AuthZLogger.SafeAppendGenericError("VanriantConfigurationSnapshot.KeyNotFoundException", ex.Message, false);
            }
            if (dictionary == null || dictionary.Count == 0)
            {
                return;
            }
            List <RoleEntryInfo> cmdletTobeAdded   = new List <RoleEntryInfo>();
            List <RoleEntryInfo> cmdletTobeRemoved = new List <RoleEntryInfo>();
            string          value          = "";
            ICmdletSettings cmdletSettings = null;
            IList <string>  list           = null;

            foreach (RoleEntryInfo roleEntryInfo in cmdletList)
            {
                if (dictionary.TryGetValue(roleEntryInfo.RoleEntry.Name, out cmdletSettings))
                {
                    bool flag = !roleEntryInfo.RoleEntry.Name.Equals(value, StringComparison.OrdinalIgnoreCase);
                    if (flag)
                    {
                        value = roleEntryInfo.RoleEntry.Name;
                    }
                    IList <string> list2 = cmdletSettings.AllFlightingParams;
                    if (!cmdletSettings.Enabled)
                    {
                        CmdletFlight.RemoveCmdlet(roleEntryInfo, cmdletTobeRemoved, flag);
                    }
                    else if (list2 != null && list2.Count > 0)
                    {
                        if (flag)
                        {
                            CmdletFlight.BuildParamFlightingList(roleEntryInfo, cmdletSettings, ref list);
                        }
                        if (list != null)
                        {
                            IEnumerable <string> source = list2.Except(list);
                            list2 = source.ToList <string>();
                        }
                        CmdletFlight.RemoveCmdletParams(roleEntryInfo, list2, cmdletTobeRemoved, cmdletTobeAdded, flag);
                    }
                    else if (flag)
                    {
                        AuthZLogger.SafeAppendColumn(RpsAuthZMetadata.CmdletFlightEnabled, roleEntryInfo.RoleEntry.Name, "*");
                    }
                }
            }
            CmdletFlight.CommitChanges(cmdletList, cmdletTobeRemoved, cmdletTobeAdded);
        }