示例#1
0
 public override PSPrimitiveDictionary GetApplicationPrivateData(PSSenderInfo senderInfo)
 {
     if (!Constants.IsPowerShellWebService)
     {
         ExchangeAuthorizationPlugin.InitializeAuthZPluginForRemotePS(senderInfo.ConnectionString);
     }
     ExchangeAuthorizationPlugin.EnsureSettingOverrideSyncIsStarted();
     return(AuthZLogHelper.StartAndEndLoging <PSPrimitiveDictionary>("GetApplicationPrivateData", () => AuthZLogHelper.ExecuteWSManPluginAPI <PSPrimitiveDictionary>("GetApplicationPrivateData", true, true, null, delegate()
     {
         InitialSessionState initialSessionStateCore = this.GetInitialSessionStateCore(senderInfo);
         if (!Constants.IsPowerShellWebService)
         {
             this.CheckSessionOverBudget();
         }
         this.currentUserISS.Target = initialSessionStateCore;
         int value = InitialSessionStateBuilder.CalculateHashForImplicitRemoting(initialSessionStateCore);
         PSPrimitiveDictionary psprimitiveDictionary = new PSPrimitiveDictionary();
         psprimitiveDictionary.Add("ImplicitRemoting", new PSPrimitiveDictionary
         {
             {
                 "Hash",
                 value
             }
         });
         if (!Constants.IsPowerShellWebService)
         {
             psprimitiveDictionary.Add("SupportedVersions", this.ExpandVersions(senderInfo.ConnectionString));
         }
         this.LogCommonValues();
         return psprimitiveDictionary;
     })));
 }
        // 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));
        }
示例#3
0
 protected virtual void CalculateOrgId()
 {
     if (this.DelegatedPrincipal != null)
     {
         ExTraceGlobals.PublicPluginAPITracer.TraceDebug <string>(0L, "Create OrgId for AuthZPluginUserToken {0} using DelegatedPrincipal.", this.UserName);
         ExchangeAuthorizationPlugin.TryFindOrganizationIdForDelegatedPrincipal(this.DelegatedPrincipal, out this.orgId);
         return;
     }
     ExTraceGlobals.PublicPluginAPITracer.TraceDebug <string>(0L, "Create OrgId for AuthZPluginUserToken {0} from UserEntry.", this.UserName);
     this.orgId = (OrganizationId)this.UserEntry[ADObjectSchema.OrganizationId];
 }
示例#4
0
        public static SecurityIdentifier GetExecutingUserSecurityIdentifier(PSPrincipal psPrincipal, string connectionUrl)
        {
            if (psPrincipal == null)
            {
                throw new ArgumentNullException("psPrincipal");
            }
            UserToken userToken = null;

            Microsoft.Exchange.Configuration.Core.AuthenticationType authenticationType;
            string    text;
            string    text2;
            IIdentity identity = ExchangeAuthorizationPlugin.InternalGetExecutingUserIdentity(psPrincipal, connectionUrl, out userToken, out authenticationType, out text, out text2);

            return(identity.GetSecurityIdentifier());
        }
示例#5
0
 static ExchangeAuthorizationPlugin()
 {
     FailFastUserCache.IsPrimaryUserCache = false;
     ExchangeAuthorizationPlugin.InitWatsonForRemotePowershell();
     if (ExchangeSetupContext.IsUnpacked)
     {
         ExchangeAuthorizationPlugin.fileSearchAssemblyResolver.Recursive   = false;
         ExchangeAuthorizationPlugin.fileSearchAssemblyResolver.SearchPaths = new string[]
         {
             ExchangeSetupContext.BinPath,
             Path.Combine(ExchangeSetupContext.BinPath, "FIP-FS\\Bin"),
             Path.Combine(ExchangeSetupContext.BinPath, "CmdletExtensionAgents"),
             Path.Combine(ExchangeSetupContext.BinPath, "res")
         };
         ExchangeAuthorizationPlugin.fileSearchAssemblyResolver.ErrorTracer = delegate(string error)
         {
             ExTraceGlobals.PublicPluginAPITracer.TraceError(0L, error.ToString());
         };
         ExchangeAuthorizationPlugin.fileSearchAssemblyResolver.Install();
     }
 }
示例#6
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);
        }
示例#7
0
 private static void InitializeAuthZPluginForRemotePS(string connectionUri)
 {
     if (AppSettings.RpsAuthZAppSettingsInitialized)
     {
         return;
     }
     AppSettings.InitializeManualLoadAppSettings(connectionUri, delegate
     {
         IAppSettings appSettings = AppSettings.Current;
         if (appSettings.SupportedEMCVersions == null)
         {
             ((ManualLoadAppSettings)appSettings).SupportedEMCVersions = SupportedVersionList.DefaultVersionString;
         }
         AppDomain.CurrentDomain.SetupInformation.ConfigurationFile = appSettings.ConfigurationFilePath;
         ConfigFiles.SetConfigSource(appSettings.VDirName, appSettings.WebSiteName);
         FailFastUserCache.FailFastEnabled = appSettings.FailFastEnabled;
         Uri uri = new Uri(connectionUri, UriKind.Absolute);
         ExchangeAuthorizationPlugin.InitializeExchangeAuthZPluginPerfCounter(appSettings.VDirName, uri.Port);
         ProvisioningCache.InitializeAppRegistrySettings(appSettings.ProvisioningCacheIdentification);
         ThreadPool.SetMaxThreads(appSettings.ThreadPoolMaxThreads, appSettings.ThreadPoolMaxCompletionPorts);
         ThrottlingPerfCounterWrapper.Initialize(BudgetType.PowerShell);
         ADSession.DisableAdminTopologyMode();
     });
 }
示例#8
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);
        }
示例#9
0
 protected virtual IIdentity GetExecutingUserIdentity(PSPrincipal psPrincipal, string connectionUrl, out UserToken userToken, out Microsoft.Exchange.Configuration.Core.AuthenticationType authenticationType)
 {
     return(ExchangeAuthorizationPlugin.InternalGetExecutingUserIdentity(psPrincipal, connectionUrl, out userToken, out authenticationType, out this.sessionId, out this.firstRequestId));
 }