public static SqlConnection GetSqlConnectionOnMaster() { string sqlConnection = String.Format(@"user id={0};password={1};data source={2};persist security info=False;initial catalog={3};connection timeout=10", RemoteServerSettings.GetSettings().LoginName, RemoteServerSettings.GetSettings().Password, RemoteServerSettings.GetSettings().ServerName, "MASTER"); return(new SqlConnection(sqlConnection)); }
public static void GrantNtfsPermissions(string path, string accountName, NTFSPermission permissions, bool inheritParentPermissions, bool preserveOriginalPermissions, RemoteServerSettings serverSettings, string usersOU, string groupsOU) { string sid = GetAccountSid(accountName, serverSettings, usersOU, groupsOU); // Check if loaded sid is not empty - because user can manually set up non existent account name. if (!String.IsNullOrEmpty(sid)) { GrantNtfsPermissionsBySid(path, sid, permissions, inheritParentPermissions, preserveOriginalPermissions); } }
private void InitializeMOG() { // Check to see if we can init the server if (!MOG_Main.Init_Client("", "Remote Server Manager")) { // Inform the user that we failed to connect and will continue in an offline mode string message = "Failed to connect to the MOG Server.\n" + "Please be advised that you will most likely experience limited functionality during this session."; MOG_Report.ReportMessage("Connection Failed", message, "", MOG_ALERT_LEVEL.ALERT); } RemoteServerSettings.Initialize(); }
private SqlConnection _getAccountSqlconnection() { Log.RemotingServiceLogger.Debug("Call get_account_sqlconnection"); if (_currentConnection == null) { _currentConnection = new SqlConnection(); string chaine = "user id=" + RemoteServerSettings.GetSettings().LoginName + ";password="******";server=" + RemoteServerSettings.GetSettings().ServerName + ";initial catalog=Accounts"; _currentConnection.ConnectionString = chaine; _currentConnection.Open(); } return(_currentConnection); }
public static bool CheckSQLDatabaseConnection() { string sqlConnection = String.Format(@"user id={0};password={1};data source={2};persist security info=False;initial catalog={3};connection timeout=10", RemoteServerSettings.GetSettings().LoginName, RemoteServerSettings.GetSettings().Password, RemoteServerSettings.GetSettings().ServerName, "Accounts"); SqlConnection connection = new SqlConnection(sqlConnection); try { connection.Open(); connection.Close(); return(true); } catch (Exception) { return(false); } }
public bool UpdateAccountActive(string pAccountName, bool pActive) { string sqlConnection = String.Format(@"user id={0};password={1};data source={2};persist security info=False;initial catalog={3};connection timeout=10", RemoteServerSettings.GetSettings().LoginName, RemoteServerSettings.GetSettings().Password, RemoteServerSettings.GetSettings().ServerName, "Accounts"); SqlConnection connection = new SqlConnection(sqlConnection); try { connection.Open(); int affectedRows = DatabaseManager.UpdateAccountActive(pAccountName, pActive, connection); connection.Close(); return(affectedRows == 1); } catch { connection.Close(); throw; } }
public bool CreateAccountDatabase(string pScriptPath) { string sqlConnection = String.Format(@"user id={0};password={1};data source={2};persist security info=False;initial catalog={3};connection timeout=10", RemoteServerSettings.GetSettings().LoginName, RemoteServerSettings.GetSettings().Password, RemoteServerSettings.GetSettings().ServerName, "MASTER"); SqlConnection connection = new SqlConnection(sqlConnection); try { connection.Open(); DatabaseManager.CreateDatabase("Accounts", connection); DatabaseManager.ExecuteScript(pScriptPath, "Accounts", connection); connection.Close(); return(true); } catch { connection.Close(); throw; } }
public static void DeleteUser(string username, RemoteServerSettings serverSettings, string usersOU) { try { if (serverSettings.ADEnabled) { // AD mode // get user entry //DirectoryEntry objUser = FindUserObject(username, serverSettings, usersOU); DirectoryEntry objUser = GetUserObject(username, serverSettings, usersOU); if (objUser == null) return; objUser.DeleteTree(); objUser.CommitChanges(); } else { // LOCAL mode DirectoryEntry machine = new DirectoryEntry( String.Format("WinNT://{0}", Environment.MachineName)); DirectoryEntry objUser = machine.Children.Find(username, "user"); machine.Children.Remove(objUser); } } catch (Exception ex) { throw new Exception("Could not delete system user", ex); } }
public static void ChangeUserPassword(string username, string password, RemoteServerSettings serverSettings, string usersOU) { try { if (serverSettings.ADEnabled) { // AD mode // get user entry //DirectoryEntry objUser = FindUserObject(username, serverSettings, usersOU); DirectoryEntry objUser = GetUserObject(username, serverSettings, usersOU); if (objUser == null) return; // change password objUser.Invoke("SetPassword", new object[] { password }); objUser.Close(); } else { // LOCAL mode // find user entry DirectoryEntry machine = new DirectoryEntry( String.Format("WinNT://{0}", Environment.MachineName)); DirectoryEntry objUser = machine.Children.Find(username, "user"); // change user password objUser.Invoke("SetPassword", new object[] { password }); objUser.Close(); } } catch (Exception ex) { throw new Exception("Could not change user password", ex); } }
public static void CreateUser(SystemUser user, RemoteServerSettings serverSettings, string usersOU, string groupsOU) { try { if (serverSettings.ADEnabled) { //check is user name less than 20 symbols if (user.Name.Length > 20) { int separatorPlace = user.Name.IndexOf("_"); user.Name = user.Name.Remove(separatorPlace - (user.Name.Length - 20), user.Name.Length - 20); } // AD mode // root entry DirectoryEntry objRoot = GetUsersRoot(serverSettings, usersOU); // add user DirectoryEntry objUser = objRoot.Children.Add("CN=" + user.Name, "user"); int spaceIdx = user.FullName.IndexOf(' '); if (spaceIdx == -1) { SetObjectProperty(objUser, "givenName", user.FullName); SetObjectProperty(objUser, "sn", user.FullName); } else { SetObjectProperty(objUser, "givenName", user.FullName.Substring(0, spaceIdx)); SetObjectProperty(objUser, "sn", user.FullName.Substring(spaceIdx + 1)); } SetObjectProperty(objUser, "description", user.Description); SetObjectProperty(objUser, "UserPrincipalName", user.Name); SetObjectProperty(objUser, "sAMAccountName", user.Name); SetObjectProperty(objUser, "UserPassword", user.Password); objUser.Properties["userAccountControl"].Value = ADAccountOptions.UF_NORMAL_ACCOUNT | ADAccountOptions.UF_PASSWD_NOTREQD; objUser.CommitChanges(); //myDirectoryEntry = GetUser(UserName); // set password objUser.Invoke("SetPassword", new object[] { user.Password }); ADAccountOptions userFlags = ADAccountOptions.UF_NORMAL_ACCOUNT; if (user.PasswordCantChange) userFlags |= ADAccountOptions.UF_PASSWD_CANT_CHANGE; if (user.PasswordNeverExpires) userFlags |= ADAccountOptions.UF_DONT_EXPIRE_PASSWD; if (user.AccountDisabled) userFlags |= ADAccountOptions.UF_ACCOUNTDISABLE; objUser.Properties["userAccountControl"].Value = userFlags; objUser.CommitChanges(); // add user to groups foreach (string groupName in user.MemberOf) AddUserToGroup(objUser, groupName, serverSettings, groupsOU); objUser.CommitChanges(); objUser.Close(); } else { // LOCAL mode DirectoryEntry computer = new DirectoryEntry( String.Format("WinNT://{0}", Environment.MachineName)); //check is user name less than 20 symbols if (user.Name.Length > 20) { int separatorPlace = user.Name.IndexOf("_"); user.Name = user.Name.Remove(separatorPlace - (user.Name.Length - 20), user.Name.Length - 20); } // create user DirectoryEntry objUser = computer.Children.Add(user.Name, "user"); objUser.Invoke("SetPassword", new object[] { user.Password }); objUser.Properties["FullName"].Add(user.FullName); objUser.Properties["Description"].Add(user.Description); objUser.Properties["UserFlags"].Add(BuildUserFlags( user.PasswordCantChange, user.PasswordNeverExpires, user.AccountDisabled)); // save account objUser.CommitChanges(); // add user to groups foreach (String groupName in user.MemberOf) { DirectoryEntry group = computer.Children.Find(groupName, "group"); if (group != null) group.Invoke("Add", new object[] { objUser.Path.ToString() }); group.CommitChanges(); } } } catch (Exception ex) { throw new Exception("Could not create system user", ex); } }
public static bool UserExists(string username, RemoteServerSettings serverSettings, string usersOU) { if (serverSettings.ADEnabled) { // AD mode return (GetUserObject(username, serverSettings, usersOU) != null); } else { // LOCAL mode return (wmi.ExecuteQuery( String.Format("SELECT * FROM Win32_UserAccount WHERE Name='{0}'", username))).Count > 0; } }
public static bool CheckWriteAccessEnabled(string path, string accountName, RemoteServerSettings serverSettings, string usersOU, string groupsOU) { return CheckWriteAccessEnabled(path, GetAccountSid(accountName, serverSettings, usersOU, groupsOU)); }
public static void RemoveNtfsPermissions(string path, string accountName, RemoteServerSettings serverSettings, string usersOU, string groupsOU) { string sid = GetAccountSid(accountName, serverSettings, usersOU, groupsOU); // Check if got non empty sid as long as user can manually supply non existent account. if (!String.IsNullOrEmpty(sid)) { RemoveNtfsPermissionsBySid(path, sid); } }
private void MainForm_FormClosing(object sender, FormClosingEventArgs e) { MOG_Main.Shutdown(); RemoteServerSettings.SaveSettings(); }
/*private static DirectoryEntry FindUserObject(string userName, RemoteServerSettings serverSettings, string usersOU) { StringBuilder sb = new StringBuilder(); // AppendProviderPath(sb, serverSettings); AppendDomainPath(sb, serverSettings); // root entry try { DirectoryEntry srchRoot = GetDirectoryObject(sb.ToString(), serverSettings); // return GetUserObject(srchRoot, userName, serverSettings); } catch { // TO-DO: Add log actions here } return null; }*/ private static string GetUserName(string userName, RemoteServerSettings serverSettings) { return userName.Replace(serverSettings.ADRootDomain + "\\", ""); }
public string GetAuthentification(string pOctoLogin, string pOctoPass, string pOctoAccount, string pComputerName, string pLoginName) { Log.RemotingServiceLogger.DebugFormat("Call of get_authentification with login : {0}, pass : {1}, account : {2}", pOctoLogin, pOctoPass, pOctoAccount); Log.RemotingServiceLogger.DebugFormat(" login : {0}, pass : {1}, server : {2}", RemoteServerSettings.GetSettings().LoginName, RemoteServerSettings.GetSettings().Password, RemoteServerSettings.GetSettings().ServerName); string md5String = ""; Token token = _getTokenByAccountName(pOctoAccount); UserRemotingContext connectionManager = new UserRemotingContext(); if (_checkAccount(token, pOctoLogin, pOctoPass) == false) { // Throw exeption // FIXME Log.RemotingServiceLogger.Error("Les User/Pass octo donn�e ne sont pas valide"); throw new Exception("messageBoxUserPasswordIncorrect.Text"); } // Generate the md5 DateTime date = DateTime.Now; string ToHash = token.get_unique_string(); ToHash += "|" + date.Minute; byte[] data = new byte[ToHash.Length]; Encoder enc = Encoding.ASCII.GetEncoder(); enc.GetBytes(ToHash.ToCharArray(), 0, ToHash.Length, data, 0, true); MD5 md5 = new MD5CryptoServiceProvider(); byte[] result = md5.ComputeHash(data); md5String = BitConverter.ToString(result).Replace("-", "").ToLower(); string connectionString = "user id=" + token.Login + ";password="******";server=" + RemoteServerSettings.GetSettings().ServerName + ";initial catalog=" + token.Account; Log.RemotingServiceLogger.DebugFormat("Connection String {0}", connectionString); SqlConnection connection = new SqlConnection(connectionString); SqlConnection secondaryConnection = new SqlConnection(connectionString); connectionManager.Token = token; connectionManager.Connection = connection; connectionManager.SecondaryConnection = secondaryConnection; if (account_table.Contains(md5String) == false) { Log.RemotingServiceLogger.DebugFormat("The account Dictionary doesnt contain this md5 : {0}", md5String); account_table[md5String] = connectionManager; } // Set the connection in the connectionManager Log.RemotingServiceLogger.DebugFormat("ConnectionString: {0}", connection.ConnectionString); this.SetConnection(connection); //OpenCBS.DatabaseConnection.ConnectionManager.GetInstance().SetConnection(connection); Log.RemotingServiceUsersLogger.InfoFormat(@"[CONNECTION {3}\{4}] Users, branch name:{0} login:{1}, connected \n \t Connection string :{2}", pOctoAccount, pOctoLogin, connectionString, pComputerName, pLoginName); Log.RemotingServiceLogger.InfoFormat(@"[CONNECTION {3}\{4}] Users, branch name:{0} login:{1}, connected \n \t Connection string :{2}", pOctoAccount, pOctoLogin, connectionString, pComputerName, pLoginName); return(md5String); }
// Check the validity of the login/pass/account private bool _checkAccount(Token pSqlToken, string pOctoLogin, string pOctoPass) { Log.RemotingServiceLogger.Debug("Call CheckAccount"); if (pSqlToken == null) { Log.RemotingServiceLogger.Debug("Call CheckAccount with pSqlToken null"); return(false); } Log.RemotingServiceLogger.DebugFormat("Call check_account user = {0} pass = {1} token = login {2}, pass {3}, account {4}", pOctoLogin, pOctoPass, pSqlToken.Login, pSqlToken.Pass, pSqlToken.Account); int valid = 0; string connection_string = "user id=" + pSqlToken.Login + ";password="******";server=" + RemoteServerSettings.GetSettings().ServerName + ";initial catalog=" + pSqlToken.Account; SqlConnection connection = new SqlConnection(connection_string); if (connection.State != ConnectionState.Open) { connection.Open(); } // CHECK if the pOctoLogin/pOctoPass is a valid octo Account string sqlText = "select * from dbo.Users where user_name =@username and user_pass =@password "; SqlCommand command = new SqlCommand(sqlText, connection); command.Parameters.Add("username", SqlDbType.NVarChar); command.Parameters["username"].Value = pOctoLogin; command.Parameters.Add("password", SqlDbType.NVarChar); command.Parameters["password"].Value = pOctoPass; try { valid = int.Parse(command.ExecuteScalar().ToString()); } catch { return(false); } return(true); }
private static DirectoryEntry GetUserObject(string userName, RemoteServerSettings serverSettings, string usersOU) { // root entry DirectoryEntry objRoot = GetUsersRoot(serverSettings, usersOU); return GetUserObject(objRoot, userName, serverSettings); }
private static DirectoryEntry GetGroupObject(string groupName, RemoteServerSettings serverSettings, string groupsOU) { // root entry DirectoryEntry objRoot = GetGroupsRoot(serverSettings, groupsOU); DirectoryEntry result = null; try { result = GetGroupObject(objRoot, groupName, serverSettings); } catch { objRoot = GetUsersRoot(serverSettings, groupsOU); result = GetGroupObject(objRoot, groupName, serverSettings); } return result; }
public static void GrantGroupNtfsPermissions( string path, UserPermission[] users, bool resetChildPermissions, RemoteServerSettings serverSettings, string usersOU, string groupsOU) { // get file or directory security object FileSystemSecurity security = GetFileSystemSecurity(path); if (security == null) return; // iterate through each account foreach (UserPermission permission in users) { SecurityIdentifier identity = null; if (String.Compare(permission.AccountName, "network service", true) == 0) identity = new SecurityIdentifier(SystemSID.NETWORK_SERVICE); else identity = new SecurityIdentifier(GetAccountSid(permission.AccountName, serverSettings, usersOU, groupsOU)); // remove explicit permissions security.RemoveAccessRuleAll(new FileSystemAccessRule(identity, FileSystemRights.Read, AccessControlType.Allow)); if (!permission.Read && !permission.Write) continue; FileSystemRights rights = 0; if (permission.Write) rights |= FileSystemRights.Write; if (permission.Read && security is DirectorySecurity) rights |= FileSystemRights.ReadAndExecute; if (permission.Read && security is FileSecurity) rights |= FileSystemRights.Read; if (permission.Read && permission.Write) rights |= FileSystemRights.Modify; InheritanceFlags flags = security is FileSecurity ? InheritanceFlags.None : InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit; // change DACL FileSystemAccessRule rule = new FileSystemAccessRule( identity, rights, flags, PropagationFlags.None, AccessControlType.Allow); // add/modify rule security.AddAccessRule(rule); } // allow inherited rules security.SetAccessRuleProtection(false, true); // set security object SetFileSystemSecurity(path, security); // reset child permissions if required if (resetChildPermissions && Directory.Exists(path)) ResetChildNtfsPermissions(path); }
private static DirectoryEntry GetGroupObject(DirectoryEntry objRoot, string groupName, RemoteServerSettings serverSettings) { //create instance fo the direcory searcher DirectorySearcher deSearch = new DirectorySearcher(); deSearch.SearchRoot = objRoot; deSearch.Filter = "(&(objectClass=group)(cn=" + groupName + "))"; deSearch.SearchScope = SearchScope.Subtree; //find the first instance SearchResult results = deSearch.FindOne(); //if found then return, otherwise return Null if (results != null) { return GetDirectoryObject(results.Path, serverSettings); } else { return null; } }
public static bool CheckWriteAccessEnabled(string path, string accountName, RemoteServerSettings serverSettings) { return CheckWriteAccessEnabled(path, accountName, serverSettings); }
public static void EnsureOrganizationalUnitsExist(RemoteServerSettings serverSettings, string usersOU, string groupsOU) { if (serverSettings.ADEnabled) { // Users OU EnsureOrganizationalUnitExists(usersOU, serverSettings); // Groups OU EnsureOrganizationalUnitExists(groupsOU, serverSettings); } }
public static string[] GetUsers(RemoteServerSettings serverSettings, string usersOU) { List<string> users = new List<string>(); if (serverSettings.ADEnabled) { // AD mode // root entry DirectoryEntry objRoot = GetUsersRoot(serverSettings, usersOU); //create instance fo the direcory searcher DirectorySearcher deSearch = new DirectorySearcher(); deSearch.SearchRoot = objRoot; deSearch.Filter = "(objectClass=user)"; deSearch.SearchScope = SearchScope.Subtree; //find the first instance SearchResultCollection results = deSearch.FindAll(); foreach (SearchResult result in results) { DirectoryEntry objUser = GetDirectoryObject(result.Path, serverSettings); users.Add(GetObjectProperty(objUser, "cn").ToString()); } } else { ManagementObjectCollection objUsers = wmi.ExecuteQuery("SELECT * FROM Win32_UserAccount"); foreach (ManagementObject objUser in objUsers) users.Add((string)objUser.Properties["Name"].Value); } return users.ToArray(); }
public static UserPermission[] GetGroupNtfsPermissions( string path, UserPermission[] users, RemoteServerSettings serverSettings, string usersOU, string groupsOU) { // get file or directory security object FileSystemSecurity security = GetFileSystemSecurity(path); if (security == null) return users; // get all explicit rules AuthorizationRuleCollection rules = security.GetAccessRules(true, true, typeof(SecurityIdentifier)); // iterate through each account foreach (UserPermission permission in users) { SecurityIdentifier identity = null; if (String.Compare(permission.AccountName, "network service", true) == 0) identity = new SecurityIdentifier(SystemSID.NETWORK_SERVICE); else identity = new SecurityIdentifier(GetAccountSid(permission.AccountName, serverSettings, usersOU, groupsOU)); foreach (FileSystemAccessRule rule in rules) { if (rule.IdentityReference == identity && rule.AccessControlType == AccessControlType.Allow && (rule.FileSystemRights & FileSystemRights.Read) == FileSystemRights.Read) permission.Read = true; if (rule.IdentityReference == identity && rule.AccessControlType == AccessControlType.Allow && (rule.FileSystemRights & FileSystemRights.Write) == FileSystemRights.Write) permission.Write = true; } } return users; }
public static SystemUser GetUser(string username, RemoteServerSettings serverSettings, string usersOU) { try { if (serverSettings.ADEnabled) { // get user entry //DirectoryEntry objUser = FindUserObject(username, serverSettings, usersOU); DirectoryEntry objUser = GetUserObject(username, serverSettings, usersOU); if (objUser == null) return null; // fill user SystemUser user = new SystemUser(); user.Name = GetObjectProperty(objUser, "cn").ToString(); user.FullName = GetObjectProperty(objUser, "givenName").ToString() + " " + GetObjectProperty(objUser, "sn").ToString(); user.Description = GetObjectProperty(objUser, "description").ToString(); ADAccountOptions userFlags = (ADAccountOptions)objUser.Properties["userAccountControl"].Value; user.PasswordCantChange = ((userFlags & ADAccountOptions.UF_PASSWD_CANT_CHANGE) != 0); user.PasswordNeverExpires = ((userFlags & ADAccountOptions.UF_DONT_EXPIRE_PASSWD) != 0); user.AccountDisabled = ((userFlags & ADAccountOptions.UF_ACCOUNTDISABLE) != 0); // get user groups user.MemberOf = GetUserGroups(objUser); return user; } else { // LOCAL mode SystemUser userInfo = null; DirectoryEntry computer = new DirectoryEntry( String.Format("WinNT://{0}", Environment.MachineName)); // get user entry DirectoryEntry user = null; try { user = computer.Children.Find(username, "user"); } catch { return userInfo; // user doesn't exist } if (user == null) return userInfo; // user doesn't exist // get user properties userInfo = new SystemUser(); userInfo.Name = username; userInfo.FullName = (string)user.Properties["FullName"].Value; userInfo.Description = (string)user.Properties["Description"].Value; ADAccountOptions userFlags = (ADAccountOptions)user.Properties["UserFlags"].Value; userInfo.PasswordCantChange = ((userFlags & ADAccountOptions.UF_PASSWD_CANT_CHANGE) != 0); userInfo.PasswordNeverExpires = ((userFlags & ADAccountOptions.UF_DONT_EXPIRE_PASSWD) != 0); userInfo.AccountDisabled = ((userFlags & ADAccountOptions.UF_ACCOUNTDISABLE) != 0); // get user groups List<string> userGroups = new List<string>(); object groups = user.Invoke("Groups", null); foreach (object nGroup in (IEnumerable)groups) { DirectoryEntry objGroup = new DirectoryEntry(nGroup); userGroups.Add(objGroup.Name); } userInfo.MemberOf = userGroups.ToArray(); return userInfo; } } catch (Exception ex) { throw new Exception("Could not get system user properties", ex); } }
public static void EnsureOrganizationalUnitExists(string ouName, RemoteServerSettings serverSettings) { // perform lookup from the upper one if (ouName == null || ouName == "") return; ouName = ouName.Replace("/", "\\"); string[] parts = ouName.Split('\\'); DirectoryEntry objUpperOU = GetOURoot("", serverSettings); for (int i = 0; i < parts.Length; i++) { // find OU //create instance fo the direcory searcher DirectorySearcher deSearch = new DirectorySearcher(); deSearch.SearchRoot = objUpperOU; //set the search filter deSearch.Filter = "(&(objectClass=organizationalUnit)(ou=" + parts[i] + "))"; deSearch.SearchScope = SearchScope.Subtree; //find the first instance SearchResult results = deSearch.FindOne(); if (results == null) { // OU not found // create it DirectoryEntry objOU = objUpperOU.Children.Add("OU=" + parts[i], "organizationalUnit"); objOU.CommitChanges(); objUpperOU = objOU; } else { objUpperOU = GetDirectoryObject(results.Path, serverSettings); } } }
public static void UpdateUser(SystemUser user, RemoteServerSettings serverSettings, string usersOU, string groupsOU) { try { if (serverSettings.ADEnabled) { // AD mode // get user entry //DirectoryEntry objUser = FindUserObject(user.Name, serverSettings, usersOU); DirectoryEntry objUser = GetUserObject(user.Name, serverSettings, usersOU); if (objUser == null) return; // get original user groups string[] origGroups = GetUserGroups(objUser); // remove user from original groups foreach (string origGroupName in origGroups) RemoveUserFromGroup(objUser, origGroupName, serverSettings, groupsOU); // change properties int spaceIdx = user.FullName.IndexOf(' '); if (spaceIdx == -1) { objUser.Properties["givenName"].Value = user.FullName; objUser.Properties["sn"].Value = user.FullName; } else { objUser.Properties["givenName"].Value = user.FullName.Substring(0, spaceIdx); objUser.Properties["sn"].Value = user.FullName.Substring(spaceIdx + 1); } objUser.Properties["description"].Value = String.IsNullOrEmpty(user.Description) ? "WebsitePanel System Account" : user.Description; ADAccountOptions userFlags = ADAccountOptions.UF_NORMAL_ACCOUNT; if (user.PasswordCantChange) userFlags |= ADAccountOptions.UF_PASSWD_CANT_CHANGE; if (user.PasswordNeverExpires) userFlags |= ADAccountOptions.UF_DONT_EXPIRE_PASSWD; if (user.AccountDisabled) userFlags |= ADAccountOptions.UF_ACCOUNTDISABLE; objUser.Properties["userAccountControl"].Value = userFlags; objUser.CommitChanges(); // add user to groups foreach (string groupName in user.MemberOf) AddUserToGroup(objUser, groupName, serverSettings, groupsOU); // set password if required if (!String.IsNullOrEmpty(user.Password)) objUser.Invoke("SetPassword", new object[] { user.Password }); objUser.Close(); } else { // LOCAL mode // get user entry DirectoryEntry computer = new DirectoryEntry( String.Format("WinNT://{0}", Environment.MachineName)); // get group entry DirectoryEntry objUser = computer.Children.Find(user.Name, "user"); // change user properties objUser.Properties["FullName"].Add(user.FullName); objUser.Properties["Description"].Add(user.Description); objUser.Properties["UserFlags"].Add(BuildUserFlags( user.PasswordCantChange, user.PasswordNeverExpires, user.AccountDisabled)); // save account objUser.CommitChanges(); // remove user from all assigned groups object groups = objUser.Invoke("Groups", null); foreach (object nGroup in (IEnumerable)groups) { DirectoryEntry objGroup = new DirectoryEntry(nGroup); objGroup.Invoke("Remove", new object[] { objUser.Path }); } // add user to groups foreach (String groupName in user.MemberOf) { DirectoryEntry group = computer.Children.Find(groupName, "group"); if (group != null) group.Invoke("Add", new object[] { objUser.Path.ToString() }); group.CommitChanges(); } // change password if required if (!String.IsNullOrEmpty(user.Password)) objUser.Invoke("SetPassword", new object[] { user.Password }); } } catch (Exception ex) { throw new Exception("Could not update system user", ex); } }
internal static DirectoryEntry GetDirectoryObject(string path, RemoteServerSettings serverSettings) { return (serverSettings.ADUsername == null || serverSettings.ADUsername == "") ? new DirectoryEntry(path) : new DirectoryEntry(path, serverSettings.ADUsername, serverSettings.ADPassword, serverSettings.ADAuthenticationType); }
public static void GrantNtfsPermissions(string path, string accountName, NTFSPermission permissions, bool inheritParentPermissions, bool preserveOriginalPermissions, RemoteServerSettings serverSettings) { GrantNtfsPermissions(path, accountName, permissions, inheritParentPermissions, preserveOriginalPermissions, serverSettings, null, null); }
private static DirectoryEntry GetOURoot(string ouName, RemoteServerSettings serverSettings) { StringBuilder sb = new StringBuilder(); // append provider AppendProviderPath(sb, serverSettings); AppendOUPath(sb, ouName); AppendDomainPath(sb, serverSettings); return GetDirectoryObject(sb.ToString(), serverSettings); }
public static string GetAccountSid(string accountName, RemoteServerSettings serverSettings, string usersOU, string groupsOU) { if (serverSettings.ADEnabled) { // try to get user entry byte[] sid = null; //DirectoryEntry objUser = FindUserObject(accountName, serverSettings, usersOU); DirectoryEntry objUser = GetUserObject(accountName, serverSettings, usersOU); if (objUser == null) { // try to get group entry DirectoryEntry objGroup = FindGroupObject(accountName, serverSettings, groupsOU); if (objGroup == null) return null; sid = (byte[])GetObjectProperty(objGroup, "objectSid"); } else { sid = (byte[])GetObjectProperty(objUser, "objectSid"); } return ConvertByteToStringSid(sid); } else { // try to get user account string sid = null; try { string normAccountName = accountName; int idx = normAccountName.LastIndexOf("\\"); if (idx != -1) normAccountName = normAccountName.Substring(idx + 1); ManagementObjectCollection accounts = wmi.ExecuteQuery(String.Format( "SELECT * FROM Win32_Account WHERE Name='{0}'", normAccountName)); foreach (ManagementObject objAccount in accounts) { sid = objAccount.Properties["SID"].Value.ToString(); break; } } catch(Exception ex) { throw new Exception("Could not get account sid", ex); } return sid; } }
private static DirectoryEntry GetUsersRoot(RemoteServerSettings serverSettings, string usersOU) { StringBuilder sb = new StringBuilder(); // append provider AppendProviderPath(sb, serverSettings); AppendUsersPath(sb, serverSettings, usersOU); AppendDomainPath(sb, serverSettings); return GetDirectoryObject(sb.ToString(), serverSettings); }
private static void RemoveUserFromGroup(DirectoryEntry objUser, string groupName, RemoteServerSettings serverSettings, string groupsOU) { DirectoryEntry objGroup = FindGroupObject(groupName, serverSettings, groupsOU); if (objGroup != null) { objGroup.Invoke("Remove", new Object[] { objUser.Path.ToString() }); objGroup.Close(); } }
private static void AppendProviderPath(StringBuilder sb, RemoteServerSettings serverSettings) { sb.Append("LDAP://"); }
private static DirectoryEntry GetUserObject(DirectoryEntry objRoot, string userName, RemoteServerSettings serverSettings) { //create instance fo the direcory searcher DirectorySearcher deSearch = new DirectorySearcher(); // get user name without domain name string accountName = GetUserName(userName, serverSettings); deSearch.SearchRoot = objRoot; deSearch.Filter = "(&(objectClass=user)(cn=" + accountName + "))"; deSearch.SearchScope = SearchScope.Subtree; //find the first instance SearchResult results = deSearch.FindOne(); //if found then return, otherwise return Null if (results != null) { return GetDirectoryObject(results.Path, serverSettings); } else { return null; } }
private static void AppendGroupsPath(StringBuilder sb, RemoteServerSettings serverSettings, string groupsOU) { // append OU location if (String.IsNullOrEmpty(groupsOU)) sb.Append("CN=Users,"); // default user accounts location else AppendOUPath(sb, groupsOU); }
/// <summary> /// Grants local group membership to both local and Active Directory user accounts. /// </summary> /// <param name="userName"></param> /// <param name="groupName"></param> /// <param name="serverSettings"></param> public static void GrantLocalGroupMembership(string userName, string groupName, RemoteServerSettings serverSettings) { using (DirectoryEntry computer = new DirectoryEntry(String.Format("WinNT://{0}", Environment.MachineName))) { // get group entry using (DirectoryEntry group = computer.Children.Find(groupName, "group")) { string userObjPath = "WinNT://{0}/{1}"; // if (serverSettings.ADEnabled) userObjPath = String.Format(userObjPath, serverSettings.ADRootDomain, userName); else userObjPath = String.Format(userObjPath, Environment.MachineName, userName); // try { group.Invoke("Add", new object[] { userObjPath }); } catch (Exception ex) { Log.WriteError("SecurityUtils.GrantLocalGroupMembership has failed to succeed", ex); } // group.Close(); } // computer.Close(); } }
private static void AppendDomainPath(StringBuilder sb, RemoteServerSettings serverSettings) { string[] parts = serverSettings.ADRootDomain.Split('.'); for (int i = 0; i < parts.Length; i++) { sb.Append("DC=").Append(parts[i]); if (i < (parts.Length - 1)) sb.Append(","); } }