예제 #1
0
 internal void HeartBeat(AuthZPluginUserToken userToken)
 {
     lock (this.instanceLock)
     {
         this.HeartBeatImpl(userToken);
     }
 }
        // Token: 0x060012B2 RID: 4786 RVA: 0x0003C778 File Offset: 0x0003A978
        internal void StartRunspace(AuthZPluginUserToken userToken)
        {
            string runspaceCacheKey = this.GetRunspaceCacheKey(userToken);

            if (string.IsNullOrEmpty(runspaceCacheKey))
            {
                AuthZLogger.SafeAppendGenericError("NullOrEmptyRunspaceCacheKey", "User token have an empty ExecutingUserName", false);
                return;
            }
            lock (base.InstanceLock)
            {
                RunspaceCacheValue runspaceCacheValue;
                if (this.runspaceCache.TryGetValue(runspaceCacheKey, out runspaceCacheValue))
                {
                    ExTraceGlobals.PublicPluginAPITracer.TraceDebug <string>((long)this.GetHashCode(), "[PswsBudgetManager.StartRunspace] item {0} is removed explicitly", runspaceCacheKey);
                    if (runspaceCacheValue != null && runspaceCacheValue.CostHandle != null)
                    {
                        runspaceCacheValue.CostHandle.Dispose();
                    }
                    this.runspaceCache.Remove(runspaceCacheKey);
                }
                CostHandle         costHandle = this.StartRunspaceImpl(userToken);
                RunspaceCacheValue value2     = new RunspaceCacheValue
                {
                    CostHandle = costHandle,
                    UserToken  = (PswsAuthZUserToken)userToken
                };
                ExTraceGlobals.PublicPluginAPITracer.TraceDebug <string, TimeSpan>((long)this.GetHashCode(), "[PswsBudgetManager.StartRunspace] Add value {0} to runspace cache. Expired time = {1}.", runspaceCacheKey, this.pswsRunspaceCacheTimeout);
                this.runspaceCache.InsertAbsolute(runspaceCacheKey, value2, this.pswsRunspaceCacheTimeout, new RemoveItemDelegate <string, RunspaceCacheValue>(this.OnRunspaceCacheItemExpired));
            }
            ExTraceGlobals.PublicPluginAPITracer.TraceDebug <string>((long)this.GetHashCode(), "[PswsBudgetManager.StartRunspace] Add/Update value {0} to connectedUser cache.", runspaceCacheKey);
            this.connectedUsers.AddOrUpdate(runspaceCacheKey, ExDateTime.Now, (string key, ExDateTime value) => ExDateTime.Now);
            AuthZPluginHelper.UpdateAuthZPluginPerfCounters(this);
        }
예제 #3
0
 internal void RemoveBudgetIfNoActiveRunspace(AuthZPluginUserToken userToken)
 {
     lock (this.instanceLock)
     {
         IPowerShellBudget budget = this.GetBudget(userToken, false, false);
         if (budget != null && budget.TotalActiveRunspacesCount <= 0)
         {
             string           text = this.CreateKey(userToken);
             Unlimited <uint> powerShellMaxRunspacesTimePeriod = budget.ThrottlingPolicy.PowerShellMaxRunspacesTimePeriod;
             if (powerShellMaxRunspacesTimePeriod.IsUnlimited)
             {
                 ExTraceGlobals.PublicPluginAPITracer.TraceDebug <string>(0L, "Key {0} is removed from budgets dictionary immediately.", text);
                 this.budgets.Remove(text);
                 this.keyToRemoveBudgets.Remove(text);
             }
             else
             {
                 int num = (int)(powerShellMaxRunspacesTimePeriod.Value + 5U);
                 ExTraceGlobals.PublicPluginAPITracer.TraceDebug <string, int>(0L, "Register key {0} to keyToRemoveBudgets, timeout {1} seconds.", text, num);
                 this.keyToRemoveBudgets.InsertAbsolute(text, BudgetManager.NormalCleanupCacheValue, TimeSpan.FromSeconds((double)num), new RemoveItemDelegate <string, string>(this.OnKeyToRemoveBudgetsCacheValueRemoved));
             }
         }
     }
     this.UpdateBudgetsPerfCounter(this.budgets.Count);
     this.UpdateKeyToRemoveBudgetsPerfCounter(this.keyToRemoveBudgets.Count);
 }
예제 #4
0
        protected IPowerShellBudget GetBudget(AuthZPluginUserToken userToken, bool createIfNotExist, bool isHeartBeat)
        {
            string text = this.CreateKey(userToken);

            if (text == null)
            {
                return(null);
            }
            IPowerShellBudget powerShellBudget;

            if (!this.budgets.TryGetValue(text, out powerShellBudget) && createIfNotExist)
            {
                powerShellBudget = this.CreateBudget(userToken);
                if (powerShellBudget != null)
                {
                    ExTraceGlobals.PublicPluginAPITracer.TraceDebug <string>(0L, "Budget of key {0} is added to budgets.", text);
                    this.budgets.Add(text, powerShellBudget);
                    this.UpdateBudgetsPerfCounter(this.budgets.Count);
                }
            }
            if (powerShellBudget != null && isHeartBeat)
            {
                this.keyToRemoveBudgets.InsertAbsolute(text, this.CreateRelatedBudgetKey(userToken), this.BudgetTimeout, new RemoveItemDelegate <string, string>(this.OnKeyToRemoveBudgetsCacheValueRemoved));
            }
            return(powerShellBudget);
        }
        // Token: 0x06001274 RID: 4724 RVA: 0x0003B65C File Offset: 0x0003985C
        internal static PswsAuthZUserToken GetAuthZPluginUserToken(UserToken userToken)
        {
            ExAssert.RetailAssert(userToken != null, "[PswsAuthorization.GetAuthZPluginUserToken] userToken can't be null.");
            Microsoft.Exchange.Configuration.Core.AuthenticationType authenticationType = userToken.AuthenticationType;
            SecurityIdentifier userSid            = userToken.UserSid;
            DelegatedPrincipal delegatedPrincipal = userToken.DelegatedPrincipal;

            ExAssert.RetailAssert(userSid != null, "The user sid is invalid (null).");
            PartitionId partitionId = userToken.PartitionId;
            string      text        = AuthenticatedUserCache.CreateKeyForPsws(userSid, userToken.AuthenticationType, partitionId);

            ExTraceGlobals.PublicPluginAPITracer.TraceDebug <string>(0L, "[PswsAuthZHelper.GetAuthZPluginUserToken] User cache key = \"{0}\".", text);
            AuthZPluginUserToken authZPluginUserToken;

            if (!AuthenticatedUserCache.Instance.TryGetValue(text, out authZPluginUserToken))
            {
                ExTraceGlobals.PublicPluginAPITracer.TraceDebug(0L, "[PswsAuthZHelper.GetAuthZPluginUserToken] User not found in cache.");
                IIdentity          identity           = HttpContext.Current.Items["X-Psws-CurrentLogonUser"] as IIdentity;
                SerializedIdentity serializedIdentity = null;
                if (identity is WindowsTokenIdentity)
                {
                    serializedIdentity = ((WindowsTokenIdentity)identity).ToSerializedIdentity();
                }
                ADRawEntry adrawEntry = ExchangeAuthorizationPlugin.FindUserEntry(userSid, null, serializedIdentity, partitionId);
                ExAssert.RetailAssert(adrawEntry != null, "UnAuthorized. Unable to find the user.");
                bool condition = (adrawEntry is MiniRecipient || adrawEntry is ADUser) && (bool)adrawEntry[ADRecipientSchema.RemotePowerShellEnabled];
                ExAssert.RetailAssert(condition, "UnAuthorized. PSWS not enabled user.");
                authZPluginUserToken = new AuthZPluginUserToken(delegatedPrincipal, adrawEntry, authenticationType, userSid.Value);
                AuthenticatedUserCache.Instance.AddUserToCache(text, authZPluginUserToken);
            }
            return(new PswsAuthZUserToken(authZPluginUserToken.DelegatedPrincipal, authZPluginUserToken.UserEntry, authenticationType, authZPluginUserToken.DefaultUserName, userToken.UserName));
        }
예제 #6
0
        protected virtual CostHandle StartRunspaceImpl(AuthZPluginUserToken userToken)
        {
            IPowerShellBudget budget = this.GetBudget(userToken, true, true);

            if (budget != null)
            {
                ExTraceGlobals.PublicPluginAPITracer.TraceDebug <string>(0L, "Start budget tracking for ActiveRunspaces, key {0}", this.CreateKey(userToken));
                return(budget.StartActiveRunspace());
            }
            ExTraceGlobals.PublicPluginAPITracer.TraceError <string>(0L, "Try to start budget tracking for ActiveRunspaces, key {0} But the budget doesn't exist.", this.CreateKey(userToken));
            return(null);
        }
        // Token: 0x06001492 RID: 5266 RVA: 0x0004CD10 File Offset: 0x0004AF10
        internal CostHandle StartRunspace(AuthZPluginUserToken userToken)
        {
            if (!this.ShouldThrottling(userToken))
            {
                return(null);
            }
            CostHandle result;

            lock (base.InstanceLock)
            {
                result = this.StartRunspaceImpl(userToken);
            }
            return(result);
        }
예제 #8
0
 // Token: 0x060012E7 RID: 4839 RVA: 0x0003D8FC File Offset: 0x0003BAFC
 internal static void LogAuthZUserToken(AuthZPluginUserToken userToken)
 {
     if (userToken == null)
     {
         AuthZLogger.SafeSetLogger(RpsAuthZMetadata.IsAuthorized, false);
         return;
     }
     AuthZLogger.SafeSetLogger(RpsAuthZMetadata.IsAuthorized, true);
     AuthZLogger.SafeSetLogger(ServiceCommonMetadata.AuthenticatedUser, userToken.UserNameForLogging);
     AuthZLogger.SafeSetLogger(ActivityStandardMetadata.AuthenticationType, userToken.AuthenticationType);
     AuthZLogger.SafeSetLogger(ActivityStandardMetadata.TenantId, userToken.OrgIdInString);
     if (userToken.DelegatedPrincipal != null)
     {
         AuthZLogger.SafeSetLogger(ConfigurationCoreMetadata.ManagedOrganization, "Delegate:" + userToken.DelegatedPrincipal.DelegatedOrganization);
     }
 }
        // Token: 0x060012B4 RID: 4788 RVA: 0x0003C958 File Offset: 0x0003AB58
        protected override void HeartBeatImpl(AuthZPluginUserToken userToken)
        {
            base.HeartBeatImpl(userToken);
            string runspaceCacheKey = this.GetRunspaceCacheKey(userToken);

            lock (base.InstanceLock)
            {
                RunspaceCacheValue value;
                if (!this.runspaceCache.TryGetValue(runspaceCacheKey, out value))
                {
                    ExTraceGlobals.PublicPluginAPITracer.TraceError <string>((long)this.GetHashCode(), "[PswsBudgetManager.HeartBeatImpl] Unexpected: User {0} is not in the runspace cache in heart-beat.", runspaceCacheKey);
                }
                else
                {
                    this.runspaceCache.InsertAbsolute(runspaceCacheKey, value, this.pswsRunspaceCacheTimeout, new RemoveItemDelegate <string, RunspaceCacheValue>(this.OnRunspaceCacheItemExpired));
                }
            }
        }
 // Token: 0x06001493 RID: 5267 RVA: 0x0004CD60 File Offset: 0x0004AF60
 internal CostHandle StartCmdlet(AuthZPluginUserToken userToken)
 {
     if (!this.ShouldThrottling(userToken))
     {
         return(null);
     }
     lock (base.InstanceLock)
     {
         IPowerShellBudget budget = base.GetBudget(userToken, true, true);
         if (budget != null)
         {
             ExTraceGlobals.PublicPluginAPITracer.TraceDebug <string>(0L, "Start budget tracking for Cmdlet, key {0}", this.CreateKey(userToken));
             return(budget.StartCmdlet(null));
         }
         ExTraceGlobals.PublicPluginAPITracer.TraceError <string>(0L, "Try to start budget tracking for Cmdlet, key {0} But the budget doesn't exist.", this.CreateKey(userToken));
     }
     return(null);
 }
예제 #11
0
        internal string GetWSManBudgetUsage(AuthZPluginUserToken userToken)
        {
            string result;

            lock (this.instanceLock)
            {
                IPowerShellBudget budget = this.GetBudget(userToken, false, false);
                if (budget == null)
                {
                    result = null;
                }
                else
                {
                    result = budget.GetWSManBudgetUsage();
                }
            }
            return(result);
        }
예제 #12
0
 internal bool CheckOverBudget(AuthZPluginUserToken userToken, CostType costType, out OverBudgetException exception)
 {
     exception = null;
     if (!this.ShouldThrottling(userToken))
     {
         return(false);
     }
     lock (this.instanceLock)
     {
         IPowerShellBudget budget = this.GetBudget(userToken, false, false);
         if (budget != null)
         {
             return(budget.TryCheckOverBudget(costType, out exception));
         }
         ExTraceGlobals.PublicPluginAPITracer.TraceDebug <string>(0L, "Try to check overbudget for key {0}. But the budget doesn't exist.", this.CreateKey(userToken));
     }
     return(false);
 }
예제 #13
0
 protected virtual void HeartBeatImpl(AuthZPluginUserToken userToken)
 {
     this.GetBudget(userToken, false, true);
 }
 // Token: 0x060012B5 RID: 4789 RVA: 0x0003C9EC File Offset: 0x0003ABEC
 private string GetRunspaceCacheKey(AuthZPluginUserToken userToken)
 {
     return(((PswsAuthZUserToken)userToken).ExecutingUserName);
 }
예제 #15
0
 protected virtual string CreateRelatedBudgetKey(AuthZPluginUserToken userToken)
 {
     return(null);
 }
        // 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)));
        }
예제 #17
0
 internal static string CreateKeyForTenantBudget(AuthZPluginUserToken userToken)
 {
     return(userToken.OrgIdInString);
 }
예제 #18
0
 protected override IPowerShellBudget CreateBudget(AuthZPluginUserToken userToken)
 {
     return(userToken.CreateBudget(BudgetType.WSManTenant));
 }
예제 #19
0
 protected override string CreateKey(AuthZPluginUserToken userToken)
 {
     return(WSManTenantBudgetManager.CreateKeyForTenantBudget(userToken));
 }
예제 #20
0
 protected virtual bool ShouldThrottling(AuthZPluginUserToken userToken)
 {
     return(true);
 }
예제 #21
0
 protected override bool ShouldThrottling(AuthZPluginUserToken userToken)
 {
     return(userToken.OrgId != null && !userToken.OrgId.Equals(OrganizationId.ForestWideOrgId));
 }
예제 #22
0
 protected virtual string CreateKey(AuthZPluginUserToken userToken)
 {
     return(userToken.UserName);
 }
예제 #23
0
 protected virtual IPowerShellBudget CreateBudget(AuthZPluginUserToken userToken)
 {
     return(userToken.CreateBudget(BudgetType.WSMan));
 }
        // 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)));
        }