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);
            }
        }
        // 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);
        }
Example #3
0
 // Token: 0x060012EA RID: 4842 RVA: 0x0003D9DC File Offset: 0x0003BBDC
 private static T HandleExceptionAndRetry <T>(string methodName, Func <T> func, bool throwException, T defaultReturnValue)
 {
     for (int i = 0; i < 2; i++)
     {
         try
         {
             Microsoft.Exchange.Diagnostics.Components.Authorization.ExTraceGlobals.PublicPluginAPITracer.TraceDebug <string, int>(0L, "Retry function {0} the {1} times.", methodName, i);
             return(func());
         }
         catch (Exception ex)
         {
             bool flag  = ex is TransientException;
             bool flag2 = AuthZPluginHelper.IsFatalException(ex);
             bool flag3 = flag2 || AuthZLogHelper.ExceptionNoNeedToRetry(ex);
             Microsoft.Exchange.Diagnostics.Components.Authorization.ExTraceGlobals.PublicPluginAPITracer.TraceDebug(0L, "{0} caught Exception {1}. IsTransientException = {2}. IsFatalException = {3}. NoNeedToRetry = {4}.", new object[]
             {
                 methodName,
                 ex,
                 flag,
                 flag2,
                 flag3
             });
             ExEventLog.EventTuple eventInfo = Microsoft.Exchange.Configuration.ObjectModel.EventLog.TaskEventLogConstants.Tuple_RBACUnavailable_UnknownError;
             if (flag)
             {
                 eventInfo = Microsoft.Exchange.Configuration.ObjectModel.EventLog.TaskEventLogConstants.Tuple_RBACUnavailable_TransientError;
             }
             else if (flag2)
             {
                 eventInfo = Microsoft.Exchange.Configuration.ObjectModel.EventLog.TaskEventLogConstants.Tuple_RBACUnavailable_FatalError;
             }
             TaskLogger.LogRbacEvent(eventInfo, null, new object[]
             {
                 methodName,
                 ex
             });
             if (flag3 || i == 1)
             {
                 if (!(ex is ADTransientException) && (flag2 || throwException))
                 {
                     throw;
                 }
                 AuthZLogHelper.LogException(ex, methodName, false);
                 break;
             }
             else
             {
                 AuthZLogger.SafeAppendGenericInfo(methodName + "-" + ex.GetType().Name + "-Retried", ex.Message);
             }
         }
     }
     Microsoft.Exchange.Diagnostics.Components.Authorization.ExTraceGlobals.PublicPluginAPITracer.TraceError <string, T>(0L, "{0} returns default value {1}.", methodName, defaultReturnValue);
     return(defaultReturnValue);
 }
        // Token: 0x06001273 RID: 4723 RVA: 0x0003B5D8 File Offset: 0x000397D8
        internal static IIdentity GetExecutingAuthZUser(UserToken userToken)
        {
            Microsoft.Exchange.Configuration.Core.AuthenticationType authenticationType = userToken.AuthenticationType;
            ExTraceGlobals.PublicPluginAPITracer.TraceDebug <Microsoft.Exchange.Configuration.Core.AuthenticationType>(0L, "[PswsAuthZHelper.GetExecutingAuthZUser] authenticationType = \"{0}\".", authenticationType);
            IIdentity identity = HttpContext.Current.Items["X-Psws-CurrentLogonUser"] as IIdentity;

            if (identity is SidOAuthIdentity)
            {
                AuthZLogger.SafeAppendGenericInfo("PswsLogonUser", "SidOAuthIdentity");
                return(identity);
            }
            if (identity is WindowsTokenIdentity)
            {
                AuthZLogger.SafeAppendGenericInfo("PswsLogonUser", "WindowsTokenIdentity");
                return(((WindowsTokenIdentity)identity).ToSerializedIdentity());
            }
            return(AuthZPluginHelper.ConstructAuthZUser(userToken, authenticationType));
        }
Example #5
0
 private void IncreasePowershellConnections()
 {
     ExTraceGlobals.PublicPluginAPITracer.TraceDebug <string>(0L, "Increase PowershellConnections for {0}.", this.currentAuthZUserToken.UserName);
     if (this.connCounterStatus != ExchangeAuthorizationPlugin.ConnCounterStatus.WaitingIncreasement)
     {
         ExTraceGlobals.PublicPluginAPITracer.TraceError <ExchangeAuthorizationPlugin.ConnCounterStatus>(0L, "Try to increase the powershell connection counter, but connCounterStatus is NOT WaitingIncreasement, instead it is {0}.", this.connCounterStatus);
         this.connCounterStatus = ExchangeAuthorizationPlugin.ConnCounterStatus.Error;
         return;
     }
     this.activeRunSpaceCostHandle = WSManBudgetManager.Instance.StartRunspace(this.currentAuthZUserToken);
     if (this.currentAuthZUserToken.OrgId != null)
     {
         this.tenantActiveRunspaceCostHandle = WSManTenantBudgetManager.Instance.StartRunspace(this.currentAuthZUserToken);
     }
     this.connCounterStatus = ExchangeAuthorizationPlugin.ConnCounterStatus.Increased;
     AuthZLogger.SafeSetLogger(RpsAuthZMetadata.ServerActiveRunspaces, WSManBudgetManager.Instance.TotalActiveRunspaces);
     AuthZLogger.SafeSetLogger(RpsAuthZMetadata.ServerActiveUsers, WSManBudgetManager.Instance.TotalActiveUsers);
     AuthZLogger.SafeSetLogger(RpsAuthZMetadata.UserBudgetOnStart, WSManBudgetManager.Instance.GetWSManBudgetUsage(this.currentAuthZUserToken));
     AuthZLogger.SafeSetLogger(RpsAuthZMetadata.TenantBudgetOnStart, WSManTenantBudgetManager.Instance.GetWSManBudgetUsage(this.currentAuthZUserToken));
     AuthZPluginHelper.UpdateAuthZPluginPerfCounters(WSManBudgetManager.Instance);
 }
Example #6
0
 private void OnKeyToRemoveBudgetsCacheValueRemoved(string key, string value, RemoveReason reason)
 {
     lock (this.instanceLock)
     {
         if (reason != RemoveReason.Removed)
         {
             ExTraceGlobals.PublicPluginAPITracer.TraceDebug <string, RemoveReason>(0L, "Key {0} is removed from budgets dictionary after timeout. Remove reason = {1}", key, reason);
             if (!BudgetManager.NormalCleanupCacheValue.Equals(value))
             {
                 this.RunspacesLeakDetected(key, value);
             }
             this.budgets.Remove(key);
         }
     }
     if (reason != RemoveReason.Removed)
     {
         this.UpdateBudgetsPerfCounter(this.budgets.Count);
         AuthZPluginHelper.UpdateAuthZPluginPerfCounters(this);
     }
     this.UpdateKeyToRemoveBudgetsPerfCounter(this.keyToRemoveBudgets.Count);
 }
Example #7
0
 private void DecreasePowershellConnections()
 {
     ExTraceGlobals.PublicPluginAPITracer.TraceDebug <string>(0L, "Decrease PowershellConnections for {0}.", (this.currentAuthZUserToken == null) ? null : this.currentAuthZUserToken.UserName);
     if (this.connCounterStatus != ExchangeAuthorizationPlugin.ConnCounterStatus.Increased)
     {
         ExTraceGlobals.PublicPluginAPITracer.TraceError <ExchangeAuthorizationPlugin.ConnCounterStatus>(0L, "Try to decrease the powershell connection counter, but connCounterStatus is NOT Increased, instead it is {0}.", this.connCounterStatus);
         this.connCounterStatus = ExchangeAuthorizationPlugin.ConnCounterStatus.Error;
         return;
     }
     AuthZPluginHelper.DisposeCostHandleAndSetToNull(ref this.activeRunSpaceCostHandle);
     AuthZPluginHelper.DisposeCostHandleAndSetToNull(ref this.tenantActiveRunspaceCostHandle);
     if (this.currentAuthZUserToken != null)
     {
         WSManBudgetManager.Instance.RemoveBudgetIfNoActiveRunspace(this.currentAuthZUserToken);
         if (this.currentAuthZUserToken.OrgId != null)
         {
             WSManTenantBudgetManager.Instance.RemoveBudgetIfNoActiveRunspace(this.currentAuthZUserToken);
         }
     }
     this.connCounterStatus = ExchangeAuthorizationPlugin.ConnCounterStatus.Decreased;
     AuthZPluginHelper.UpdateAuthZPluginPerfCounters(WSManBudgetManager.Instance);
 }
 // Token: 0x060012B6 RID: 4790 RVA: 0x0003C9FC File Offset: 0x0003ABFC
 private void OnRunspaceCacheItemExpired(string key, RunspaceCacheValue value, RemoveReason reason)
 {
     ExTraceGlobals.PublicPluginAPITracer.TraceDebug <string, RemoveReason>((long)this.GetHashCode(), "[PswsBudgetManager.OnRunspaceCacheItemExpired] item {0} is removed. Reason = {1}", key, reason);
     if (reason != RemoveReason.Removed)
     {
         try
         {
             if (value != null)
             {
                 if (value.CostHandle != null)
                 {
                     value.CostHandle.Dispose();
                 }
                 else
                 {
                     ExTraceGlobals.PublicPluginAPITracer.TraceDebug((long)this.GetHashCode(), "[PswsBudgetManager.OnRunspaceCacheItemExpired] value.CostHandle = null");
                 }
                 if (value.UserToken == null)
                 {
                     ExTraceGlobals.PublicPluginAPITracer.TraceDebug((long)this.GetHashCode(), "[PswsBudgetManager.OnRunspaceCacheItemExpired] value.UserToken = null");
                 }
                 else
                 {
                     base.RemoveBudgetIfNoActiveRunspace(value.UserToken);
                     string     runspaceCacheKey = this.GetRunspaceCacheKey(value.UserToken);
                     ExDateTime exDateTime;
                     if (runspaceCacheKey != null && this.connectedUsers.TryRemove(runspaceCacheKey, out exDateTime))
                     {
                         ExTraceGlobals.PublicPluginAPITracer.TraceDebug <string>((long)this.GetHashCode(), "[PswsBudgetManager.OnRunspaceCacheItemExpired] User {0} is removed from connectedUsers cache.", runspaceCacheKey);
                     }
                 }
             }
         }
         finally
         {
             AuthZPluginHelper.UpdateAuthZPluginPerfCounters(this);
         }
     }
 }
Example #9
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 #10
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);
        }
Example #11
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));
 }