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; }))); }
protected OutOfProcessServerSessionTransportManager CreateSessionTransportManager(string configurationName, PSRemotingCryptoHelperServer cryptoHelper, string workingDirectory) { PSSenderInfo senderInfo; #if !UNIX WindowsIdentity currentIdentity = WindowsIdentity.GetCurrent(); PSPrincipal userPrincipal = new PSPrincipal( new PSIdentity(string.Empty, true, currentIdentity.Name, null), currentIdentity); senderInfo = new PSSenderInfo(userPrincipal, "http://localhost"); #else PSPrincipal userPrincipal = new PSPrincipal( new PSIdentity(string.Empty, true, string.Empty, null), null); senderInfo = new PSSenderInfo(userPrincipal, "http://localhost"); #endif OutOfProcessServerSessionTransportManager tm = new OutOfProcessServerSessionTransportManager(originalStdOut, originalStdErr, cryptoHelper); ServerRemoteSession.CreateServerRemoteSession( senderInfo, _initialCommand, tm, configurationName, workingDirectory); return(tm); }
// Token: 0x0600126F RID: 4719 RVA: 0x0003B544 File Offset: 0x00039744 protected override void PostGetInitialSessionState(PSSenderInfo senderInfo) { ExTraceGlobals.PublicPluginAPITracer.TraceDebug((long)this.GetHashCode(), "[PswsAuthorizationPlugin.PostGetInitialSessionState] Enter."); UserToken userToken = HttpContext.Current.CurrentUserToken(); PswsAuthZUserToken authZPluginUserToken = PswsAuthZHelper.GetAuthZPluginUserToken(userToken); PswsBudgetManager.Instance.StartRunspace(authZPluginUserToken); ExTraceGlobals.PublicPluginAPITracer.TraceDebug((long)this.GetHashCode(), "[PswsAuthorizationPlugin.PostGetInitialSessionState] Exit."); }
private OutOfProcessServerSessionTransportManager CreateSessionTransportManager() { WindowsIdentity current = WindowsIdentity.GetCurrent(); PSPrincipal userPrincipal = new PSPrincipal(new PSIdentity("", true, current.Name, null), current); PSSenderInfo senderInfo = new PSSenderInfo(userPrincipal, "http://localhost"); OutOfProcessServerSessionTransportManager transportManager = new OutOfProcessServerSessionTransportManager(this.originalStdOut); ServerRemoteSession.CreateServerRemoteSession(senderInfo, this._initialCommand, transportManager); return(transportManager); }
/// <summary> /// Gets custom initial session state /// It relies on the RBAC system to give list of commands allowed for a user /// and creates Initial Session state from that /// </summary> /// <param name="senderInfo">Sender information</param> /// <returns>Custom initial Session state</returns> public override InitialSessionState GetInitialSessionState(PSSenderInfo senderInfo) { if (senderInfo == null) { throw new ArgumentNullException("senderInfo"); } if (senderInfo.UserInfo == null) { throw new ArgumentException("senderInfo.UserInfo is null"); } InitialSessionState initialSessionState = InitialSessionState.CreateDefault(); foreach (SessionStateCommandEntry command in initialSessionState.Commands) { command.Visibility = SessionStateEntryVisibility.Private; } List <string> scripts = RbacSystem.Current.GetScripts(senderInfo.UserInfo); foreach (string script in scripts) { initialSessionState.Commands.Add(new SessionStateScriptEntry(script)); } List <string> modules = RbacSystem.Current.GetModules(senderInfo.UserInfo); if (modules.Count > 0) { initialSessionState.ImportPSModule(modules.ToArray()); } // enable execution of scripts in this process System.Environment.SetEnvironmentVariable("PSExecutionPolicyPreference", "unrestricted"); List <string> cmdletsFromRbac = RbacSystem.Current.GetCmdlets(senderInfo.UserInfo); // Add all commands from Rbac system to Initial Session State commands foreach (string cmdlet in cmdletsFromRbac) { SessionStateCommandEntry cmdletFromRbac = initialSessionState.Commands.FirstOrDefault(item => string.Equals(item.Name, cmdlet, StringComparison.OrdinalIgnoreCase)); if (cmdletFromRbac == null) { throw new ArgumentException("Command not found in InitialSessionState " + cmdlet); } cmdletFromRbac.Visibility = SessionStateEntryVisibility.Public; } return(initialSessionState); }
public Guid CreateSession(string connection, string username, string password, int authMechanism, int protocolVersion) { Guid sessionId = Guid.NewGuid(); var identity = new PSIdentity("", true, username, null); var principal = new PSPrincipal(identity, WindowsIdentity.GetCurrent()); var sender = new PSSenderInfo(principal, connection); var session = ServerRemoteSession.CreateServerRemoteSession(sender, null, new WSManServerSessionTransportManager()); lock (_lock) { _sessions.Add(sessionId, session); } return(sessionId); }
public Guid CreateSession() { var username = System.Threading.Thread.CurrentPrincipal.Identity.Name; string connection = OperationContext.Current.Host.Description.Endpoints[0].Address.Uri.ToString(); var identity = new PSIdentity("", true, username, null); var principal = new PSPrincipal(identity, WindowsIdentity.GetCurrent()); var sender = new PSSenderInfo(principal, connection); var session = ServerRemoteSession.CreateServerRemoteSession(sender, null, sessionTransportManager); lock (_lock) { _sessions.Add(session.InstanceId, session); } return(session.InstanceId); }
public InitialSessionState Create(UserContext userContext, string membershipId) { InitialSessionState initialSessionState; using (OperationTracerWithTimeout operationTracerWithTimeout = new OperationTracerWithTimeout(new Action <string>(TraceHelper.Current.PSSessionCallStart), new Action <string>(TraceHelper.Current.PSSessionCallEnd), "InitialSessionState", new Action <string>(TraceHelper.Current.PSSessionMethodExceededTimeLimit), 30)) { PSCertificateDetails pSCertificateDetail = null; if (userContext.ClientCertificate != null) { pSCertificateDetail = new PSCertificateDetails(userContext.ClientCertificate.Subject, userContext.ClientCertificate.Issuer, userContext.ClientCertificate.Thumbprint); } PSIdentity pSIdentity = new PSIdentity(userContext.AuthenticationType, userContext.IsAuthenticated, userContext.Name, pSCertificateDetail); PSPrincipal pSPrincipal = new PSPrincipal(pSIdentity, userContext.GetIdentity() as WindowsIdentity); PSSenderInfo pSSenderInfo = new PSSenderInfo(pSPrincipal, DataServiceController.Current.GetCurrentResourceUri().ToString()); try { InitialSessionState initialSessionState1 = this.sessionConfiguration.GetInitialSessionState(pSSenderInfo); if (initialSessionState1 != null) { TraceHelper.Current.GetInitialSessionStateRequestSucceeded(userContext.Name); initialSessionState1.Trace(); initialSessionState = initialSessionState1; } else { object[] objArray = new object[2]; objArray[0] = "PSSessionState.GetInitialSessionState"; objArray[1] = "null"; throw new InvalidOperationException(ExceptionHelpers.GetExceptionMessage(Resources.MethodReturnedInvalidOutput, objArray)); } } catch (Exception exception1) { Exception exception = exception1; TraceHelper.Current.GetInitialSessionStateRequestFailed(userContext.Name, exception.Message); if (!exception.IsSevereException()) { throw new CustomModuleInvocationFailedException(this.sessionConfiguration.GetType().AssemblyQualifiedName, "GetInitialState", exception); } else { throw; } } } return(initialSessionState); }
/// <summary> /// Gets custom initial session state /// </summary> /// <param name="senderInfo">Sender information</param> /// <returns>Custom initial Session state</returns> public override InitialSessionState GetInitialSessionState(PSSenderInfo senderInfo) { var initialSessionState = InitialSessionState.CreateDefault(); var dir = HttpContext.Current != null?HttpContext.Current.Server.MapPath(".") : Directory.GetCurrentDirectory(); initialSessionState.ImportPSModule(Directory.EnumerateFiles(dir, "*.psm1") .Select(s => Path.Combine(dir, Path.GetFileNameWithoutExtension(s))).ToArray()); foreach (var cmdletFileName in Directory.EnumerateFiles(dir, "*-*.ps1")) { initialSessionState.Commands.Add( new SessionStateFunctionEntry(Path.GetFileNameWithoutExtension(cmdletFileName), File.ReadAllText(Path.Combine(dir, cmdletFileName)))); } return(initialSessionState); }
public override InitialSessionState GetInitialSessionState(PSSenderInfo senderInfo) { return(AuthZLogHelper.StartAndEndLoging <InitialSessionState>("GetInitialSessionState", () => AuthZLogHelper.ExecuteWSManPluginAPI <InitialSessionState>("GetInitialSessionState", true, true, null, delegate() { if (senderInfo == null || senderInfo.UserInfo == null || senderInfo.UserInfo.Identity == null || senderInfo.UserInfo.Identity.Name == null) { throw new ArgumentException("senderInfo"); } ExTraceGlobals.PublicPluginAPITracer.TraceDebug((long)this.GetHashCode(), "[EAP.GetInitialSessionState] Enter."); this.PreGetInitialSessionState(senderInfo); InitialSessionState initialSessionState = this.currentUserISS.Target as InitialSessionState; this.currentUserISS.Target = null; if (initialSessionState == null) { initialSessionState = this.GetInitialSessionStateCore(senderInfo); } this.PostGetInitialSessionState(senderInfo); return initialSessionState; }))); }
// 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."); }
protected OutOfProcessServerSessionTransportManager CreateSessionTransportManager( string configurationName, string configurationFile, PSRemotingCryptoHelperServer cryptoHelper, string workingDirectory) { PSSenderInfo senderInfo; #if !UNIX WindowsIdentity currentIdentity = WindowsIdentity.GetCurrent(); PSPrincipal userPrincipal = new PSPrincipal( new PSIdentity(string.Empty, true, currentIdentity.Name, null), currentIdentity); senderInfo = new PSSenderInfo(userPrincipal, "http://localhost"); #else PSPrincipal userPrincipal = new PSPrincipal( new PSIdentity(string.Empty, true, string.Empty, null), null); senderInfo = new PSSenderInfo(userPrincipal, "http://localhost"); #endif var tm = new OutOfProcessServerSessionTransportManager( originalStdOut, originalStdErr, cryptoHelper); ServerRemoteSession.CreateServerRemoteSession( senderInfo: senderInfo, configurationProviderId: "Microsoft.PowerShell", initializationParameters: string.Empty, transportManager: tm, initialCommand: _initialCommand, configurationName: configurationName, configurationFile: configurationFile, initialLocation: workingDirectory); return(tm); }
private void Start(string initialCommand) { WindowsIdentity current = WindowsIdentity.GetCurrent(); PSSenderInfo senderInfo = new PSSenderInfo(new PSPrincipal(new PSIdentity("", true, current.Name, (PSCertificateDetails)null), current), "http://localhost"); this.sessionTM = new OutOfProcessServerSessionTransportManager(this.originalStdOut); ServerRemoteSession.CreateServerRemoteSession(senderInfo, initialCommand, (AbstractServerSessionTransportManager)this.sessionTM); try { while (true) { string str = this.originalStdIn.ReadLine(); if (!string.IsNullOrEmpty(str)) { ThreadPool.QueueUserWorkItem(new WaitCallback(this.ProcessingThreadStart), (object)str); } else { break; } } this.sessionTM.Close((Exception)null); throw new PSRemotingTransportException(PSRemotingErrorId.IPCUnknownElementReceived, new object[1] { (object)string.Empty }); } catch (Exception ex) { CommandProcessorBase.CheckForSevereException(ex); OutOfProcessMediator.ETWTracer.OperationalChannel.WriteError(PSEventId.TransportError, PSOpcode.Open, PSTask.None, (object)Guid.Empty, (object)Guid.Empty, (object)4000, (object)ex.Message, (object)ex.StackTrace); OutOfProcessMediator.ETWTracer.AnalyticChannel.WriteError(PSEventId.TransportError_Analytic, PSOpcode.Open, PSTask.None, (object)Guid.Empty, (object)Guid.Empty, (object)4000, (object)ex.Message, (object)ex.StackTrace); this.originalStdErr.WriteLine(ex.Message); Environment.Exit(4000); } }
// 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)); }
public override InitialSessionState GetInitialSessionState(PSSessionConfigurationData sessionConfigurationData, PSSenderInfo senderInfo, string configProviderId) { Tracer tracer = new Tracer(); tracer.Correlate(); if (sessionConfigurationData != null) { if (senderInfo != null) { if (!string.IsNullOrEmpty(configProviderId)) { if (Interlocked.CompareExchange(ref PSWorkflowSessionConfiguration._modulesLoaded, 1, 0) == 0) { try { PSWorkflowConfigurationProvider configuration = WorkflowJobSourceAdapter.GetInstance().GetPSWorkflowRuntime().Configuration; if (configuration != null) { configuration.Populate(sessionConfigurationData.PrivateData, configProviderId, senderInfo); if (sessionConfigurationData.ModulesToImport != null) { foreach (string modulesToImport in sessionConfigurationData.ModulesToImport) { PSWorkflowSessionConfiguration.InitialSessionState.ImportPSModulesFromPath(modulesToImport); } } } else { throw new InvalidOperationException("PSWorkflowConfigurationProvider is null"); } } catch (Exception exception) { Interlocked.CompareExchange(ref PSWorkflowSessionConfiguration._modulesLoaded, 0, 1); throw; } } if (configProviderId.ToLower(CultureInfo.InvariantCulture).Equals("http://schemas.microsoft.com/powershell/microsoft.windows.servermanagerworkflows")) { PSSessionConfigurationData.IsServerManager = true; } return(PSWorkflowSessionConfiguration.InitialSessionState); } else { throw new ArgumentNullException("configProviderId"); } } else { throw new ArgumentNullException("senderInfo"); } } else { throw new ArgumentNullException("sessionConfigurationData"); } }
public override InitialSessionState GetInitialSessionState(PSSenderInfo senderInfo) { throw new NotImplementedException(); }
/// <summary> /// /// </summary> /// <param name="sessionConfigurationData"></param> /// <param name="senderInfo"></param> /// <param name="configProviderId"></param> /// <returns></returns> public override InitialSessionState GetInitialSessionState(PSSessionConfigurationData sessionConfigurationData, PSSenderInfo senderInfo, string configProviderId) { Tracer structuredTracer = new Tracer(); structuredTracer.Correlate(); if (sessionConfigurationData == null) { throw new ArgumentNullException("sessionConfigurationData"); } if (senderInfo == null) { throw new ArgumentNullException("senderInfo"); } if (string.IsNullOrEmpty(configProviderId)) { throw new ArgumentNullException("configProviderId"); } if (Interlocked.CompareExchange(ref _modulesLoaded, ModulesLoaded, ModulesNotLoaded) == ModulesNotLoaded) { // it is sufficient if Populate() is called the first time and // modules are loaded once try { IsWorkflowTypeEndpoint = true; PSWorkflowConfigurationProvider workflowConfiguration = WorkflowJobSourceAdapter.GetInstance().GetPSWorkflowRuntime().Configuration; if (workflowConfiguration == null) { throw new InvalidOperationException("PSWorkflowConfigurationProvider is null"); } workflowConfiguration.Populate(sessionConfigurationData.PrivateData, configProviderId, senderInfo); // now get all the modules in the specified path and import the same if (sessionConfigurationData.ModulesToImport != null) { foreach (var module in sessionConfigurationData.ModulesToImport) { ModuleSpecification moduleSpec = null; if (ModuleSpecification.TryParse(module, out moduleSpec)) { var modulesToImport = new Collection <ModuleSpecification> { moduleSpec }; InitialSessionState.ImportPSModule(modulesToImport); } else { InitialSessionState.ImportPSModule(new[] { Environment.ExpandEnvironmentVariables(module) }); } } } // Start the workflow job manager, if not started, to add an event handler for zero active sessions changed events // This is required to auto shutdown the workflow type shared process when no workflow jobs have scheduled/inprogress and when no active sessions WorkflowJobSourceAdapter.GetInstance().GetJobManager(); } catch (Exception) { // if there is an exception in either Populate() or Importing modules // we consider that it is not loaded Interlocked.CompareExchange(ref _modulesLoaded, ModulesNotLoaded, ModulesLoaded); throw; } } if (configProviderId.ToLower(CultureInfo.InvariantCulture).Equals("http://schemas.microsoft.com/powershell/microsoft.windows.servermanagerworkflows")) { PSSessionConfigurationData.IsServerManager = true; } return(InitialSessionState); }
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); }
protected virtual void OnGetInitialSessionStateError(PSSenderInfo senderInfo, Exception exception) { }
protected virtual void PostGetInitialSessionState(PSSenderInfo senderInfo) { this.IncreasePowershellConnections(); this.LogCommonValues(); }
protected virtual void PreGetInitialSessionState(PSSenderInfo senderInfo) { }
protected OutOfProcessServerSessionTransportManager CreateSessionTransportManager(string configurationName, PSRemotingCryptoHelperServer cryptoHelper) { PSSenderInfo senderInfo; #if !UNIX WindowsIdentity currentIdentity = WindowsIdentity.GetCurrent(); PSPrincipal userPrincipal = new PSPrincipal(new PSIdentity("", true, currentIdentity.Name, null), currentIdentity); senderInfo = new PSSenderInfo(userPrincipal, "http://localhost"); #else PSPrincipal userPrincipal = new PSPrincipal(new PSIdentity("", true, "", null), null); senderInfo = new PSSenderInfo(userPrincipal, "http://localhost"); #endif OutOfProcessServerSessionTransportManager tm = new OutOfProcessServerSessionTransportManager(originalStdOut, originalStdErr, cryptoHelper); ServerRemoteSession srvrRemoteSession = ServerRemoteSession.CreateServerRemoteSession(senderInfo, _initialCommand, tm, configurationName); return tm; }
public override int?GetMaximumReceivedDataSizePerCommand(PSSenderInfo senderInfo) { return(new int?(AppSettings.Current.PSMaximumReceivedDataSizePerCommandMB)); }
public override int?GetMaximumReceivedObjectSize(PSSenderInfo senderInfo) { return(new int?(AppSettings.Current.PSMaximumReceivedObjectSizeMB)); }
/// <summary> /// Takes out the content from the database and writes them out. /// </summary> protected override void ProcessRecord() { // Remoting detection: // * Automatic variable $PSSenderInfo is defined in true remoting contexts as well as in background jobs. // * $PSSenderInfo.ApplicationArguments.PSVersionTable.PSVersion contains the client version, as a [version] instance. // Note: Even though $PSVersionTable.PSVersion is of type [semver] in PowerShell 6+, it is of type [version] here, // presumably because only the latter type deserializes type-faithfully. var clientVersion = PowerShellVersion; PSSenderInfo remotingClientInfo = GetVariableValue("PSSenderInfo") as PSSenderInfo; if (clientVersion == null && remotingClientInfo != null) { clientVersion = PSObject.Base((PSObject.Base(remotingClientInfo.ApplicationArguments["PSVersionTable"]) as PSPrimitiveDictionary)?["PSVersion"]) as Version; } // During remoting, remain compatible with v5.0- clients by default. // Passing a -PowerShellVersion argument allows overriding the client version. bool writeOldWay = (remotingClientInfo != null && clientVersion == null) // To be safe: Remoting client version could unexpectedly not be determined. || (clientVersion != null && (clientVersion.Major < 5 || (clientVersion.Major == 5 && clientVersion.Minor < 1))); TypeInfoDataBase db = this.Context.FormatDBManager.Database; List<ViewDefinition> viewdefinitions = db.viewDefinitionsSection.viewDefinitionList; Dictionary<string, List<string>> typeGroupMap = GetTypeGroupMap(db.typeGroupSection.typeGroupDefinitionList); var typedefs = new Dictionary<ConsolidatedString, List<FormatViewDefinition>>(ConsolidatedString.EqualityComparer); foreach (ViewDefinition definition in viewdefinitions) { if (definition.isHelpFormatter) continue; var consolidatedTypeName = CreateConsolidatedTypeName(definition, typeGroupMap); if (!ShouldGenerateView(consolidatedTypeName)) continue; PSControl control; var tableControlBody = definition.mainControl as TableControlBody; if (tableControlBody != null) { control = new TableControl(tableControlBody, definition); } else { var listControlBody = definition.mainControl as ListControlBody; if (listControlBody != null) { control = new ListControl(listControlBody, definition); } else { var wideControlBody = definition.mainControl as WideControlBody; if (wideControlBody != null) { control = new WideControl(wideControlBody, definition); if (writeOldWay) { // Alignment was added to WideControl in V2, but wasn't // used. It was removed in V5, but old PowerShell clients // expect this property or fail to rehydrate the remote object. var psobj = new PSObject(control); psobj.Properties.Add(new PSNoteProperty("Alignment", 0)); } } else { var complexControlBody = (ComplexControlBody)definition.mainControl; control = new CustomControl(complexControlBody, definition); } } } // Older version of PowerShell do not know about something in the control, so // don't return it. if (writeOldWay && !control.CompatibleWithOldPowerShell()) continue; var formatdef = new FormatViewDefinition(definition.name, control, definition.InstanceId); List<FormatViewDefinition> viewList; if (!typedefs.TryGetValue(consolidatedTypeName, out viewList)) { viewList = new List<FormatViewDefinition>(); typedefs.Add(consolidatedTypeName, viewList); } viewList.Add(formatdef); } // write out all the available type definitions foreach (var pair in typedefs) { var typeNames = pair.Key; if (writeOldWay) { foreach (var typeName in typeNames) { var etd = new ExtendedTypeDefinition(typeName, pair.Value); WriteObject(etd); } } else { var etd = new ExtendedTypeDefinition(typeNames[0], pair.Value); for (int i = 1; i < typeNames.Count; i++) { etd.TypeNames.Add(typeNames[i]); } WriteObject(etd); } } }
/// <summary> /// Gets application private data /// </summary> /// <param name="senderInfo">Sender information</param> /// <returns>Always returns null</returns> public override PSPrimitiveDictionary GetApplicationPrivateData(PSSenderInfo senderInfo) { return(null); }
internal void Populate(string applicationPrivateData, string configProviderId, PSSenderInfo senderInfo) { this._senderInfo = senderInfo; this.Populate(applicationPrivateData, configProviderId); }