/// <summary> /// Clears a flag in the user account control property. /// </summary> /// <param name="userGuid">The GUID of the user in question.</param> /// <param name="uac">The user account control property to toggle.</param> public void ClearUserAccountControl(string userGuid, UserAccountControl uac) { //Get the user DirectoryEntry ldapSearch.Filter = String.Format("(&(objectGUID={0})(objectCategory=person))", SharedMethods.Guid2OctetString(userGuid)); SearchResult result = ldapSearch.FindOne(); if (result == null) { throw new NullReferenceException("Attempted to edit a property for a nonexistent user."); } DirectoryEntry DEUser = result.GetDirectoryEntry(); UserAccountControl curVal = (UserAccountControl)DEUser.Properties["userAccountControl"].Value; DEUser.Properties["userAccountControl"].Value = (int)curVal & ((int)uac ^ int.MaxValue); DEUser.CommitChanges(); Cache.RemoveByGuid(userGuid); DEUser.Close(); }
public static bool HasNot(this UserAccountControl flags, UserAccountControl flag) => (flags & flag) == 0;
public static bool HasAny(this UserAccountControl flags, UserAccountControl flag) => (flags & flag) != 0;
// Create the "Calculated Values" private string CreateCalculatedValue(string propName, object prop) { string theCalculatedValue = ""; switch (propName) { case "pwdlastset": case "lastlogon": case "lastlogontimestamp": { // source: https://stackoverflow.com/questions/18614810/how-to-convert-active-directory-pwdlastset-to-date-time // ("accountexpires" is not a "FileTimeUtc" value) theCalculatedValue = DateTime.FromFileTimeUtc((long)prop).ToString(); break; } case "objectguid": { // Source: https://stackoverflow.com/questions/18383843/how-do-i-convert-an-active-directory-objectguid-to-a-readable-string/31040455 theCalculatedValue = new Guid((byte[])prop).ToString(); break; } case "objectsid": { // Populated the "_Calculated" properties for the SIDs // source: https://stackoverflow.com/questions/11580128/how-to-convert-sid-to-string-in-net theCalculatedValue = new SecurityIdentifier((byte[])prop, 0).ToString(); break; } case "accountexpires": { // Populated the "_Calculated" properties for the accountexpires // Source: https://stackoverflow.com/questions/6360284/convert-ldap-accountexpires-to-datetime-in-c-sharp // Source: https://stackoverflow.com/questions/8042398/c-sharp-active-directory-accountexpires-property-not-reading-correctly theCalculatedValue = (long.MaxValue == (long)prop) ? "Never" : new DateTime(1601, 01, 01, 0, 0, 0, DateTimeKind.Utc).AddTicks((long)prop).ToString(); break; } case "useraccountcontrol": { // Source: https://stackoverflow.com/questions/10231914/useraccountcontrol-in-active-directory UserAccountControl userAccountControl = (UserAccountControl)prop; // This gets a comma separated string of the flag names that apply. string userAccountControlFlagNames = userAccountControl.ToString(); theCalculatedValue = userAccountControlFlagNames; break; } case "member": case "memberof": { try { // To be simplified / fixed / debugged string[] tmpDNArr = prop.ToString().Split(','); theCalculatedValue = tmpDNArr[0].Substring(3); } catch (Exception curEx) { theCalculatedValue = curEx.Message; } break; } } return(theCalculatedValue); }
public DSAccount(DirectoryObject dsObject, DirectorySecretDecryptor pek) { // Parameter validation Validator.AssertNotNull(dsObject, "dsObject"); if (!dsObject.IsAccount) { // TODO: Exteption type throw new Exception("Not an account."); } // Guid: this.Guid = dsObject.Guid; // DN: this.DistinguishedName = dsObject.DistinguishedName; // Sid: this.Sid = dsObject.Sid; // SidHistory: dsObject.ReadAttribute(CommonDirectoryAttributes.SIDHistory, out this.sidHistory); // DisplayName: dsObject.ReadAttribute(CommonDirectoryAttributes.DisplayName, out this.displayName); // Description dsObject.ReadAttribute(CommonDirectoryAttributes.Description, out this.description); // GivenName: dsObject.ReadAttribute(CommonDirectoryAttributes.GivenName, out this.givenName); // Surname: dsObject.ReadAttribute(CommonDirectoryAttributes.Surname, out this.surname); // Security Descriptor: dsObject.ReadAttribute(CommonDirectoryAttributes.SecurityDescriptor, out this.securityDescriptor); // AdminCount (Although the schema defines it as Int32, it can only have values 0 and 1, so we directly convert it to bool) dsObject.ReadAttribute(CommonDirectoryAttributes.AdminCount, out this.adminCount); // Enabled: // TODO: Move to DirectoryObject? int?numericUac; dsObject.ReadAttribute(CommonDirectoryAttributes.UserAccountControl, out numericUac); UserAccountControl uac = (UserAccountControl)numericUac.Value; this.Enabled = !uac.HasFlag(UserAccountControl.Disabled); // Deleted: dsObject.ReadAttribute(CommonDirectoryAttributes.IsDeleted, out this.isDeleted); // LastLogon: dsObject.ReadAttribute(CommonDirectoryAttributes.LastLogon, out this.lastLogon); // UPN: dsObject.ReadAttribute(CommonDirectoryAttributes.UserPrincipalName, out this.upn); // SamAccountName: dsObject.ReadAttribute(CommonDirectoryAttributes.SAMAccountName, out this.samAccountName); // SamAccountType: // TODO: Move to DirectoryObject? int?numericAccountType; dsObject.ReadAttribute(CommonDirectoryAttributes.SamAccountType, out numericAccountType); this.SamAccountType = (SamAccountType)numericAccountType.Value; // PrimaryGroupId int?groupId; dsObject.ReadAttribute(CommonDirectoryAttributes.PrimaryGroupId, out groupId); this.PrimaryGroupId = groupId.Value; if (pek == null) { // Do not continue if we do not have a decryption key return; } // NTHash: byte[] encryptedNtHash; dsObject.ReadAttribute(CommonDirectoryAttributes.NTHash, out encryptedNtHash); if (encryptedNtHash != null) { this.NTHash = pek.DecryptHash(encryptedNtHash, this.Sid.GetRid()); } // LMHash byte[] encryptedLmHash; dsObject.ReadAttribute(CommonDirectoryAttributes.LMHash, out encryptedLmHash); if (encryptedLmHash != null) { this.LMHash = pek.DecryptHash(encryptedLmHash, this.Sid.GetRid()); } // NTHashHistory: byte[] encryptedNtHashHistory; dsObject.ReadAttribute(CommonDirectoryAttributes.NTHashHistory, out encryptedNtHashHistory); if (encryptedNtHashHistory != null) { this.NTHashHistory = pek.DecryptHashHistory(encryptedNtHashHistory, this.Sid.GetRid()); } // LMHashHistory: byte[] encryptedLmHashHistory; dsObject.ReadAttribute(CommonDirectoryAttributes.LMHashHistory, out encryptedLmHashHistory); if (encryptedLmHashHistory != null) { this.LMHashHistory = pek.DecryptHashHistory(encryptedLmHashHistory, this.Sid.GetRid()); } // SupplementalCredentials: byte[] encryptedSupplementalCredentials; dsObject.ReadAttribute(CommonDirectoryAttributes.SupplementalCredentials, out encryptedSupplementalCredentials); if (encryptedSupplementalCredentials != null) { byte[] binarySupplementalCredentials = pek.DecryptSecret(encryptedSupplementalCredentials); this.SupplementalCredentials = new SupplementalCredentials(binarySupplementalCredentials); } }
protected void login_Click(object sender, EventArgs e) { if (Cache.Get("hapBannedIps") == null) { HttpContext.Current.Cache.Insert("hapBannedIps", new List <Banned>()); } List <Banned> bans = Cache.Get("hapBannedIps") as List <Banned>; Cache.Remove("hapBannedIps"); if (bans.Count(b => b.Computer == Request.UserHostName && b.IPAddress == Request.UserHostAddress && b.UserAgent == Request.UserAgent) == 0) { bans.Add(new Banned { Attempts = 0, Computer = Request.UserHostName, IPAddress = Request.UserHostAddress, IsBanned = false, UserAgent = Request.UserAgent }); } Banned ban = bans.Single(b => b.Computer == Request.UserHostName && b.IPAddress == Request.UserHostAddress && b.UserAgent == Request.UserAgent); if (ban.IsBanned) { if (ban.BannedUntil.Value < DateTime.Now) { ban.IsBanned = false; ban.BannedUntil = null; ban.Attempts = 0; login.Visible = true; } else { message.Text = "<div class=\"ui-state-error ui-corner-all\" style=\" padding: 5px 10px\"><span class=\"ui-icon ui-icon-alert\" style=\"float: left; margin-right: 5px;\"></span>Your IP Addresss has been banned from logging on until " + ban.BannedUntil.Value.ToShortTimeString() + "</div>"; login.Visible = false; return; } } string code; ban.Attempts++; try { UserAccountControl uac = HAP.AD.User.UserAccountControl(username.Text); if ((uac & UserAccountControl.AccountDisabled) == UserAccountControl.AccountDisabled) { HAP.Web.Logging.EventViewer.Log("HAP+ Logon", "Home Access Plus+ Logon\n\nUsername: "******"\nState: Disabled", System.Diagnostics.EventLogEntryType.Information, true); HAP.Data.SQL.WebEvents.Log(DateTime.Now, "Disabled Logon", username.Text, Request.UserHostAddress, Request.Browser.Platform, Request.Browser.Browser + " " + Request.Browser.Version, Request.UserHostName, Request.UserAgent); message.Text = "<div class=\"ui-state-error ui-corner-all\" style=\" padding: 5px 10px\"><span class=\"ui-icon ui-icon-alert\" style=\"float: left; margin-right: 5px;\"></span>" + Localizable.Localize("ad/disabled") + "</div>"; return; } else if ((uac & UserAccountControl.PasswordExpired) == UserAccountControl.PasswordExpired) { HAP.Web.Logging.EventViewer.Log("HAP+ Logon", "Home Access Plus+ Logon\n\nUsername: "******"\nState: Password Expired", System.Diagnostics.EventLogEntryType.Information, true); HAP.Data.SQL.WebEvents.Log(DateTime.Now, "Expired Logon", username.Text, Request.UserHostAddress, Request.Browser.Platform, Request.Browser.Browser + " " + Request.Browser.Version, Request.UserHostName, Request.UserAgent); message.Text = "<div class=\"ui-state-error ui-corner-all\" style=\" padding: 5px 10px\"><span class=\"ui-icon ui-icon-alert\" style=\"float: left; margin-right: 5px;\"></span>" + Localizable.Localize("ad/passexpired") + "</div>"; return; } else if ((uac & UserAccountControl.Lockout) == UserAccountControl.Lockout) { HAP.Web.Logging.EventViewer.Log("HAP+ Logon", "Home Access Plus+ Logon\n\nUsername: "******"\nState: Locked Out", System.Diagnostics.EventLogEntryType.Information, true); HAP.Data.SQL.WebEvents.Log(DateTime.Now, "Lockedout Logon", username.Text, Request.UserHostAddress, Request.Browser.Platform, Request.Browser.Browser + " " + Request.Browser.Version, Request.UserHostName, Request.UserAgent); message.Text = "<div class=\"ui-state-error ui-corner-all\" style=\" padding: 5px 10px\"><span class=\"ui-icon ui-icon-alert\" style=\"float: left; margin-right: 5px;\"></span>" + Localizable.Localize("ad/lockedout") + "</div>"; return; } } catch { HAP.Web.Logging.EventViewer.Log("HAP+ Logon", "Home Access Plus+ Logon\n\nUsername: "******"\nState: Invalid", System.Diagnostics.EventLogEntryType.Error, true); HAP.Data.SQL.WebEvents.Log(DateTime.Now, "Invalid User", username.Text, Request.UserHostAddress, Request.Browser.Platform, Request.Browser.Browser + " " + Request.Browser.Version, Request.UserHostName, Request.UserAgent); } if (oneusecode.Text.Length == 4 && IsValidCode(out code) && !ban.IsBanned && Membership.ValidateUser(username.Text.Trim(), HAP.AD.TokenGenerator.ConvertToPlain(code))) { HAP.Web.Logging.EventViewer.Log("HAP+ Logon", "Home Access Plus+ Logon\n\nUsername: "******"Logon", username.Text, Request.UserHostAddress, Request.Browser.Platform, Request.Browser.Browser + " " + Request.Browser.Version, Request.UserHostName, Request.UserAgent); FormsAuthentication.SetAuthCookie(username.Text, false); HttpCookie tokenCookie = new HttpCookie("token", code); tokenCookie.Domain = ((AuthenticationSection)WebConfigurationManager.GetWebApplicationSection("system.web/authentication")).Forms.Domain; tokenCookie.Secure = true; if (Request.Cookies["token"] == null) { Response.AppendCookie(tokenCookie); } else { Response.SetCookie(tokenCookie); } bans.Remove(ban); Cache.Insert("hapBannedIps", bans); FormsAuthentication.RedirectFromLoginPage(username.Text, false); } else if (Membership.ValidateUser(username.Text.Trim(), password.Text.Trim()) && !ban.IsBanned) { HAP.Web.Logging.EventViewer.Log("HAP+ Logon", "Home Access Plus+ Logon\n\nUsername: "******"Logon", username.Text, Request.UserHostAddress, Request.Browser.Platform, Request.Browser.Browser + " " + Request.Browser.Version, Request.UserHostName, Request.UserAgent); FormsAuthentication.SetAuthCookie(username.Text, false); HttpCookie tokenCookie = new HttpCookie("token", TokenGenerator.ConvertToToken(password.Text)); tokenCookie.Secure = true; tokenCookie.Domain = ((AuthenticationSection)WebConfigurationManager.GetWebApplicationSection("system.web/authentication")).Forms.Domain; if (Request.Cookies["token"] == null) { Response.AppendCookie(tokenCookie); } else { Response.SetCookie(tokenCookie); } bans.Remove(ban); Cache.Insert("hapBannedIps", bans); if (Request.QueryString["ReturnUrl"] == "OneUseCodes.aspx") { Response.Redirect("OneUseCodes.aspx?gencodes=1"); } else { FormsAuthentication.RedirectFromLoginPage(username.Text, false); } } else { if (ban.Attempts > (hapConfig.Current.AD.MaxLogonAttemps - 1)) { ban.IsBanned = true; ban.BannedUntil = DateTime.Now.AddMinutes(30); message.Text = "<div class=\"ui-state-error ui-corner-all\" style=\" padding: 5px 10px\"><span class=\"ui-icon ui-icon-alert\" style=\"float: left; margin-right: 5px;\"></span>Your IP Addresss has been banned from logging on until " + ban.BannedUntil.Value.ToShortTimeString() + "</div>"; login.Visible = false; HAP.Web.Logging.EventViewer.Log("HAP+ Logon", "Home Access Plus+ Logon\n\nBanned logon Username: "******"Logon.Banned", username.Text, Request.UserHostAddress, Request.Browser.Platform, Request.Browser.Browser + " " + Request.Browser.Version, Request.UserHostName, Request.UserAgent); } else { login.Visible = true; message.Text = "<div class=\"ui-state-error ui-corner-all\" style=\" padding: 5px 10px\"><span class=\"ui-icon ui-icon-alert\" style=\"float: left; margin-right: 5px;\"></span>Either your Username or Password was Incorrect or you do not have permission to access this site.</div>"; } Cache.Insert("hapBannedIps", bans); } }
/// <summary> /// Tests whether an integer contains a UserAccountControl flag. /// </summary> /// <param name="accountControlValue">The integer to test.</param> /// <param name="flag">The UserAccountControl flag to look for.</param> public static bool UserAccountControlContains(long accountControlValue, UserAccountControl flag) { if ((accountControlValue & (int)flag) == (int)flag) { // The account control value contains the flag. return true; } else { // The account control value does not contain the flag. return false; } }
/// <summary></summary> public void ToggleUserAccountControl(ADUser user, UserAccountControl uac) { ToggleUserAccountControl(user.ObjectGuid.ToString(), uac); }
/// <summary> /// Gets a string with the name of a User Account Control flag given its value. /// </summary> /// <param name="uac">The value of the User Account Control flag.</param> /// <returns>The name of the flag.</returns> public static string GetUserAccountControlName(UserAccountControl uac) { switch (uac) { case UserAccountControl.Accountdisable: return "ACCOUNTDISABLE"; case UserAccountControl.DontExpirePassword: return "DONT_EXPIRE_PASSWORD"; case UserAccountControl.DontReqPreauth: return "DONT_REQ_PREAUTH"; case UserAccountControl.EncryptedTextPwdAllowed: return "ENCRYPTED_TEXT_PWD_ALLOWED"; case UserAccountControl.HomedirRequired: return "HOMEDIR_REQUIRED"; case UserAccountControl.InterdomainTrustAccount: return "INTERDOMAIN_TRUST_ACCOUNT"; case UserAccountControl.Lockout: return "LOCKOUT"; case UserAccountControl.MNSLogonAccount: return "MNS_LOGON_ACCOUNT"; case UserAccountControl.NormalAccount: return "NORMAL_ACCOUNT"; case UserAccountControl.NotDelegated: return "NOT_DELEGATED"; case UserAccountControl.PartialSecretsAccount: return "PARTIAL_SECRETS_ACCOUNT"; case UserAccountControl.PasswdCantChange: return "PASSWD_CANT_CHANGE"; case UserAccountControl.PasswdNotreqd: return "PASSWD_NOTREQD"; case UserAccountControl.PasswordExpired: return "PASSWORD_EXPIRED"; case UserAccountControl.Script: return "SCRIPT"; case UserAccountControl.ServerTrustAccount: return "SERVER_TRUST_ACCOUNT"; case UserAccountControl.SmartcardRequired: return "SMARTCARD_REQUIRED"; case UserAccountControl.TempDuplicateAccount: return "TEMP_DUPLICATE_ACCOUNT"; case UserAccountControl.TrustedForDelgation: return "TRUSTED_FOR_DELEGATION"; case UserAccountControl.TrustedToAuthForDelegation: return "TRUSTED_TO_AUTH_FOR_DELEGATION"; case UserAccountControl.UseAESKeys: return "USE_AES_KEYS"; case UserAccountControl.UseDESKeyOnly: return "USE_DES_KEY_ONLY"; case UserAccountControl.WorkstationTrustAccount: return "WORKSTATION_TRUST_ACCOUNT"; default: return null; } }
private void treeView1_AfterSelect(object sender, TreeViewEventArgs e) { switch (e.Node.Text) { case "Add": emptyPanel.Controls.Clear(); emptyPanel.Visible = true; UserAccountControl upc = new UserAccountControl(); emptyPanel.Controls.Add(upc); //emptyPanel.Dock = DockStyle.Fill; upc.Show(); //emptyPanel.Controls.Add(upc); break; case "Services and Catalogs": emptyPanel.Controls.Clear(); emptyPanel.Visible = true; ServicesAndCatalogControl sacc = new ServicesAndCatalogControl(); emptyPanel.Controls.Add(sacc); sacc.Show(); break; case "Document": emptyPanel.Controls.Clear(); emptyPanel.Visible = true; TemplateControl temp = new TemplateControl(); emptyPanel.Controls.Add(temp); temp.Show(); break; case "Categories": emptyPanel.Controls.Clear(); emptyPanel.Visible = true; CategoryControl category = new CategoryControl(); emptyPanel.Controls.Add(category); category.Show(); break; case "Schedule List": emptyPanel.Controls.Clear(); emptyPanel.Visible = true; SchedulerControl scl = new SchedulerControl(); emptyPanel.Controls.Add(scl); scl.Show(); break; case "General": emptyPanel.Controls.Clear(); emptyPanel.Visible = true; MessagingControl msgc = new MessagingControl(); emptyPanel.Controls.Add(msgc); msgc.Show(); break; case "TestTest": emptyPanel.Controls.Clear(); emptyPanel.Visible = true; Testing te = new Testing(); emptyPanel.Controls.Add(te); te.Show(); break; default: emptyPanel.Controls.Clear(); emptyPanel.Visible = false; break; } }
public override void ProcessDeploy(String cacheId, PluginConnectorBaseDeployPackage package, Dictionary <String, Object> config, List <PluginConnectorBaseDeployPackageMapping> fieldMapping) { if (!CheckInputConfig(config, true, Log)) { return; } String deployLogShort = ""; String deployLogLong = ""; StringBuilder processLog = new StringBuilder(); PluginLogType logType = PluginLogType.Information; try { List <String> prop = new List <String>(); LDAP ldap = new LDAP(config["ldap_server"].ToString(), config["username"].ToString(), config["password"].ToString(), ""); LDAP.DebugLog reg = new LDAP.DebugLog(delegate(String text) { #if DEBUG Log2(this, PluginLogType.Debug, package.entityId, package.identityId, "LDAP log: " + text, ""); #endif }); ldap.Log += reg; try { ldap.Bind(); } catch (Exception ex) { logType = PluginLogType.Error; processLog.AppendLine("Error on connect to ActiveDirectory: " + ex.Message); Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Error on connect to ActiveDirectory: " + ex.Message, ""); ldap = null; return; } String login = package.login; foreach (PluginConnectorBasePackageData dt in package.pluginData) { if (dt.dataName.ToLower() == "samaccountname") { login = dt.dataValue; } } /*else if (dt.dataName.ToLower() == "displayname") * login = dt.dataValue;*/ if (login == "") { login = package.login; } if (login == "") { logType = PluginLogType.Error; processLog.AppendLine("IAM Login not found in properties list"); Log2(this, PluginLogType.Error, package.entityId, package.identityId, "IAM Login not found in properties list", ""); return; } String container = "";// package.container; String ou_base = (config.ContainsKey("ou_base") ? config["ou_base"].ToString() : ""); if (!String.IsNullOrWhiteSpace(ou_base)) { container += ou_base.TrimEnd("\\ ".ToCharArray()); } if (container == "") { container = "IAMUsers"; } container = container.Trim("\\ ".ToCharArray()); DirectoryEntry baseCN = ldap.DirectoryEntryRoot; if ((container != null) && (container != "")) { baseCN = ldap.AddContainerTree(container); } if (!String.IsNullOrWhiteSpace(package.container)) { container += "\\" + package.container.Trim("\\ ".ToCharArray()); } container = container.Trim("\\ ".ToCharArray()); DirectoryEntry user = null; SearchResultCollection res = ldap.Find(login); DirectoryEntry ct = ldap.DirectoryEntryRoot; if ((container != null) && (container != "")) { ct = ldap.AddContainerTree(container); } #if DEBUG Log2(this, PluginLogType.Debug, package.entityId, package.identityId, "Container = " + ct.Path, ""); Log2(this, PluginLogType.Debug, package.entityId, package.identityId, "Find user? " + (res.Count > 0), ""); StringBuilder users = new StringBuilder(); users.AppendLine("User collection:"); foreach (SearchResult sr in res) { users.AppendLine("\t" + sr.Path); } #endif if (res.Count == 0) { if (package.password == "") { package.password = IAM.Password.RandomPassword.Generate(16); processLog.AppendLine("User not found in AD and IAM Password not found in properties list, creating a random password (" + package.password + ")"); } ldap.AddUser(ct, package.fullName.fullName, login, package.password); res = ldap.Find(login); processLog.AppendLine("User added"); } user = res[0].GetDirectoryEntry(); processLog.AppendLine("User CN: " + user.Path); try { if (container != "IAMUsers") { ldap.ChangeObjectContainer(user, ct); } } catch (Exception ex) { processLog.AppendLine("Error on change user container: " + ex.Message); Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Error on change user container: " + ex.Message, ""); } #if DEBUG Log2(this, PluginLogType.Debug, package.entityId, package.identityId, "User = "******""); #endif UserAccountControl ctrl = (UserAccountControl)user.Properties["useraccountcontrol"][0]; //Limpa as flags que serão verificadas por este sistema if ((ctrl & UserAccountControl.ACCOUNTDISABLE) == UserAccountControl.ACCOUNTDISABLE) { ctrl -= UserAccountControl.ACCOUNTDISABLE; } if ((package.locked) || (package.temp_locked)) { ctrl = (UserAccountControl)((Int32)ctrl + UserAccountControl.ACCOUNTDISABLE); } processLog.AppendLine("User locked? " + (package.locked || package.temp_locked ? "true" : "false")); String[] propNames = new String[user.Properties.PropertyNames.Count]; user.Properties.PropertyNames.CopyTo(propNames, 0); user.Properties["displayname"].Value = package.fullName.fullName; user.Properties["givenName"].Value = package.fullName.givenName; user.Properties["sn"].Value = package.fullName.familyName; user.Properties["userAccountControl"].Value = ctrl; try { try { user.CommitChanges(); } catch (Exception ex) { logType = PluginLogType.Error; processLog.AppendLine("Error on commit user data: " + ex.Message); Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Error on commit user data: " + ex.Message, ""); return; } try { if (!String.IsNullOrWhiteSpace(package.password)) { user.Invoke("SetPassword", (Object)package.password); } user.CommitChanges(); } catch (Exception ex) { logType = PluginLogType.Error; processLog.AppendLine("Error on set user password, check the password complexity rules"); processLog.AppendLine(ex.Message); if (ex.InnerException != null) { processLog.AppendLine(ex.InnerException.Message); } String sPs = ""; try { PasswordStrength ps = CheckPasswordStrength(package.password, package.fullName.fullName); sPs += "Length = " + package.password.Length + Environment.NewLine; sPs += "Contains Uppercase? " + ps.HasUpperCase + Environment.NewLine; sPs += "Contains Lowercase? " + ps.HasLowerCase + Environment.NewLine; sPs += "Contains Symbol? " + ps.HasSymbol + Environment.NewLine; sPs += "Contains Number? " + ps.HasDigit + Environment.NewLine; sPs += "Contains part of the name/username? " + ps.HasNamePart + Environment.NewLine; processLog.AppendLine(sPs); } catch { } Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Error on set user password, check the password complexity rules", ex.Message + (ex.InnerException != null ? " " + ex.InnerException.Message : "") + Environment.NewLine + sPs); return; } //Atribui as outras variáveis processLog.AppendLine("Property update"); try { processLog.AppendLine("\tCompany: " + package.enterprise); processLog.AppendLine("\tCompany exists: " + user.Properties.Contains("company")); if (!String.IsNullOrEmpty(package.enterprise)) { if (user.Properties.Contains("company")) { user.Properties["company"].Value = package.enterprise; } else { user.Properties["company"].Add(package.enterprise); } } user.CommitChanges(); } catch (Exception ex) { processLog.AppendLine("\tError on set user company: " + ex.Message); } //Monta todos os campos que serão inseridos/atualizados Dictionary <String, String> data = new Dictionary <String, String>(); Dictionary <String, String> mostKnolege = GetCommonItems(); foreach (String k in mostKnolege.Keys) { if (!data.ContainsKey(k)) { data.Add(k, null); } } foreach (PropertyValueCollection property in user.Properties) { if (!data.ContainsKey(property.PropertyName.ToLower())) { data.Add(property.PropertyName.ToLower(), null); } } foreach (PluginConnectorBasePackageData dt in package.importsPluginData) { if (data.ContainsKey(dt.dataName.ToLower()) && data[dt.dataName.ToLower()] == null) { data[dt.dataName.ToLower()] = dt.dataValue; //DebugLog(this, PluginLogType.Debug, package.entityId, package.identityId, "1. data[" + dt.dataName.ToLower() + "] = " + dt.dataValue, ""); #if DEBUG processLog.AppendLine("1. data[" + dt.dataName.ToLower() + "] = " + dt.dataValue); #endif } } foreach (PluginConnectorBasePackageData dt in package.pluginData) { if (data.ContainsKey(dt.dataName.ToLower()) && data[dt.dataName.ToLower()] == null) { data[dt.dataName.ToLower()] = dt.dataValue; //DebugLog(this, PluginLogType.Debug, package.entityId, package.identityId, "2. data[" + dt.dataName.ToLower() + "] = " + dt.dataValue, ""); #if DEBUG processLog.AppendLine("2. data[" + dt.dataName.ToLower() + "] = " + dt.dataValue); #endif } } foreach (PluginConnectorBasePackageData dt in package.properties) { if (data.ContainsKey(dt.dataName.ToLower()) && data[dt.dataName.ToLower()] == null) { data[dt.dataName.ToLower()] = dt.dataValue; //DebugLog(this, PluginLogType.Debug, package.entityId, package.identityId, "3. data[" + dt.dataName.ToLower() + "] = " + dt.dataValue, ""); #if DEBUG processLog.AppendLine("3. data[" + dt.dataName.ToLower() + "] = " + dt.dataValue); #endif } } //Remove os ítens protegidos pelo AD, onde a forma de atualização deve ser outra data.Remove("whencreated"); data.Remove("lastlogon"); data.Remove("name"); data.Remove("lockouttime"); data.Remove("useraccountcontrol"); data.Remove("memberof"); data.Remove("distinguishedname"); data.Remove("samaccountname"); data.Remove("displayname"); data.Remove("givenname"); data.Remove("sn"); data.Remove("cn"); foreach (String k in data.Keys) { if (data[k] != null) { try { // SearchResultCollection res2 = ldap.Find(login); user = res2[0].GetDirectoryEntry(); processLog.AppendLine("\t" + k + " exists: " + user.Properties.Contains(k)); if (!String.IsNullOrEmpty(package.enterprise)) { if (user.Properties.Contains(k)) { user.Properties[k].Value = data[k]; } else { user.Properties[k].Add(data[k]); } } user.CommitChanges(); } catch (Exception ex) { processLog.AppendLine("\tError setting data '" + k + "': " + ex.Message); } } } processLog.AppendLine("RBAC"); //Busca o usuário novamente //Para não aplicas as informações incorretas //Devido a definição das propriedades anteriores res = ldap.Find(login); user = res[0].GetDirectoryEntry(); //Executa as ações do RBAC if ((package.pluginAction != null) && (package.pluginAction.Count > 0)) { foreach (PluginConnectorBaseDeployPackageAction act in package.pluginAction) { try { processLog.AppendLine("\tRole: " + act.roleName + " (" + act.actionType.ToString() + ") " + act.ToString()); switch (act.actionKey.ToLower()) { case "group": if (act.actionType == PluginActionType.Add) { String grpCN = ldap.FindOrCreateGroup(baseCN, act.actionValue); if (ldap.addUserToGroup(user.Name, grpCN)) { processLog.AppendLine("\tUser added in group " + act.actionValue + " by role " + act.roleName); } } else if (act.actionType == PluginActionType.Remove) { String grpCN = ldap.FindOrCreateGroup(baseCN, act.actionValue); if (ldap.removeUserFromGroup(user.Name, grpCN)) { processLog.AppendLine("\tUser removed from group " + act.actionValue + " by role " + act.roleName); } } break; default: processLog.AppendLine("\tAction not recognized: " + act.actionKey); break; } } catch (Exception ex) { processLog.AppendLine("\tError on execute action (" + act.actionKey + "): " + ex.Message); Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Error on execute action (" + act.actionKey + "): " + ex.Message, ""); } } } } finally { user.Close(); } NotityChangeUser(this, package.entityId); if (package.password != "") { processLog.AppendLine("User updated with password"); } else { processLog.AppendLine("User updated without password"); } } catch (Exception ex) { logType = PluginLogType.Error; processLog.AppendLine("Error on process deploy: " + ex.Message); Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Error on process deploy: " + ex.Message, ""); } finally { Log2(this, logType, package.entityId, package.identityId, "Deploy executed", processLog.ToString()); processLog.Clear(); processLog = null; } }
public override PluginConnectorBaseFetchResult FetchFields(Dictionary <String, Object> config) { PluginConnectorBaseFetchResult ret = new PluginConnectorBaseFetchResult(); LogEvent iLog = new LogEvent(delegate(Object sender, PluginLogType type, string text) { if (Log != null) { Log(sender, type, text); } }); if (!CheckInputConfig(config, true, iLog, true, true)) { ret.success = false; return(ret); } List <PluginConfigFields> cfg = new List <PluginConfigFields>(); PluginConfigFields[] tmpF = this.GetConfigFields(); foreach (PluginConfigFields cf in tmpF) { try { iLog(this, PluginLogType.Information, "Field " + cf.Name + " (" + cf.Key + "): " + (config.ContainsKey(cf.Key) ? config[cf.Key].ToString() : "empty")); } catch (Exception ex) { iLog(this, PluginLogType.Information, "Field " + cf.Name + " (" + cf.Key + "): error on get data -> " + ex.Message); } } String ldapServer = config["ldap_server"].ToString(); String username = config["username"].ToString(); String password = config["password"].ToString(); //Create a dictionary with the most knolege properties Dictionary <String, String> mostKnolege = GetCommonItems(); foreach (String k in mostKnolege.Keys) { if (!ret.fields.ContainsKey(k)) { ret.fields.Add(k, new List <string>()); } ret.fields[k].Add(mostKnolege[k]); } try { DirectoryEntry entry = new DirectoryEntry("LDAP://" + ldapServer, username, password, AuthenticationTypes.Secure); DirectorySearcher search = new DirectorySearcher(entry); search.SearchScope = SearchScope.Subtree; //search.Filter = "(&(objectClass=user)(sAMAccountName=helvio.junior))"; search.Filter = "(samAccountType=805306368)"; search.PropertiesToLoad.Add("distinguishedName"); search.PropertiesToLoad.Add("company"); search.PropertiesToLoad.Add("department"); SearchResultCollection result = search.FindAll(); if (result != null) { Int32 count = 0; foreach (SearchResult sr in result) { if (count >= 20) { break; } try { DirectoryEntry entry1 = new DirectoryEntry("LDAP://" + ldapServer + "/" + sr.Properties["distinguishedName"][0].ToString(), username, password); entry1.AuthenticationType = AuthenticationTypes.Secure; foreach (PropertyValueCollection property in entry1.Properties) { if (!ret.fields.ContainsKey(property.PropertyName)) { ret.fields.Add(property.PropertyName, new List <string>()); } //Separa os itens que mecessita algum tratamento switch (property.PropertyName.ToLower()) { case "lastlogon": case "whencreated": case "lockouttime": try { Int64 tmp = Int64.Parse(property[0].ToString()); DateTime tmp2 = DateTime.FromFileTime(tmp); if (tmp2.Year > 1970) //Se a data for inferior nem envia { ret.fields[property.PropertyName].Add(tmp2.ToString("yyyy-MM-dd HH:mm:ss")); } } catch (Exception ex) { } break; case "useraccountcontrol": foreach (Object p1 in property) { UserAccountControl ctrl = (UserAccountControl)p1; foreach (UserAccountControl c in Enum.GetValues(typeof(UserAccountControl))) { //Verifica se está utilizando if ((ctrl & c) == c) { ret.fields[property.PropertyName].Add(c.ToString()); } } } break; default: foreach (Object p1 in property) { ret.fields[property.PropertyName].Add(p1.ToString()); } break; } } count++; } catch (Exception ex) { iLog(this, PluginLogType.Error, "Erro ao importar o registro (" + sr.Path + "): " + ex.Message); } } } ret.success = true; search.Dispose(); } catch (Exception ex) { iLog(this, PluginLogType.Error, ex.Message); } return(ret); }
public override void ProcessImport(String cacheId, String importId, Dictionary <String, Object> config, List <PluginConnectorBaseDeployPackageMapping> fieldMapping) { if (!CheckInputConfig(config, true, Log)) { return; } List <String> prop = new List <String>(); String ldapServer = config["ldap_server"].ToString(); String username = config["username"].ToString(); String password = config["password"].ToString(); String ou_base = (config.ContainsKey("ou_base") ? config["ou_base"].ToString() : ""); String _dnBase = ""; LDAP ldap = new LDAP(ldapServer, username, password, _dnBase); LDAP.DebugLog reg = new LDAP.DebugLog(delegate(String text) { #if DEBUG //Log2(this, PluginLogType.Debug, package.entityId, package.identityId, "LDAP log: " + text, ""); #endif }); ldap.Log += reg; try { ldap.Bind(); } catch (Exception ex) { Log(this, PluginLogType.Error, "Error on connect to ActiveDirectory: " + ex.Message); Log2(this, PluginLogType.Error, 0, 0, "Error on connect to ActiveDirectory: " + ex.Message, ""); ldap = null; return; } DirectoryEntry entry = null; try { //Caso haja o ou_base, buscar/criar a OU para listar os usuários if (!String.IsNullOrWhiteSpace(ou_base)) { entry = ldap.AddContainerTree(ou_base); } } catch { } //Realiza a busca de todas as OUs e grupos if (ImportPackageStruct != null) { PluginConnectorBaseImportPackageStruct structPackage = new PluginConnectorBaseImportPackageStruct(importId); try { if (entry == null) { entry = ldap.DirectoryEntryRoot; } DirectorySearcher search = new DirectorySearcher(entry); search.SearchScope = SearchScope.Subtree; search.Filter = "(objectCategory=group)"; search.PropertiesToLoad.Add("distinguishedName"); search.PropertiesToLoad.Add("name"); SearchResultCollection result = search.FindAll(); if (result != null) { foreach (SearchResult sr in result) { try { structPackage.AddGroup(sr.Properties["name"][0].ToString()); } catch (Exception ex) { Log(this, PluginLogType.Error, "Erro ao listar o grupo (" + sr.Path + "): " + ex.Message); } finally { } } } search.Dispose(); } catch (Exception ex) { Log(this, PluginLogType.Error, ex.Message); } try { if (entry == null) { entry = ldap.DirectoryEntryRoot; } DirectorySearcher search = new DirectorySearcher(entry); search.SearchScope = SearchScope.Subtree; search.Filter = "(objectClass=organizationalUnit)"; search.PropertiesToLoad.Add("distinguishedName"); search.PropertiesToLoad.Add("name"); SearchResultCollection result = search.FindAll(); if (result != null) { foreach (SearchResult sr in result) { try { /* * String dn = sr.Properties["distinguishedName"][0].ToString(); * //String name = sr.Properties["name"][0].ToString(); * String[] ou = dn.Replace(entry.Properties["distinguishedName"][0].ToString(), "").Replace(",", "").Replace("OU=", "\\").Trim(" ,".ToCharArray()).Split("\\".ToCharArray()); * * Array.Reverse(ou); * * String path = "\\" + String.Join("\\", ou);*/ structPackage.AddContainer(DNToPath(sr.Properties["distinguishedName"][0].ToString(), entry)); } catch (Exception ex) { Log(this, PluginLogType.Error, "Erro ao listar a OU (" + sr.Path + "): " + ex.Message); } finally { } } } search.Dispose(); } catch (Exception ex) { Log(this, PluginLogType.Error, ex.Message); } //Envia o pacote da estrutura ImportPackageStruct(structPackage); } //Realiza a busca dos usuários try { //DirectoryEntry entry = new DirectoryEntry("LDAP://" + ldapServer, username, password, AuthenticationTypes.Secure); if (entry == null) { entry = ldap.DirectoryEntryRoot; } DirectorySearcher search = new DirectorySearcher(entry); search.SearchScope = SearchScope.Subtree; //search.Filter = "(&(objectClass=user)(sAMAccountName=helvio.junior))"; search.Filter = "(samAccountType=805306368)"; search.PropertiesToLoad.Add("useraccountcontrol"); search.PropertiesToLoad.Add("distinguishedName"); search.PropertiesToLoad.Add("company"); search.PropertiesToLoad.Add("department"); search.PropertiesToLoad.Add("memberOf"); foreach (PluginConnectorBaseDeployPackageMapping m in fieldMapping) { if (!search.PropertiesToLoad.Contains(m.dataName)) { search.PropertiesToLoad.Add(m.dataName); } } /* * search.PropertiesToLoad.Add("displayName"); * search.PropertiesToLoad.Add("mail"); * search.PropertiesToLoad.Add("sAMAccountName"); * search.PropertiesToLoad.Add("objectClass"); * search.PropertiesToLoad.Add("distinguishedName"); * search.PropertiesToLoad.Add("lastLogonTimestamp"); * search.PropertiesToLoad.Add("whenCreated"); * * search.PropertiesToLoad.Add("lockoutTime"); * search.PropertiesToLoad.Add("proxyAddresses"); * search.PropertiesToLoad.Add("mailNickname"); * search.PropertiesToLoad.Add("telephoneNumber"); * search.PropertiesToLoad.Add("userPrincipalName"); * search.PropertiesToLoad.Add("memberOf");*/ SearchResultCollection result = search.FindAll(); if (result != null) { foreach (SearchResult sr in result) { PluginConnectorBaseImportPackageUser package = new PluginConnectorBaseImportPackageUser(importId); try { using (DirectoryEntry entry1 = new DirectoryEntry("LDAP://" + ldapServer + "/" + sr.Properties["distinguishedName"][0].ToString(), username, password)) { entry1.AuthenticationType = AuthenticationTypes.Secure; String ou = entry1.Parent.Path; ou = ou.Replace("LDAP://" + ldapServer + "/", ""); package.container = DNToPath(ou, entry); if (fieldMapping.Exists(f => (f.dataName == "organizationslUnit")) || fieldMapping.Exists(f => (f.dataName == "organizationslunit"))) { package.AddProperty("organizationslUnit", ou, "string"); } } foreach (String p in sr.Properties.PropertyNames) { //Separa os itens que mecessita algum tratamento switch (p.ToLower()) { case "lastlogon": case "whencreated": case "lockouttime": try { Int64 tmp = Int64.Parse(sr.Properties[p][0].ToString()); DateTime tmp2 = DateTime.FromFileTime(tmp); if (tmp2.Year > 1970) //Se a data for inferior nem envia { package.AddProperty(p, tmp2.ToString("o"), (fieldMapping.Exists(f => (f.dataName == p)) ? fieldMapping.Find(f => (f.dataName == p)).dataType : "datetime")); } } catch (Exception ex) { } break; case "useraccountcontrol": foreach (Object p1 in sr.Properties[p]) { UserAccountControl ctrl = (UserAccountControl)p1; foreach (UserAccountControl c in Enum.GetValues(typeof(UserAccountControl))) { //Verifica se está utilizando if ((ctrl & c) == c) { package.AddProperty(p, c.ToString(), (fieldMapping.Exists(f => (f.dataName == p)) ? fieldMapping.Find(f => (f.dataName == p)).dataType : "string")); } } } break; case "memberof": foreach (Object p1 in sr.Properties[p]) { //Trata o grupo try { using (DirectoryEntry entry1 = new DirectoryEntry("LDAP://" + ldapServer + "/" + p1.ToString(), username, password)) { entry1.AuthenticationType = AuthenticationTypes.Secure; package.AddGroup(entry1.Properties["name"][0].ToString()); } } catch { } if (fieldMapping.Exists(m => (m.dataName == "memberOf"))) { package.AddProperty(p, p1.ToString(), (fieldMapping.Exists(f => (f.dataName == p)) ? fieldMapping.Find(f => (f.dataName == p)).dataType : "string")); } } break; default: foreach (Object p1 in sr.Properties[p]) { package.AddProperty(p, p1.ToString(), (fieldMapping.Exists(f => (f.dataName == p)) ? fieldMapping.Find(f => (f.dataName == p)).dataType : "string")); } break; } } ImportPackageUser(package); } catch (Exception ex) { Log(this, PluginLogType.Error, "Erro ao importar o registro (" + sr.Path + "): " + ex.Message); } finally { package.Dispose(); package = null; } } } search.Dispose(); } catch (Exception ex) { Log(this, PluginLogType.Error, ex.Message); } }
/// <summary></summary> public void ClearUserAccountControl(ADUser user, UserAccountControl uac) { ClearUserAccountControl(user.ObjectGuid.ToString(), uac); }