예제 #1
0
        private void RunspacesLeakDetected(string key, string relatedBudgetKey)
        {
            int num = 0;
            IPowerShellBudget powerShellBudget = null;

            if (this.budgets.TryGetValue(key, out powerShellBudget))
            {
                num = powerShellBudget.TotalActiveRunspacesCount;
            }
            if (powerShellBudget != null)
            {
                ExTraceGlobals.PublicPluginAPITracer.TraceError <string, string, int>(0L, "Connection leak detected for Key {0} in class {1}. Leaked value {2}.", key, base.GetType().ToString(), num);
                if (num > 0)
                {
                    AuthZLogger.SafeAppendGenericError("WSManBudgetManagerBase.RunspacesLeakDetected", string.Format("Connection leak detected for Key {0} in class {1}. Leaked value {2}.", key, base.GetType(), num), false);
                    TaskLogger.LogRbacEvent(TaskEventLogConstants.Tuple_PSConnectionLeakDetected, null, new object[]
                    {
                        key,
                        base.GetType().ToString(),
                        num
                    });
                    this.UpdateConnectionLeakPerfCounter(num);
                }
                powerShellBudget.Dispose();
            }
            if (num > 0 && relatedBudgetKey != null)
            {
                this.CorrectRelatedBudgetWhenLeak(relatedBudgetKey, num);
            }
        }
        // Token: 0x06001245 RID: 4677 RVA: 0x00039AC8 File Offset: 0x00037CC8
        public override string GetMembershipId(SenderInfo senderInfo)
        {
            ExTraceGlobals.PublicPluginAPITracer.TraceDebug((long)this.GetHashCode(), "[PswsAuthorization.GetMembershipId] Enter.");
            string result;

            try
            {
                string name = senderInfo.Principal.Identity.Name;
                ExTraceGlobals.PublicPluginAPITracer.TraceDebug <string>((long)this.GetHashCode(), "[PswsAuthorization.GetMembershipId] membershipId = \"{0}\".", name);
                result = name;
            }
            catch (Exception ex)
            {
                ExTraceGlobals.PublicPluginAPITracer.TraceError <Exception>((long)this.GetHashCode(), "[PswsAuthorization.GetMembershipId] Exception: {0}", ex);
                AuthZLogger.SafeAppendGenericError("PswsAuthorization.GetMembershipId", ex, new Func <Exception, bool>(KnownException.IsUnhandledException));
                TaskLogger.LogRbacEvent(TaskEventLogConstants.Tuple_PswsPublicAPIFailed, null, new object[]
                {
                    "PswsAuthorization.GetMembershipId",
                    ex.ToString()
                });
                PswsErrorHandling.SendErrorToClient(PswsErrorCode.MemberShipIdError, ex, null);
                throw;
            }
            finally
            {
                ExTraceGlobals.PublicPluginAPITracer.TraceDebug((long)this.GetHashCode(), "[PswsAuthorization.GetMembershipId] Exit.");
            }
            return(result);
        }
예제 #3
0
        private static void ValidateQueryString(string httpURL, ADRawEntry userEntry)
        {
            string text;
            string tenantOrganization = ExchangeRunspaceConfigurationSettings.FromUriConnectionString(httpURL, out text).TenantOrganization;
            string value = tenantOrganization;

            if (string.IsNullOrEmpty(tenantOrganization))
            {
                return;
            }
            AuthZLogger.SafeSetLogger(ConfigurationCoreMetadata.ManagedOrganization, value);
            OrganizationId organizationId = userEntry[ADObjectSchema.OrganizationId] as OrganizationId;

            if (organizationId != null && !ExchangeRunspaceConfiguration.IsAllowedOrganizationForPartnerAccounts(organizationId))
            {
                AuthZLogger.SafeAppendGenericError("ValidateQueryString", string.Format("Organization {0} not allowed for partner account.", organizationId.ToString()), false);
                ExTraceGlobals.AccessDeniedTracer.TraceError <ADObjectId>(0L, "EAP.ValidateQueryString returns AccessDenied because user {0} does not belong to the appropriate organization", userEntry.Id);
                throw new NotAllowedForPartnerAccessException(Strings.ErrorNotAllowedForPartnerAccess);
            }
            Uri uri;

            if (!Uri.TryCreate(httpURL, UriKind.Absolute, out uri))
            {
                AuthZLogger.SafeAppendGenericError("ValidateQueryString", string.Format("Url {0} Incorrect.", httpURL), false);
                ExTraceGlobals.AccessDeniedTracer.TraceError <ADObjectId, string, string>(0L, "EAP.ValidateQueryString returns AccessDenied because tenant user {0} requested partner access to {1} which is not found in the local forest and URL {2} is invalid", userEntry.Id, tenantOrganization, httpURL);
                throw new UrlInValidException(Strings.ErrorUrlInValid);
            }
            ExTraceGlobals.ADConfigTracer.TraceDebug(0L, "EAP.ValidateQueryString returns Success.");
        }
        // 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);
        }
        // Token: 0x06001277 RID: 4727 RVA: 0x0003B964 File Offset: 0x00039B64
        internal static bool TryParseCultureInfo(NameValueCollection headers, out CultureInfo cultureInfo)
        {
            cultureInfo = null;
            string text = headers.Get("X-CultureInfo");

            if (!string.IsNullOrWhiteSpace(text))
            {
                try
                {
                    cultureInfo = new CultureInfo(text);
                    return(true);
                }
                catch (CultureNotFoundException ex)
                {
                    ExTraceGlobals.RunspaceConfigTracer.TraceError <string, CultureNotFoundException>(0L, "[PswsAuthZHelper.TryParseCultureInfo] Invalid culture info \"{0}\". Exception: {1}", text, ex);
                    TaskLogger.LogRbacEvent(TaskEventLogConstants.Tuple_InvalidCultureInfo, text, new object[]
                    {
                        text,
                        ex.ToString()
                    });
                    AuthZLogger.SafeAppendGenericError("InvalidCultureInfo", text, false);
                }
                return(false);
            }
            return(false);
        }
예제 #6
0
 // Token: 0x060012E8 RID: 4840 RVA: 0x0003D98F File Offset: 0x0003BB8F
 private static void LogException(Exception ex, string funcName, bool throwException)
 {
     if (throwException)
     {
         AuthZLogger.SafeSetLogger(RpsAuthZMetadata.IsAuthorized, false);
     }
     AuthZLogger.SafeAppendGenericError(funcName, ex, new Func <Exception, bool>(KnownException.IsUnhandledException));
 }
        // 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)));
        }
예제 #8
0
        internal static bool ValidateFilteringOnlyUser(string domain, string username)
        {
            if (string.IsNullOrEmpty(domain) || !VariantConfiguration.GetSnapshot(MachineSettingsContext.Local, null, null).CmdletInfra.ValidateFilteringOnlyUser.Enabled)
            {
                return(false);
            }
            if (username.EndsWith(".exchangemon.net", StringComparison.InvariantCultureIgnoreCase))
            {
                AuthZLogger.SafeAppendGenericInfo("ValidateFilteringOnlyUser", string.Format("Bypass monitoring account {0} check.", username));
                return(false);
            }
            bool result;

            try
            {
                bool flag = false;
                domain = domain.ToLower();
                if (!UserValidationHelper.filteringOnlyCache.TryGetValue(domain, out flag))
                {
                    CustomerType customerType = CustomerType.None;
                    Guid         guid;
                    string       text;
                    string       text2;
                    UserValidationHelper.GlsSession.GetFfoTenantSettingsByDomain(domain, out guid, out text, out text2, out customerType);
                    flag = (customerType == CustomerType.FilteringOnly);
                    UserValidationHelper.filteringOnlyCache.TryInsertAbsolute(domain, flag, UserValidationHelper.DefaultAbsoluteTimeout);
                    ExTraceGlobals.PublicPluginAPITracer.TraceDebug(0L, "[UserValidationHelper.ValidateFilteringOnlyUser] Domain:{0} belongs to TenantId:{1}, Region:{2}, Version: {3}, CustomerType: {4}.", new object[]
                    {
                        domain,
                        guid,
                        text,
                        text2,
                        customerType
                    });
                    AuthZLogger.SafeAppendGenericInfo("ValidateFilteringOnlyUser", string.Format("Domain:{0} belongs to TenantId:{1}, Region:{2}, Version: {3}, CustomerType: {4}.", new object[]
                    {
                        domain,
                        guid,
                        text,
                        text2,
                        customerType
                    }));
                }
                else
                {
                    AuthZLogger.SafeAppendGenericInfo("ValidateFilteringOnlyUser", string.Format("HitCache Domain: {0} is filteringOnly: {1}.", domain, flag));
                }
                result = flag;
            }
            catch (Exception ex)
            {
                ExTraceGlobals.PublicPluginAPITracer.TraceError <Exception>(0L, "[UserValidationHelper.ValidateFilteringOnlyUser] Exception:{0}", ex);
                AuthZLogger.SafeAppendGenericError("ValidateFilteringOnlyUser", ex, new Func <Exception, bool>(KnownException.IsUnhandledException));
                result = false;
            }
            return(result);
        }
        // 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)));
        }
예제 #10
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);
        }
예제 #11
0
 // Token: 0x06000080 RID: 128 RVA: 0x00004400 File Offset: 0x00002600
 public WinRMDataReceiver(string connectionUrl, string userName, string authenticationType, LatencyTracker latencyTracker)
 {
     WinRMDataReceiver < > 4__this = this;
     if (!WinRMDataExchangeHelper.IsExchangeDataUseAuthenticationType() && !WinRMDataExchangeHelper.IsExchangeDataUseNamedPipe())
     {
         throw new InvalidFlightingException();
     }
     CoreLogger.ExecuteAndLog("WinRMDataReceiver.Ctor", true, latencyTracker, delegate(Exception ex)
     {
         AuthZLogger.SafeAppendGenericError("WinRMDataReceiver.Ctor", ex.ToString(), false);
     }, delegate()
     {
         < > 4__this.latencyTracker = latencyTracker;
         if (WinRMDataExchangeHelper.IsExchangeDataUseAuthenticationType())
         {
             WinRMDataExchangeHelper.DehydrateAuthenticationType(authenticationType, out < > 4__this.authenticationType, out < > 4__this.serializedData);
         }
         else
         {
예제 #12
0
        internal static bool TryFindOrganizationIdForDelegatedPrincipal(DelegatedPrincipal principal, out OrganizationId orgId)
        {
            orgId = null;
            ExchangeConfigurationUnit exchangeConfigurationUnit = null;
            Exception ex = null;

            try
            {
                exchangeConfigurationUnit = ExchangeAuthorizationPlugin.GetExchangeConfigurationUnitByNameOrAcceptedDomain(principal.DelegatedOrganization);
            }
            catch (CannotResolveTenantNameException ex2)
            {
                ex = ex2;
            }
            catch (DataSourceOperationException ex3)
            {
                ex = ex3;
            }
            catch (TransientException ex4)
            {
                ex = ex4;
            }
            catch (DataValidationException ex5)
            {
                ex = ex5;
            }
            if (ex != null)
            {
                AuthZLogger.SafeAppendGenericError("TryFindOrganizationIdForDelegatedPrincipal", ex, new Func <Exception, bool>(KnownException.IsUnhandledException));
                TaskLogger.LogRbacEvent(TaskEventLogConstants.Tuple_FailedToResolveOrganizationIdForDelegatedPrincipal, null, new object[]
                {
                    principal.DelegatedOrganization,
                    ex
                });
                return(false);
            }
            orgId = exchangeConfigurationUnit.OrganizationId;
            return(true);
        }
예제 #13
0
        // Token: 0x0600126E RID: 4718 RVA: 0x0003B46C File Offset: 0x0003966C
        protected override void PreGetInitialSessionState(PSSenderInfo senderInfo)
        {
            ExTraceGlobals.PublicPluginAPITracer.TraceDebug((long)this.GetHashCode(), "[PswsAuthorizationPlugin.PreGetInitialSessionState] Enter.");
            UserToken           userToken            = HttpContext.Current.CurrentUserToken();
            PswsAuthZUserToken  authZPluginUserToken = PswsAuthZHelper.GetAuthZPluginUserToken(userToken);
            OverBudgetException ex;

            if (PswsBudgetManager.Instance.CheckOverBudget(authZPluginUserToken, CostType.ActiveRunspace, out ex))
            {
                ExTraceGlobals.PublicPluginAPITracer.TraceError <OverBudgetException>((long)this.GetHashCode(), "[PswsAuthorizationPlugin.PreGetInitialSessionState] OverBudgetException: {0}.", ex);
                TaskLogger.LogRbacEvent(TaskEventLogConstants.Tuple_PswsOverBudgetException, null, new object[]
                {
                    HttpContext.Current.User.Identity.Name,
                    ex.ToString(),
                    PswsBudgetManager.Instance.GetConnectedUsers()
                });
                PswsErrorHandling.SendErrorToClient(PswsErrorCode.OverBudgetException, ex, ex.Snapshot);
                AuthZLogger.SafeAppendGenericError("OverBudgetException", ex.ToString(), false);
                throw ex;
            }
            ExTraceGlobals.PublicPluginAPITracer.TraceDebug((long)this.GetHashCode(), "[PswsAuthorizationPlugin.PreGetInitialSessionState] Exit.");
        }
 // Token: 0x06001246 RID: 4678 RVA: 0x00039C60 File Offset: 0x00037E60
 private bool ConnectionBlockedByClientAccessRules(PswsAuthZUserToken userToken, out string blockingRuleName)
 {
     blockingRuleName = null;
     if (userToken.OrgId != null && VariantConfiguration.GetSnapshot(MachineSettingsContext.Local, null, null).CmdletInfra.PswsClientAccessRulesEnabled.Enabled)
     {
         string blockRuleName = null;
         bool   result        = ClientAccessRulesUtils.ShouldBlockConnection(userToken.OrgId, ClientAccessRulesUtils.GetUsernameFromADRawEntry(userToken.UserEntry), ClientAccessProtocol.PowerShellWebServices, ClientAccessRulesUtils.GetRemoteEndPointFromContext(HttpContext.Current), ClientAccessAuthenticationMethod.BasicAuthentication, userToken.UserEntry, delegate(ClientAccessRulesEvaluationContext context)
         {
             blockRuleName = context.CurrentRule.Name;
             AuthZLogger.SafeAppendGenericError(ClientAccessRulesConstants.ClientAccessRuleName, context.CurrentRule.Name, false);
             ExTraceGlobals.PublicPluginAPITracer.TraceDebug <string, string>((long)this.GetHashCode(), "[PswsAuthorization.AuthorizeUser] Blocked by Client Access Rules ({0}={1})", ClientAccessRulesConstants.ClientAccessRuleName, context.CurrentRule.Name);
         }, delegate(double latency)
         {
             if (latency > 50.0)
             {
                 AuthZLogger.SafeAppendGenericInfo(ClientAccessRulesConstants.ClientAccessRulesLatency, latency.ToString());
                 ExTraceGlobals.PublicPluginAPITracer.TraceDebug <string, string>((long)this.GetHashCode(), "[PswsAuthorization.AuthorizeUser] Client Access Rules latency logger ({0}={1})", ClientAccessRulesConstants.ClientAccessRulesLatency, latency.ToString());
             }
         });
         blockingRuleName = blockRuleName;
         return(result);
     }
     return(false);
 }
예제 #15
0
 internal void CorrectRunspacesLeakPassively(string key, int leakedValue)
 {
     lock (this.instanceLock)
     {
         IPowerShellBudget powerShellBudget;
         if (this.budgets.TryGetValue(key, out powerShellBudget))
         {
             int totalActiveRunspacesCount = powerShellBudget.TotalActiveRunspacesCount;
             if (totalActiveRunspacesCount > 0)
             {
                 ExTraceGlobals.PublicPluginAPITracer.TraceError(0L, "Correct runspaces leak passively for Key {0} in class {1}. Current Value {2}, Leaked value {3}.", new object[]
                 {
                     key,
                     base.GetType().ToString(),
                     totalActiveRunspacesCount,
                     leakedValue
                 });
                 AuthZLogger.SafeAppendGenericError("WSManBudgetManagerBase.CorrectRunspacesLeakPassively", string.Format("Correct runspaces leak passively for Key {0} in class {1}. Current Value {2}, Leaked value {3}.", new object[]
                 {
                     key,
                     base.GetType(),
                     totalActiveRunspacesCount,
                     leakedValue
                 }), false);
                 TaskLogger.LogRbacEvent(TaskEventLogConstants.Tuple_PSConnectionLeakPassivelyCorrected, null, new object[]
                 {
                     key,
                     base.GetType().ToString(),
                     totalActiveRunspacesCount,
                     leakedValue
                 });
                 powerShellBudget.CorrectRunspacesLeak(leakedValue);
             }
         }
     }
 }
예제 #16
0
 private static IIdentity InternalGetExecutingUserIdentity(PSPrincipal psPrincipal, string connectionUrl, out UserToken userToken, out Microsoft.Exchange.Configuration.Core.AuthenticationType authenticationType, out string sessionId, out string firstRequestId)
 {
     authenticationType = Microsoft.Exchange.Configuration.Core.AuthenticationType.Unknown;
     userToken          = null;
     sessionId          = null;
     firstRequestId     = null;
     if (psPrincipal.Identity.AuthenticationType.StartsWith("Cafe-", StringComparison.OrdinalIgnoreCase))
     {
         using (WinRMDataReceiver winRMDataReceiver = new WinRMDataReceiver(connectionUrl, psPrincipal.Identity.Name, psPrincipal.Identity.AuthenticationType, AuthZLogHelper.LantencyTracker))
         {
             userToken      = winRMDataReceiver.UserToken;
             sessionId      = winRMDataReceiver.SessionId;
             firstRequestId = winRMDataReceiver.RequestId;
             string text = winRMDataReceiver.AuthenticationType.Substring("Cafe-".Length);
             if (text.Equals("GenericIdentity", StringComparison.OrdinalIgnoreCase))
             {
                 return(AuthZPluginHelper.ConstructGenericIdentityFromUserToken(userToken));
             }
             if (userToken.CommonAccessToken != null)
             {
                 return(new WindowsTokenIdentity(userToken.CommonAccessToken.WindowsAccessToken).ToSerializedIdentity());
             }
         }
     }
     if (DelegatedPrincipal.DelegatedAuthenticationType.Equals(psPrincipal.Identity.AuthenticationType, StringComparison.OrdinalIgnoreCase))
     {
         authenticationType = Microsoft.Exchange.Configuration.Core.AuthenticationType.RemotePowerShellDelegated;
         return(DelegatedPrincipal.GetDelegatedIdentity(psPrincipal.Identity.Name));
     }
     if (psPrincipal.WindowsIdentity != null)
     {
         string authenticationType2 = psPrincipal.Identity.AuthenticationType;
         if (authenticationType2 != null && authenticationType2.StartsWith("Converted-", StringComparison.OrdinalIgnoreCase))
         {
             if (authenticationType2.StartsWith("Converted-Kerberos", StringComparison.OrdinalIgnoreCase))
             {
                 authenticationType = Microsoft.Exchange.Configuration.Core.AuthenticationType.Kerberos;
             }
             else
             {
                 AuthZLogger.SafeAppendGenericError("InternalGetExecutingUserIdentity", "Unexpected AuthenticationType " + authenticationType2, true);
             }
             using (WinRMDataReceiver winRMDataReceiver2 = new WinRMDataReceiver(connectionUrl, psPrincipal.Identity.Name, psPrincipal.Identity.AuthenticationType, AuthZLogHelper.LantencyTracker))
             {
                 userToken      = winRMDataReceiver2.UserToken;
                 sessionId      = winRMDataReceiver2.SessionId;
                 firstRequestId = winRMDataReceiver2.RequestId;
                 if (userToken.CommonAccessToken == null)
                 {
                     throw new AuthzException("DEV BUG, the CommonAccessToken should not be NULL when passing from Locally Kerberos logon.");
                 }
                 return(new WindowsTokenIdentity(userToken.CommonAccessToken.WindowsAccessToken).ToSerializedIdentity());
             }
         }
         if ("CertificateLinkedUser".Equals(authenticationType2, StringComparison.OrdinalIgnoreCase))
         {
             authenticationType = Microsoft.Exchange.Configuration.Core.AuthenticationType.CertificateLinkedUser;
             return(new GenericIdentity(psPrincipal.Identity.Name));
         }
         try
         {
             authenticationType = Microsoft.Exchange.Configuration.Core.AuthenticationType.Certificate;
             new SecurityIdentifier(psPrincipal.Identity.Name);
             return(new GenericIdentity(psPrincipal.Identity.Name));
         }
         catch (ArgumentException)
         {
             authenticationType = Microsoft.Exchange.Configuration.Core.AuthenticationType.Unknown;
             return(psPrincipal.WindowsIdentity);
         }
     }
     if ("RPS".Equals(psPrincipal.Identity.AuthenticationType, StringComparison.OrdinalIgnoreCase) || "Kerberos".Equals(psPrincipal.Identity.AuthenticationType, StringComparison.OrdinalIgnoreCase) || "Basic".Equals(psPrincipal.Identity.AuthenticationType, StringComparison.OrdinalIgnoreCase))
     {
         authenticationType = Microsoft.Exchange.Configuration.Core.AuthenticationType.Kerberos;
         SecurityIdentifier securityIdentifier = (SecurityIdentifier) new NTAccount(psPrincipal.Identity.Name).Translate(typeof(SecurityIdentifier));
         return(new GenericIdentity(securityIdentifier.ToString()));
     }
     authenticationType = Microsoft.Exchange.Configuration.Core.AuthenticationType.Unknown;
     return(new GenericIdentity(psPrincipal.Identity.Name));
 }
        internal static bool RevertExpiredThrottlingPolicyIfNeeded(IPowerShellBudget budget)
        {
            if (budget == null)
            {
                return(false);
            }
            bool result;

            using (new MonitoredScope("PowerShellThrottlingPolicyUpdater", "RevertExpiredThrottlingPolicyIfNeeded", AuthZLogHelper.AuthZPerfMonitors))
            {
                ThrottlingPolicy throttlingPolicy = null;
                try
                {
                    throttlingPolicy = ((EffectiveThrottlingPolicy)budget.ThrottlingPolicy).ThrottlingPolicy;
                    Match    match = Regex.Match(throttlingPolicy.Name, "^\\[(?<expiredtime>[0-9]{4}(-[0-9]{2}){2}T([0-9]{2}:){2}[0-9]{2})\\](?<orginalname>.+)", RegexOptions.Compiled);
                    DateTime t;
                    if (!match.Success)
                    {
                        result = false;
                    }
                    else if (!DateTime.TryParse(match.Groups["expiredtime"].Value, out t))
                    {
                        AuthZLogger.SafeAppendGenericInfo("PowerShellThrottlingPolicyUpdater", string.Format("Unrecognized time format in throttling policy '{0}'.", throttlingPolicy.Name));
                        result = false;
                    }
                    else if (t > DateTime.UtcNow)
                    {
                        AuthZLogger.SafeAppendGenericInfo("PowerShellThrottlingPolicyUpdater", string.Format("Throttlling policy '{0}' is not expired yet.", throttlingPolicy.Name));
                        result = false;
                    }
                    else
                    {
                        IConfigurationSession configuationSession      = PowerShellThrottlingPolicyUpdater.GetConfiguationSession(throttlingPolicy.OrganizationId);
                        ThrottlingPolicy      writableThrottlingPolicy = PowerShellThrottlingPolicyUpdater.GetWritableThrottlingPolicy(configuationSession, throttlingPolicy);
                        if (writableThrottlingPolicy == null || writableThrottlingPolicy.Name != throttlingPolicy.Name)
                        {
                            AuthZLogger.SafeAppendGenericInfo("PowerShellThrottlingPolicyUpdater", string.Format("Throttlling policy '{0}' is updated and don't need to be expired.", throttlingPolicy.Name));
                            result = false;
                        }
                        else
                        {
                            string arg;
                            if (PowerShellThrottlingPolicyUpdater.RevertBackupThrottlingSettings(writableThrottlingPolicy, out arg))
                            {
                                writableThrottlingPolicy.Name = match.Groups["orginalname"].Value;
                                configuationSession.Save(writableThrottlingPolicy);
                                AuthZLogger.SafeAppendGenericInfo("PowerShellThrottlingPolicyUpdater", string.Format("Revert throttling policy '{0}' to name: {1} and restore backup throttling value: {2}.", throttlingPolicy.Name, writableThrottlingPolicy.Name, arg));
                            }
                            else
                            {
                                PowerShellThrottlingPolicyUpdater.ClearThrottlingPolicyAssoicate(PowerShellThrottlingPolicyUpdater.GetRecipientSession(throttlingPolicy.OrganizationId), throttlingPolicy);
                                configuationSession.Delete(writableThrottlingPolicy);
                                AuthZLogger.SafeAppendGenericInfo("PowerShellThrottlingPolicyUpdater", string.Format("Delete throttling policy '{0}' and clear associates with it.", throttlingPolicy.Name));
                            }
                            result = true;
                        }
                    }
                }
                catch (TransientException arg2)
                {
                    AuthZLogger.SafeAppendGenericInfo("PowerShellThrottlingPolicyUpdater", string.Format("Occur transient exception on revert throttling policy '{0}': {1}", (throttlingPolicy != null) ? throttlingPolicy.Name : string.Empty, arg2));
                    result = false;
                }
                catch (Exception ex)
                {
                    AuthZLogger.SafeAppendGenericError("PowerShellThrottlingPolicyUpdater", string.Format("Error on revert throttling policy '{0}': {1}", (throttlingPolicy != null) ? throttlingPolicy.Name : string.Empty, ex), KnownException.IsUnhandledException(ex));
                    result = false;
                }
            }
            return(result);
        }
예제 #18
0
 // Token: 0x06001270 RID: 4720 RVA: 0x0003B59A File Offset: 0x0003979A
 protected override void OnGetInitialSessionStateError(PSSenderInfo senderInfo, Exception exception)
 {
     base.OnGetInitialSessionStateError(senderInfo, exception);
     PswsErrorHandling.SendErrorToClient(PswsErrorCode.GetISSError, exception, null);
     AuthZLogger.SafeAppendGenericError(exception.GetType().FullName, exception, new Func <Exception, bool>(KnownException.IsUnhandledException));
 }
예제 #19
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);
        }
        // Token: 0x06001244 RID: 4676 RVA: 0x00039740 File Offset: 0x00037940
        public override WindowsIdentity AuthorizeUser(SenderInfo senderInfo, out UserQuota userQuota)
        {
            ExTraceGlobals.PublicPluginAPITracer.TraceDebug((long)this.GetHashCode(), "[PswsAuthorization.AuthorizeUser] Enter.");
            WindowsIdentity current;

            try
            {
                if (this.IsBlockedPswsDirectInvocation())
                {
                    AuthZLogger.SafeAppendGenericError("PswsAuthorization.AuthorizeUser", "UnAuthorized. Blocked Psws direct invocation", false);
                    throw new InvalidOperationException(Strings.InvalidPswsDirectInvocationBlocked);
                }
                CultureInfo cultureInfo = null;
                if (PswsAuthZHelper.TryParseCultureInfo(HttpContext.Current.Request.Headers, out cultureInfo))
                {
                    ExTraceGlobals.PublicPluginAPITracer.TraceDebug <string>((long)this.GetHashCode(), "[PswsAuthorization.AuthorizeUser] Set thread culture to be {0}", cultureInfo.Name);
                    Thread.CurrentThread.CurrentCulture   = cultureInfo;
                    Thread.CurrentThread.CurrentUICulture = cultureInfo;
                }
                IThrottlingPolicy  throttlingPolicy = null;
                PswsAuthZUserToken authZUserToken   = null;
                AuthZLogHelper.ExecuteWSManPluginAPI("PswsAuthorization.AuthorizeUser", false, true, delegate()
                {
                    UserToken userToken = HttpContext.Current.CurrentUserToken();
                    authZUserToken      = PswsAuthZHelper.GetAuthZPluginUserToken(userToken);
                    if (authZUserToken != null)
                    {
                        throttlingPolicy = authZUserToken.GetThrottlingPolicy();
                    }
                });
                ExAssert.RetailAssert(authZUserToken != null, "UnAuthorized. The user token is invalid (null).");
                ExAssert.RetailAssert(throttlingPolicy != null, "UnAuthorized. Unable to get the user quota.");
                PswsBudgetManager.Instance.HeartBeat(authZUserToken);
                AuthZLogger.SafeSetLogger(RpsAuthZMetadata.ServerActiveRunspaces, PswsBudgetManager.Instance.TotalActiveRunspaces);
                AuthZLogger.SafeSetLogger(RpsAuthZMetadata.ServerActiveUsers, PswsBudgetManager.Instance.TotalActiveUsers);
                AuthZLogger.SafeSetLogger(RpsAuthZMetadata.UserBudgetOnStart, PswsBudgetManager.Instance.GetWSManBudgetUsage(authZUserToken));
                userQuota = new UserQuota((int)(throttlingPolicy.PswsMaxConcurrency.IsUnlimited ? 2147483647U : throttlingPolicy.PswsMaxConcurrency.Value), (int)(throttlingPolicy.PswsMaxRequest.IsUnlimited ? 2147483647U : throttlingPolicy.PswsMaxRequest.Value), (int)(throttlingPolicy.PswsMaxRequestTimePeriod.IsUnlimited ? 2147483647U : throttlingPolicy.PswsMaxRequestTimePeriod.Value));
                ExTraceGlobals.PublicPluginAPITracer.TraceDebug <Unlimited <uint>, Unlimited <uint>, Unlimited <uint> >((long)this.GetHashCode(), "[PswsAuthorization.AuthorizeUser] User quota: PswsMaxConcurrenty={0}, PswsMaxRequest={1}, PswsMaxRequestTimePeriod={2}.", throttlingPolicy.PswsMaxConcurrency, throttlingPolicy.PswsMaxRequest, throttlingPolicy.PswsMaxRequestTimePeriod);
                AuthZLogger.SafeSetLogger(RpsAuthZMetadata.IsAuthorized, true);
                AuthZLogger.SafeSetLogger(RpsAuthZMetadata.AuthorizeUser, authZUserToken.UserNameForLogging);
                AuthZLogger.SafeSetLogger(RpsAuthZMetadata.GetQuota, string.Format("PswsMaxConcurrenty={0};PswsMaxRequest={1};PswsMaxRequestTimePeriod={2}", throttlingPolicy.PswsMaxConcurrency, throttlingPolicy.PswsMaxRequest, throttlingPolicy.PswsMaxRequestTimePeriod));
                string ruleName = null;
                if (this.ConnectionBlockedByClientAccessRules(authZUserToken, out ruleName))
                {
                    throw new ClientAccessRulesBlockedConnectionException(ruleName);
                }
                current = WindowsIdentity.GetCurrent();
            }
            catch (Exception ex)
            {
                ExTraceGlobals.PublicPluginAPITracer.TraceError <Exception>((long)this.GetHashCode(), "[PswsAuthorization.AuthorizeUser] Exception: {0}", ex);
                AuthZLogger.SafeAppendGenericError("PswsAuthorization.AuthorizeUser", ex, new Func <Exception, bool>(KnownException.IsUnhandledException));
                TaskLogger.LogRbacEvent(TaskEventLogConstants.Tuple_PswsPublicAPIFailed, null, new object[]
                {
                    "PswsAuthorization.AuthorizeUser",
                    ex.ToString()
                });
                AuthZLogger.SafeSetLogger(RpsAuthZMetadata.IsAuthorized, false);
                PswsErrorHandling.SendErrorToClient((ex is ClientAccessRulesBlockedConnectionException) ? PswsErrorCode.ClientAccessRuleBlock : PswsErrorCode.AuthZUserError, ex, null);
                throw;
            }
            finally
            {
                ExTraceGlobals.PublicPluginAPITracer.TraceDebug((long)this.GetHashCode(), "[PswsAuthorization.AuthorizeUser] Exit.");
            }
            return(current);
        }
예제 #21
0
        private InitialSessionState GetInitialSessionStateCore(PSSenderInfo senderInfo)
        {
            InitialSessionState result;

            using (new MonitoredScope("GetInitialSessionStateCore", "GetInitialSessionStateCore", AuthZLogHelper.AuthZPerfMonitors))
            {
                if (senderInfo == null || senderInfo.UserInfo == null || senderInfo.UserInfo.Identity == null || senderInfo.UserInfo.Identity.Name == null)
                {
                    throw new ArgumentException("senderInfo");
                }
                PSPrincipal userInfo = senderInfo.UserInfo;
                ExTraceGlobals.PublicPluginAPITracer.TraceDebug <string>((long)this.GetHashCode(), "Entering EAP.GetInitialSessionState({0})", userInfo.Identity.Name);
                UserToken userToken = null;
                Microsoft.Exchange.Configuration.Core.AuthenticationType authenticatedType;
                IIdentity executingUserIdentity = this.GetExecutingUserIdentity(userInfo, senderInfo.ConnectionString, out userToken, out authenticatedType);
                ExchangeRunspaceConfigurationSettings exchangeRunspaceConfigurationSettings = this.BuildRunspaceConfigurationSettings(senderInfo.ConnectionString, executingUserIdentity);
                if (userToken != null)
                {
                    exchangeRunspaceConfigurationSettings.UserToken = userToken;
                }
                if (AppSettings.Current.SiteRedirectTemplate != null)
                {
                    ExTraceGlobals.PublicPluginAPITracer.TraceDebug <string, string, string>((long)this.GetHashCode(), "EAP.GetInitialSessionState({0}) site redirection template used is {1}, pod redirection template used is {2}", userInfo.Identity.Name, AppSettings.Current.SiteRedirectTemplate, AppSettings.Current.PodRedirectTemplate);
                    exchangeRunspaceConfigurationSettings.SiteRedirectionTemplate = AppSettings.Current.SiteRedirectTemplate;
                    exchangeRunspaceConfigurationSettings.PodRedirectionTemplate  = AppSettings.Current.PodRedirectTemplate;
                }
                ExchangeExpiringRunspaceConfiguration exchangeExpiringRunspaceConfiguration;
                using (new MonitoredScope("GetInitialSessionStateCore", "ExchangeExpiringRunspaceConfiguration", AuthZLogHelper.AuthZPerfMonitors))
                {
                    if (DatacenterRegistry.IsForefrontForOffice())
                    {
                        try
                        {
                            using (RegistryKey registryKey = Registry.LocalMachine.OpenSubKey(string.Format("SOFTWARE\\Microsoft\\ExchangeServer\\{0}\\Setup", "v15")))
                            {
                                string   name         = "Microsoft.Exchange.Hygiene.Security.Authorization.ForefrontExpiringDatacenterRunspaceConfiguration";
                                string   path         = (string)registryKey.GetValue("MsiInstallPath");
                                string   assemblyFile = Path.Combine(path, "Bin", "Microsoft.Exchange.Hygiene.Security.Authorization.dll");
                                Assembly assembly     = Assembly.LoadFrom(assemblyFile);
                                Type     type         = assembly.GetType(name);
                                exchangeExpiringRunspaceConfiguration = (ExchangeExpiringRunspaceConfiguration)type.InvokeMember("Instance", BindingFlags.InvokeMethod, Type.DefaultBinder, null, new object[]
                                {
                                    executingUserIdentity,
                                    exchangeRunspaceConfigurationSettings,
                                    senderInfo.ConnectionString,
                                    Constants.IsPowerShellWebService
                                });
                            }
                            goto IL_1FA;
                        }
                        catch (TargetInvocationException ex)
                        {
                            throw ex.InnerException ?? ex;
                        }
                    }
                    exchangeExpiringRunspaceConfiguration = new ExchangeExpiringRunspaceConfiguration(executingUserIdentity, exchangeRunspaceConfigurationSettings, Constants.IsPowerShellWebService);
                    IL_1FA :;
                }
                this.currentAuthZUserToken = new AuthZPluginUserToken(exchangeExpiringRunspaceConfiguration.DelegatedPrincipal, exchangeExpiringRunspaceConfiguration.LogonUser, authenticatedType, exchangeExpiringRunspaceConfiguration.IdentityName);
                ADRawEntry logonUser = exchangeExpiringRunspaceConfiguration.LogonUser;
                if (logonUser[ADRecipientSchema.RemotePowerShellEnabled] != null && !(bool)logonUser[ADRecipientSchema.RemotePowerShellEnabled])
                {
                    AuthZLogger.SafeAppendGenericError("GetInitialSessionStateCore", "RemotePowerShellEnabled false", false);
                    ExTraceGlobals.AccessDeniedTracer.TraceError <string>(0L, "EAP.GetInitialSessionStateCore user {0} is not allowed to use remote Powershell, access denied", executingUserIdentity.Name);
                    AuthZPluginHelper.TriggerFailFastForAuthZFailure(this.currentAuthZUserToken.WindowsLiveId);
                    throw new RemotePowerShellNotEnabledException(Strings.ErrorRemotePowerShellNotEnabled);
                }
                if (exchangeExpiringRunspaceConfiguration.DelegatedPrincipal == null)
                {
                    ExchangeAuthorizationPlugin.ValidateQueryString(senderInfo.ConnectionString, logonUser);
                }
                else if (exchangeExpiringRunspaceConfiguration.DelegatedPrincipal.UserOrganizationId == null)
                {
                    AuthZLogger.SafeAppendGenericError("GetInitialSessionStateCore", "User Token is delegated user, but user.OrgId is null.", false);
                    ExTraceGlobals.AccessDeniedTracer.TraceError(0L, "EAP.GetInitialSessionStateCore delegated user is not in organization.");
                    AuthZPluginHelper.TriggerFailFastForAuthZFailure(this.currentAuthZUserToken.WindowsLiveId);
                    throw new DelegatedUserNotInOrgException(Strings.ErrorDelegatedUserNotInOrg);
                }
                string friendlyName = exchangeExpiringRunspaceConfiguration.OrganizationId.GetFriendlyName();
                if (exchangeExpiringRunspaceConfiguration.HasAdminRoles && exchangeExpiringRunspaceConfiguration.IsAppPasswordUsed)
                {
                    AuthZLogger.SafeAppendGenericError("GetInitialSessionStateCore", string.Format("User {0} of Domain {1} is not allowed to create session using app password.", userInfo.Identity.Name, friendlyName), false);
                    AuthZPluginHelper.TriggerFailFastForAuthZFailure(this.currentAuthZUserToken.WindowsLiveId);
                    throw new AppPasswordLoginException(Strings.ErrorAdminLoginUsingAppPassword);
                }
                if (string.Equals(executingUserIdentity.AuthenticationType, "LiveIdBasic", StringComparison.OrdinalIgnoreCase) || DelegatedPrincipal.DelegatedAuthenticationType.Equals(executingUserIdentity.AuthenticationType, StringComparison.OrdinalIgnoreCase))
                {
                    using (new MonitoredScope("GetInitialSessionStateCore", "ValidateFilteringOnlyUser", AuthZLogHelper.AuthZPerfMonitors))
                    {
                        if (UserValidationHelper.ValidateFilteringOnlyUser(friendlyName, this.currentAuthZUserToken.WindowsLiveId))
                        {
                            AuthZLogger.SafeAppendGenericError("GetInitialSessionStateCore", string.Format("User {0} of Domain {1} doesn't have valid subscriptions for Exchange Hosted.", userInfo.Identity.Name, friendlyName), false);
                            AuthZPluginHelper.TriggerFailFastForAuthZFailure(this.currentAuthZUserToken.WindowsLiveId);
                            throw new FilteringOnlyUserLoginException(Strings.ErrorFilteringOnlyUserLogin);
                        }
                    }
                }
                InitialSessionState initialSessionState;
                using (new MonitoredScope("GetInitialSessionStateCore", "exchangeRunspaceConfig.CreateInitialSessionState", AuthZLogHelper.AuthZPerfMonitors))
                {
                    initialSessionState = exchangeExpiringRunspaceConfiguration.CreateInitialSessionState();
                }
                ExTraceGlobals.PublicPluginAPITracer.TraceDebug <int>((long)this.GetHashCode(), "EAP.GetInitialSessionState(PSSenderInfo) returns ISS with {0} commands", initialSessionState.Commands.Count);
                result = initialSessionState;
            }
            return(result);
        }