public void SyncronizeFileSystem(SecurityTemplate securityTemplate) { string fullPath = securityTemplate.GetFullPath(ServerConfig.WebsiteDirectory); WindowsUser windowsUser = getWindowsUser(securityTemplate.Username); FileInfo fileInfo = new FileInfo(fullPath); DirectoryInfo directoryInfo = new DirectoryInfo(fullPath); if (fileInfo.Exists) { FileSecurity security = fileInfo.GetAccessControl(); applySecurityAccessRule(securityTemplate, windowsUser, security); fileInfo.SetAccessControl(security); } else if (directoryInfo.Exists) { DirectorySecurity security = directoryInfo.GetAccessControl(); applySecurityAccessRule(securityTemplate, windowsUser, security); directoryInfo.SetAccessControl(security); } else { throw new Exception( "Cannot set security rule because the path '" + fullPath + "' does not exist."); } }
private void removeWebsiteSecurity(CleanWebsite website) { SecurityIdentifier sid = null; if (website.IisSite.IdentitySid != null) { // In most cases, the SID will exist. sid = new SecurityIdentifier(website.IisSite.IdentitySid); } else if (!string.IsNullOrEmpty(website.IisSite.IdentityUserName)) { // In some cases because of an earlier bug, only the username may exist. WindowsUser windowsUser = wuManager.Find(website.IisSite.IdentityUserName); if (windowsUser != null) { sid = windowsUser.Sid; } } if (sid != null) { // If no record of the user exists, then we can't remove security. removeSecurityRecursive(getWebsiteDirectory(website), sid); } }
/// <summary> /// Gets the name of the Plex service log on user name. /// </summary> /// <returns> /// A <see cref="TE.LocalSystem.WindowsUser"/> object of the service /// log on user. /// </returns> private WindowsUser GetServiceUser() { Log.Write("Getting the service user."); WindowsUser user = null; if (IsInstalled()) { Log.Write("The Plex service is installed. Let's get the user associated with the service."); ManagementObject service = new ManagementObject( $"Win32_Service.Name='{ServiceName}'"); if (service == null) { Log.Write("The service user could not be found."); return(null); } service.Get(); user = new WindowsUser(service["startname"].ToString().Replace( @".\", $"{MachineName}\\")); Log.Write($"The Plex service user: {user.Name}."); } else { Log.Write("The Plex service is not installed."); } return(user); }
private WindowsUser findWindowsUser() { WindowsUserManager wuManager = new WindowsUserManager(ServerConfig.WindowsServerName); WindowsUser namedUser = wuManager.Find(iscBindUser); return(namedUser); }
public static bool TryCreate(bool isSeries, DateTime when, Movie movie, WindowsUser user, Episode episode) { using (UnitOfWork uow = new UnitOfWork()) { Record record = uow.Records.Where(r => r.IsSeries == false && r.MovieID == movie.ID).FirstOrDefault(); if (record == null) { record = new Record { IsSeries = isSeries, SeenAt = when, MovieID = movie.ID, UserID = user.ID }; if (episode != null) { record.EpisodeID = episode.ID; } uow.Records.Add(record); uow.Save(); return(true); } return(false); } }
public void Modify(string appPoolName, ApplicationPool modified) { try { DirectoryEntry appPools = new DirectoryEntry(AdsiPath); DirectoryEntry appPoolEntry = appPools.Children.Find( appPoolName, "IIsApplicationPool"); if (appPoolName != modified.Name) { appPoolEntry.Rename(modified.Name); } if (modified.IdentityType == ApplicationPoolIdentityType.SpecificUser) { WindowsUser user = modified.User; appPoolEntry.Properties["WamUserName"].Value = user.Username; appPoolEntry.Properties["WamUserPass"].Value = user.Password; } appPoolEntry.Properties["AppPoolIdentityType"].Value = (int)modified.IdentityType; appPoolEntry.CommitChanges(); } catch (Exception ex) { throwIfNotSupported(ex); throw new Exception( "An error occured while updating " + "the IIS Application Pool.", ex); } }
public FileSystemAccessRule GetFileSystemAccessRule <TSecurity>( SecurityTemplate template, WindowsUser windowsUser) where TSecurity : FileSystemSecurity { if (typeof(TSecurity) == typeof(DirectorySecurity)) { // Directory security with default inheritance (files and subfolders). return(new FileSystemAccessRule( windowsUser.Sid, template.GetFileSystemRights(), InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, template.GetAccessControlType())); } else if (typeof(TSecurity) == typeof(FileSecurity)) { // Files must not have inheritance specified. return(new FileSystemAccessRule( windowsUser.Sid, template.GetFileSystemRights(), template.GetAccessControlType())); } else { throw new NotSupportedException( "File system security type '" + typeof(TSecurity).FullName + "' is not supported."); } }
public ServerStatusActionResult RepairBindSecurity() { WindowsUser namedUser = findWindowsUser(); if (namedUser == null) { throw new Exception( "Cannot repair when user '" + iscBindUser + "' does not exist."); } IscBindSetup setup = new IscBindSetup( ServerConfig.IscBindDirectory.FullName, namedUser.Sid); setup.IntitializeSecurity(); ServerStatusActionResult r = new ServerStatusActionResult(); if (getIscBindSecurityStatus().Condition == ServerStatusCondition.Normal) { r.Success = true; r.UserMessage = "Security has been repaired."; } else { r.Success = false; r.UserMessage = "Security was not repaired."; } return(r); }
private WindowsUser findWindowsUser(string username) { WindowsUserManager manager = new WindowsUserManager(ServerConfig.WindowsServerName); WindowsUser windowsUser = manager.Find(username); return(windowsUser); }
public DirectoryEntry UpdateWindowsUser(WindowsUser user) { var entry = SearchEntry(user.UserName, LdapClasses.User); entry.Invoke("SetPassword", user.Password); entry.Invoke("Put", "Description", user.Description); SaveEntry(entry, false); return(entry); }
/// <summary> /// Initialize a new IIS Application Pool. /// </summary> /// <param name="name">Name of the application pool.</param> /// <param name="user">User to run the application pool.</param> /// <param name="type">Identity type of application pool.</param> protected ApplicationPool( string name, WindowsUser user, ApplicationPoolIdentityType type) { this.Name = name; this.User = user; this.IdentityType = type; }
public DirectoryEntry CreateWindowsUser(WindowsUser user) { var entryAttributes = GetEntryAttributes(user, user.OtherAttributes); var entry = CreateEntry(user.UserName, null, LdapClasses.User, entryAttributes); entry.Invoke("SetPassword", user.Password); entry.Invoke("Put", "Description", user.Description); SaveEntry(entry, false); return(entry); }
private ServerStatusElement getIscBindSecurityStatus() { ServerStatusElement e = new ServerStatusElement(); e.Name = "ISC BIND security (" + ServerConfig.IscBindDirectory.FullName + ")"; DirectorySecurity security = ServerConfig.IscBindDirectory.GetAccessControl(); AuthorizationRuleCollection rules = security.GetAccessRules( true, false, typeof(SecurityIdentifier)); WindowsUserManager wuManager = new WindowsUserManager(ServerConfig.WindowsServerName); WindowsUser namedUser = wuManager.Find(iscBindUser); if (namedUser == null) { e.Value = "Windows user '" + iscBindUser + "' is missing"; e.Condition = ServerStatusCondition.Error; } else { var q = from r in rules.OfType <FileSystemAccessRule>() where r.IdentityReference == namedUser.Sid where r.AccessControlType == AccessControlType.Allow select r; if (q.Count() != 0) { if ((q.Single().FileSystemRights & FileSystemRights.Modify) == FileSystemRights.Modify) { e.Value = "User '" + iscBindUser + "' can modify"; e.Condition = ServerStatusCondition.Normal; } else { e.Value = "User '" + iscBindUser + "' cannot modify"; e.Condition = ServerStatusCondition.Error; } } else { e.Value = "User '" + iscBindUser + "' does not have any access"; e.Condition = ServerStatusCondition.Error; } if (e.Condition == ServerStatusCondition.Error) { // At this point, if the user exists but the security is wrong, it can be reset. e.ActionText = "Repair"; e.ActionCommand = "RepairBindSecurity"; } } return(e); }
public ServerStatusActionResult RepairBindConfig() { WindowsUser namedUser = findWindowsUser(); if (namedUser == null) { throw new Exception( "Cannot repair when user '" + iscBindUser + "' does not exist."); } string iscBindDirectory = ServerConfig.IscBindDirectory.FullName; IscBindSetup bindSetup = new IscBindSetup(iscBindDirectory, namedUser.Sid); // Backup existing configs and replace with new one. bindSetup.InitializeConfig(); // Regenerate zone config file in case it's corrupt. IscBindManager bindManager = CreateManager <IscBindManager>(); bindManager.RegenerateMainConfigFile(); ServiceController sc = getIscBindServiceController(); if (sc.Status == ServiceControllerStatus.Running) { sc.Stop(); sc.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(10)); } sc.Start(); sc.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(10)); ServerStatusActionResult result = new ServerStatusActionResult(); if (sc.Status == ServiceControllerStatus.Running) { result.Success = true; result.UserMessage = "The configuration was repaired, and the ISC BIND service was restarted."; } else { result.Success = false; if (getIscBindConfigStatus().Condition == ServerStatusCondition.Normal) { result.UserMessage = "The repair was successful, but the ISC BIND service did not start."; } else { result.UserMessage = "The repair has failed, and the ISC BIND service failed to start."; } } return(result); }
private WindowsUser getWindowsUser(string username) { WindowsUser windowsUser = findWindowsUser(username); if (windowsUser == null) { throw new Exception( "There is no Windows user with username '" + username + "'."); } return(windowsUser); }
public static void Main() { WindowsUser wu = new WindowsUser(); wu.Username = "******"; Authentication.Logon(wu); //dynamic binding PassportUser pu = new PassportUser(); pu.Email = "*****@*****.**"; Authentication.Logon(pu); //dynamic binding }
private void applySecurityAccessRule <TSecurity>( SecurityTemplate securityTemplate, WindowsUser windowsUser, TSecurity security) where TSecurity : FileSystemSecurity { RemoveMatchingRules <TSecurity>( security, windowsUser.Sid, securityTemplate.GetAccessControlType()); // Add new rule (effectively replace if removed) to apply security. security.AddAccessRule(GetFileSystemAccessRule <TSecurity>(securityTemplate, windowsUser)); }
private void createServiceAccount() { windowsUser = new WindowsUser( accountUserName, accountPassword, accountDisplayName, accountDescription, WindowsUserFlag.PasswordCannotChange | WindowsUserFlag.PasswordNeverExpires); WindowsUserManager manager = new WindowsUserManager(Environment.MachineName); manager.Create(windowsUser); manager.GrantLogonAsService(windowsUser); }
public void Delete(RhspDataID dataID) { SecurityTemplate securityTemplate = Get(dataID); if (!string.IsNullOrEmpty(securityTemplate.Username)) { // Only try to delete the physical rule if the user is specified. WindowsUser windowsUser = findWindowsUser(securityTemplate.Username); if (windowsUser != null) { // Only try to delete when the user is still on the system. deleteFromFileSystem(securityTemplate, windowsUser.Sid); } } HostingConfig.Delete <SecurityTemplate>(dataID); }
public bool AddUserToGroup(WindowsUser user, IEnumerable <string> groups) { var userEntry = SearchEntry(user.UserName, LdapClasses.User); foreach (var groupName in groups) { var groupEntry = SearchEntry(groupName, LdapClasses.Group); if (!IsMemberOf(userEntry, groupEntry)) { groupEntry.Invoke(LdapMethods.Add, userEntry.Path); } } SaveEntry(userEntry, false); return(true); }
private ScriptCommandSet(Package package) { if (package == null) { throw new ArgumentNullException("package"); } _package = package; OleMenuCommandService commandService = this.ServiceProvider.GetService(typeof(IMenuCommandService)) as OleMenuCommandService; if (commandService != null) { var scriptMenuCommandId = new CommandID(CommandSet, CommandScriptId); var scriptMenuCommand = new MenuCommand(this.MenuScriptCallback, scriptMenuCommandId); commandService.AddCommand(scriptMenuCommand); var runMenuCommandId = new CommandID(CommandSet, CommandRunId); var runMenuCommand = new MenuCommand(this.MenuRunCallback, runMenuCommandId); commandService.AddCommand(runMenuCommand); } DTE2 dte = (DTE2)ServiceProvider.GetService(typeof(DTE)); IHostContext hostCtx = new HostContext(dte); IWindowsUser windowsUser = new WindowsUser(); string registryMasterKey = Registry.CurrentUser.Name + "\\Software\\SSMScripter"; IScripterParser scripterParser = new ScripterParser(); IScripter scripter = new SmoScripter(); IScripterConfigStorage scripterConfigStorage = new ScripterConfigRegistryStorage(registryMasterKey); _scriptAction = new ScriptAction(hostCtx, scripter, scripterParser, scripterConfigStorage); IRunConfigStorage runConfigStorage = new RunConfigRegistryStorage(registryMasterKey); IRunContextProvider runContextProvider = new RunContextProvider(hostCtx, runConfigStorage); IRunParamsProcessor runParamsProcessor = new RunParamsProcessor(windowsUser); IRunProcessStarter runProcessStarter = new RunProcessStarter(); _runAction = new RunAction(runContextProvider, runParamsProcessor, runProcessStarter); }
/// <summary> /// Creates an instance of the <see cref="TE.Plex.ServerService"/> /// class. /// </summary> /// <exception cref="TE.Plex.ServiceNotInstalledException"> /// The Plex Media Server service is not installed. /// </exception> /// <exception cref="TE.LocalSystem.WindowsUserSidNotFound"> /// The Plex Media Server service account SID could not be found. /// </exception> public ServerService() { try { // Get the LogOnUser for the Plex Media Server service LogOnUser = GetServiceUser(); } catch (WindowsUserSidNotFound) { throw new WindowsUserSidNotFound( "The Plex Media Server service account SID could not be found."); } // If a WindowsUser object was not returned, throw an exception // indicating the service does not exist if (LogOnUser == null) { throw new ServiceNotInstalledException( "The Plex Media Server service is not installed."); } }
/// <summary> /// Create a new IIS Virtual Server redirect. /// </summary> /// <param name="description">Shows in the IIS snap-in as comment.</param> /// <param name="redirectUrl">URL to redirect to.</param> /// <param name="redirectFlags">HttpRedirect append flags.</param> /// <param name="anonymousUser">Anonymous windows user.</param> /// <param name="homeDirectory">Required for redirect, not null.</param> /// <param name="bindings">Any number of bindings.</param> public VirtualServer( string description, string redirectUrl, VirtualServerRedirectFlag redirectFlags, WindowsUser anonymousUser, string homeDirectory, IEnumerable <VirtualServerBinding> bindings, VirtualServerPath path) : this( description, homeDirectory, anonymousUser, null, bindings, VirtualServerAuthFlag.Anonymous, VirtualServerAccessFlag.AccessRead, redirectUrl, redirectFlags, path) { }
/// <summary> /// Initializes a new IIS Virtual Server with anonymous access. /// </summary> /// <param name="description">Shows in the IIS snap-in as comment.</param> /// <param name="homeDirectory">Location of the website files.</param> /// <param name="redirectUrl">URL to redirect to.</param> /// <param name="applicationPool">Application pool to use.</param> /// <param name="bindings">Any number of bindings.</param> /// <param name="anonymousUser">Anonymous windows user.</param> public VirtualServer( string description, string homeDirectory, string applicationPool, IEnumerable <VirtualServerBinding> bindings, VirtualServerAccessFlag accessFlags, WindowsUser anonymousUser, VirtualServerPath path) : this( description, homeDirectory, anonymousUser, applicationPool, bindings, VirtualServerAuthFlag.Anonymous, accessFlags, null, VirtualServerRedirectFlag.None, path) { }
public static async void GetWindowsUser(Action <WindowsUser, Exception> onComplete) { try { if (onComplete != null) { var user = new WindowsUser(); user.DisplayName = await UserInformation.GetDisplayNameAsync(); user.FirstName = await UserInformation.GetFirstNameAsync(); user.LastName = await UserInformation.GetLastNameAsync(); var image = UserInformation.GetAccountPicture(AccountPictureKind.SmallImage) as StorageFile; if (image != null) { IRandomAccessStream myMemoryStream = await image.OpenReadAsync(); if (myMemoryStream != null) { var bytes = new byte[myMemoryStream.Size]; await myMemoryStream.ReadAsync(bytes.AsBuffer(), (uint)myMemoryStream.Size, InputStreamOptions.None); user.AccountPicture = bytes; } } onComplete(user, null); } } catch (Exception ex) { if (onComplete != null) { onComplete(null, ex); } } }
public WindowsUser GetIisIdentity(RhspManager manager) { if (IisSite.IdentityUserName == null) { throw new Exception("The IIS identity user name has not been set."); } WindowsUser windowsUser = new WindowsUser( IisSite.IdentityUserName, manager.DecryptPassword(IisSite.IdentityPassword), "IIS Identity (" + PrimaryHost.Name + ")", "User for the IIS site " + PrimaryHost.Name + " and it's application pool.", WindowsUserFlag.PasswordCannotChange | WindowsUserFlag.PasswordNeverExpires, new WindowsUserGroup("IIS_IUSRS")); if (!string.IsNullOrEmpty(IisSite.IdentitySid)) { windowsUser.Sid = new SecurityIdentifier(IisSite.IdentitySid); } return(windowsUser); }
private IEnumerable <ICommand> CreateCommands() { IHostContext hostCtx = new HostContext(_app); IWindowsUser windowsUser = new WindowsUser(); string registryMasterKey = Registry.CurrentUser.Name + "\\Software\\SSMScripter"; IScripterParser scripterParser = new ScripterParser(); IScripter scripter = new SmoScripter(); IScripterConfigStorage scripterConfigStorage = new ScripterConfigRegistryStorage(registryMasterKey); ScriptAction scriptAction = new ScriptAction(hostCtx, scripter, scripterParser, scripterConfigStorage); yield return(new ScriptCommand(_app, _addin, scriptAction)); IRunConfigStorage runConfigStorage = new RunConfigRegistryStorage(registryMasterKey); IRunContextProvider runContextProvider = new RunContextProvider(hostCtx, runConfigStorage); IRunParamsProcessor runParamsProcessor = new RunParamsProcessor(windowsUser); IRunProcessStarter runProcessStarter = new RunProcessStarter(); RunAction runAction = new RunAction(runContextProvider, runParamsProcessor, runProcessStarter); yield return(new RunCommand(_app, _addin, runAction)); }
public ActionResult <IEnumerable <string> > Windows() { var result = new List <string>(); IUser winUser = new WindowsUser() { Username = "******", Password = "******", WindowsAuth = new WindowsAuthKey { Key = "windows" } }; result.Add(authenticatorFactory.GetEncoder(winUser).EncodePassword(winUser.Password)); if (authenticatorFactory.GetAuthenticator(winUser).Authenticate(winUser)) { result.Add("Authenticated!"); } else { result.Add("Not Authenticated!"); } return(result); }
/// <summary> /// Initializes a new Virtual Server (all prarameters - protected). /// </summary> /// <param name="description">Shows in the IIS snap-in as comment.</param> /// <param name="homeDirectory">Location of the website files.</param> /// <param name="applicationPool">Application pool to use.</param> /// <param name="bindings">Any number of bindings.</param> /// <param name="authFlags"> /// Basic should be used if HTTPS is not enabled, and NTLM should be /// used to enable windows integrated authentication. /// </param> /// <param name="accessFlags">Reflects user access to website.</param> /// <param name="redirectUrl">URL to redirect to, null accepted.</param> /// <param name="redirectFlags">HttpRedirect append flags.</param> protected VirtualServer( string description, string homeDirectory, WindowsUser anonymousUser, string applicationPool, IEnumerable <VirtualServerBinding> bindings, VirtualServerAuthFlag authFlags, VirtualServerAccessFlag accessFlags, string redirectUrl, VirtualServerRedirectFlag redirectFlags, VirtualServerPath path) { this.description = description; this.homeDirectory = homeDirectory; this.applicationPool = applicationPool; this.bindings = bindings; this.authFlags = authFlags; this.accessFlags = accessFlags; this.redirectUrl = redirectUrl; this.redirectFlags = redirectFlags; this.anonymousUser = anonymousUser; this.path = path; }
/// <summary> /// Creates a new IIS virtual server. /// </summary> /// <param name="virtualServer">Virtual server to create.</param> /// <param name="start">Start the virtual server.</param> /// <returns>Virtual server with updated path.</returns> public /*VirtualServer*/ void Create(VirtualServer virtualServer, bool start) { ManagementPath createPath = new ManagementPath(); createPath.RelativePath = "IIsWebService.Name='W3SVC'"; ManagementObject management = new ManagementObject( WmiScope, createPath, null); ManagementBaseObject inParams = management.GetMethodParameters("CreateNewSite"); inParams["PathOfRootVirtualDir"] = virtualServer.HomeDirectory; inParams["ServerBindings"] = virtualServer.GetBaseObjectBindings(this); inParams["ServerComment"] = virtualServer.Description; // Execute the CreateNewSite method and get returned params. ManagementBaseObject outParams = management. InvokeMethod("CreateNewSite", inParams, null); // Set the new site path. virtualServer.Path = new VirtualServerPath( outParams.Properties["ReturnValue"].Value.ToString()); ManagementPath settingsPath = new ManagementPath(); settingsPath.RelativePath = virtualServer.Path; settingsPath.ClassName = "IIsWebServerSetting"; ManagementObject siteSettings = new ManagementObject(WmiScope, settingsPath, null); PropertyDataCollection properties = siteSettings.Properties; // If anonymous access is set, then set the anonymous user values. if ((virtualServer.AuthFlags & VirtualServerAuthFlag.Anonymous) != 0) { WindowsUser user = virtualServer.AnonymousUser; properties["AnonymousUserName"].Value = user.Username; properties["AnonymousUserPass"].Value = user.Password; } // Set only if specified, otherwise DefaultAppPool is used. if (!string.IsNullOrEmpty(virtualServer.ApplicationPool)) { properties["AppPoolId"].Value = virtualServer.ApplicationPool; } // Apply access, auth and application pool values. properties["AuthFlags"].Value = (int)virtualServer.AuthFlags; properties["AccessFlags"].Value = (int)virtualServer.AccessFlags; // Update the settings. siteSettings.Put(); // Take the ID for the virtual server and use root folder. ManagementPath rootSettingsPath = new ManagementPath( String.Format( "IIsWebVirtualDirSetting='W3SVC/{0}/ROOT'", virtualServer.Path.Id)); ManagementObject rootSettings = new ManagementObject(WmiScope, rootSettingsPath, null); PropertyDataCollection rootProperties = rootSettings.Properties; // Assign AppFriendlyName always; it may be in the DefaultAppPool. rootProperties["AppFriendlyName"].Value = virtualServer.Description; rootProperties["HttpRedirect"].Value = virtualServer.HttpRedirect; rootSettings.Put(); if (start) { // Start the virtual server if parameter is true. this.ChangeState(virtualServer, VirtualServerState.Start); } //return virtualServer; }
public static async void GetWindowsUser(Action<WindowsUser, Exception> onComplete) { try { if (onComplete != null) { var user = new WindowsUser(); user.DisplayName = await UserInformation.GetDisplayNameAsync(); user.FirstName = await UserInformation.GetFirstNameAsync(); user.LastName = await UserInformation.GetLastNameAsync(); var image = UserInformation.GetAccountPicture(AccountPictureKind.SmallImage) as StorageFile; if (image != null) { IRandomAccessStream myMemoryStream = await image.OpenReadAsync(); if (myMemoryStream != null) { var bytes = new byte[myMemoryStream.Size]; await myMemoryStream.ReadAsync(bytes.AsBuffer(), (uint)myMemoryStream.Size, InputStreamOptions.None); user.AccountPicture = bytes; } } onComplete(user, null); } } catch (Exception ex) { if (onComplete != null) { onComplete(null, ex); } } }