private static string Property( this LdapEntry entry, Context context, string name, string pattern = null) { var logs = new Logs() { new Log("entry", entry.DN), new Log("propertyName", name) }; if (!name.IsNullOrEmpty()) { try { return(entry.getAttribute(name)?.StringValue != null ? pattern.IsNullOrEmpty() ? entry.getAttribute(name).StringValue : entry.getAttribute(name).StringValue.RegexFirst(pattern) : string.Empty); } catch (Exception e) { new SysLogModel(context: context, e: e, logs: logs); } } return(string.Empty); }
private string GetEntryAttribute(LdapEntry ldapEntry, string attributeName) { try { if (attributeName.ToLower() == "objectguid") { var attValue = ldapEntry.getAttribute(attributeName); if (attValue != null) { return(new Guid((Byte[])(Array)attValue.ByteValue).ToString()); } else { return(""); } } else { return(ldapEntry.getAttribute(attributeName)?.StringValue ?? ""); } } catch (Exception) { //we are just eating this error on a specific attribute, Not a real reason why to stopped the process // unless its is required value that must be use somewhere else, but so far we are just displaying info only. return(""); //throw; } }
private ActiveDirectoryUser SearchUser(string username) { var currentUser = new ActiveDirectoryUser(); var lsc = connection.Search( adUri.AbsolutePath.Substring(1), LdapConnection.SCOPE_SUB, $"(sAMAccountName={(username.Contains("\\") ? username.Split('\\').Last() : username)})", new[] { "name", "userPrincipalName", "sAMAccountName", "employeeID", "extensionAttribute1" }, false); while (lsc.hasMore()) { LdapEntry nextEntry = null; try { nextEntry = lsc.next(); } catch (LdapException) { continue; } currentUser.Name = nextEntry.getAttribute("name")?.StringValue; currentUser.Email = nextEntry.getAttribute("userPrincipalName")?.StringValue; currentUser.NameIdentifier = nextEntry.getAttribute("sAMAccountName")?.StringValue; currentUser.EmployeeID = nextEntry.getAttribute("employeeID")?.StringValue; return(currentUser); } return(null); }
public void SetBaseDetails(LdapEntry ldapEntry, string providerName) { DisplayName = ldapEntry.getAttribute("displayname").StringValue; UserName = ldapEntry.getAttribute("cn").StringValue; Email = ldapEntry.getAttribute("mail").StringValue; Location = ldapEntry.getAttribute("location").StringValue; ProviderName = providerName; SubjectId = UserName; }
public ActionResult <HashSet <object> > GetUsersWithActiveDirectory([FromBody] SampekeyUserAccountRequest value) { var users = new HashSet <object>(); try { using (var connection = new LdapConnection { SecureSocketLayer = false }) { var _domain = Environment.GetEnvironmentVariable("AD_DDOMAIN"); var _domainServer = Environment.GetEnvironmentVariable("AD_DDOMAIN_SSERVER"); var _port = Environment.GetEnvironmentVariable("AD_PORT"); connection.Connect(_domainServer, int.Parse(_port)); connection.Bind($"{value.UserName}@{_domain}", value.Password); LdapSearchResults searchResults = connection.Search( Environment.GetEnvironmentVariable("BIND_DN"), LdapConnection.SCOPE_SUB, Environment.GetEnvironmentVariable("LDAP_FILTER"), null, false ); while (searchResults.hasMore()) { LdapEntry nextEntry = null; nextEntry = searchResults.next(); nextEntry.getAttributeSet(); var attr = nextEntry.getAttribute("mail"); if (attr == null) { users.Add(nextEntry.getAttribute("distinguishedName").StringValue); } else { users.Add(new{ Email = nextEntry.getAttribute("mail").StringValue, UserName = nextEntry.getAttribute("sAMAccountName").StringValue }); } } return(users); } } catch { return(users); } /* * HashSet<string> data = account.GetUsersWithActiveDirectory(value); * return Ok(data); */ }
public static string Credenciales(string usuario, string contraseña) { string[] prueba = new string[20]; string acceso = ""; try { string email = null; string rol = null; if (usuario != "u00000000" && usuario != "u12345678") { string ldapHost = "ldap.uca.es"; int ldapPort = 389; string loginDN = "CN=" + usuario + ",dc=uca,dc=es"; LdapConnection conn = new LdapConnection(); conn.Connect(ldapHost, ldapPort); conn.Bind(loginDN, contraseña); if (conn.Bound) { string searchBase = "CN=" + usuario + ",dc=uca,dc=es"; string searchFilter = "tipodocumento=NIF"; LdapSearchResults lsc = conn.Search(searchBase, LdapConnection.SCOPE_BASE, searchFilter, null, false); LdapEntry nextEntry = lsc.next(); email = nextEntry.getAttribute("mail").StringValue; rol = nextEntry.getAttribute("ou").StringValue; } } else { email = "*****@*****.**"; rol = "PDI"; } prueba = Insertar(7, usuario, null, null, null, null, null, null, null, null); acceso = prueba[0]; if (acceso == "0") { Insertar(10, usuario, email, rol, null, null, null, null, null, null); } if (acceso == "1") { acceso = "2"; } if (acceso == "0") { acceso = "1"; } } catch (LdapException e) { Console.WriteLine(e); } return(acceso); }
/// <summary> /// Checks if the user's password has expired /// </summary> /// <param name="entry">LdapEntry</param> /// <returns>true - password expired/false - password still valid or no policy</returns> private bool IsPasswordExpired(LdapEntry entry, out int daysUntilExpired) { bool passwordExpired = false; daysUntilExpired = -1; LdapAttribute attr = entry.getAttribute("userAccountControl"); if (attr != null) { // Check account control to see if the password is set to never expire. int accountControl = int.Parse(attr.StringValue); if ((accountControl & (int)ADS_USER_FLAGS.DONT_EXPIRE_PASSWD) != (int)ADS_USER_FLAGS.DONT_EXPIRE_PASSWD) { attr = entry.getAttribute("pwdLastSet"); if (attr != null) { long pwdLastSetVal = long.Parse(attr.StringValue); if (pwdLastSetVal == 0) { passwordExpired = true; } else { // Convert the value to a local time value. DateTime pwdLastSet = new DateTime(timeDelta + pwdLastSetVal).ToLocalTime(); DateTime pwdExpires = pwdLastSet - maxPwdAge; if (pwdExpires < DateTime.Now) { passwordExpired = true; } else { try { TimeSpan pwdExpiresIn = pwdExpires - DateTime.Now; daysUntilExpired = pwdExpiresIn.Days; } catch (Exception ex) { // In some scenarios "pwdExpires - DateTime.Now" result is too big // to fit into TimeSpan variable. In this case exception is logged and // default value is set for daysUntilExpired log.Debug("Exception occured {0}:{1} while calculating daysUntilExpired", ex.Message, ex.StackTrace); daysUntilExpired = defaultdaysUntilExpired; } } } } } } return(passwordExpired); }
public ADInfo(string accountName, LdapEntry entry) { AccountName = accountName; try { FirstName = entry.getAttribute("givenName").StringValue; } catch { FirstName = "?"; } try { LastName = entry.getAttribute("SN").StringValue; } catch { LastName = "?"; } try { Email = entry.getAttribute("MAIL").StringValue; } catch { Email = "?"; } try { var groups = entry.getAttribute("MEMBEROF"); foreach (var value in groups.StringValueArray) { string this_value = value; if (this_value.Contains(",")) { this_value = value.Substring(0, this_value.IndexOf(",", StringComparison.Ordinal)); } if (this_value.ToUpper().StartsWith("CN=", StringComparison.Ordinal)) { this_value = this_value.Substring(3); } Groups.Add(this_value); } } catch { } }
public void ToLdapEntity_Value() { LdapEntry entry = Generators.CreateEntry(); var entity = entry.ToLdapEntity <LdapUser>(_mapper); Assert.Multiple(() => { Assert.AreEqual(entry.DN, entity.DistinguishedName); Assert.AreEqual(entry.getAttribute("dn").StringValue, entity.DistinguishedName); Assert.AreEqual(entry.getAttribute("cn").StringValue, entity.CommonName); Assert.AreEqual(entry.getAttribute("gn").StringValue, entity.GivenName); }); }
public void ToNovellEntry_Value() { LdapUser entity = Generators.CreateUser(); LdapEntry entry = entity.ToNovellEntry(_mapper); Assert.Multiple(() => { Assert.AreEqual(entity?.DistinguishedName, entry.DN); Assert.AreEqual(entity?.DistinguishedName, entry.getAttribute("dn").StringValue); Assert.AreEqual(entity?.CommonName, entry.getAttribute("cn").StringValue); Assert.AreEqual(entity?.GivenName, entry.getAttribute("gn").StringValue); }); }
private static LDAPUserParameters GetUserParameter(LdapConnection ldap, string username) { try { //user daten parameter lesen - frage: daten nur holen, wenn noch nicht registriert oder sollen die daten immer verwendet werden und u.U auch in sofi aktualisiert werden string[] attributesToReturn = new string[] { "displayName", "sn", "givenName", "cn", "mail", "ou", "gidNumber", "Uid" }; string sMail = ""; string sDisplayName = ""; string sFirstName = ""; string sLastName = ""; string sStudiengang = ""; string sStudiengangKuerzel = ""; string sPersonalBezeichnung = ""; var queue = ldap.Search(ATTRIBUTES, LdapConnection.SCOPE_SUB, string.Format("(Uid={0})", username), attributesToReturn, false); LdapEntry entry = queue.Next(); if (entry != null) { sMail = entry.getAttribute("mail").StringValue ?? string.Empty; sLastName = entry.getAttribute("sn").StringValue ?? string.Empty; sFirstName = entry.getAttribute("givenName").StringValue ?? string.Empty; // sDisplayName = entry.getAttribute("displayName").StringValue ?? string.Format("{0} {1}", sFirstName, sLastName); string iGidNumber = entry.getAttribute("gidNumber").StringValue ?? string.Empty; // 101=Technikum, 102=Student sStudiengang = ""; sStudiengangKuerzel = ""; sPersonalBezeichnung = ""; var oOu = entry.getAttribute("ou"); if (iGidNumber == "101" || iGidNumber == "120") //tw-personal & FH Admin { sPersonalBezeichnung = "Teacher"; } else if (oOu != null && oOu.size() > 0 && iGidNumber == "102") //student { sStudiengang = oOu.StringValueArray[1]; sStudiengangKuerzel = oOu.StringValueArray[2]; } } return(new LDAPUserParameters(true, sFirstName, sLastName, sDisplayName, sMail, sStudiengang, sStudiengangKuerzel, sPersonalBezeichnung)); } catch { return(new LDAPUserParameters()); } }
/// <summary>Gets the value of the given attribute for the given /// entry. /// </summary> /// <param name="le">LdapEntry</param> /// <param name="attrs">List of attributes to lookup</param> /// <returns>A list of attribute values</returns> public string[] GetAttributeValuesFromEntry(LdapEntry le, string[] attrs) { if (le == null || attrs == null) { throw new ArgumentNullException(); } List <string> retVal = new List <string> (); foreach (string n in attrs) { LdapAttribute la = le.getAttribute(n); if (la != null) { retVal.Add(la.StringValue); } else { retVal.Add(""); } } return(retVal.ToArray()); }
public static object GetAttributeValue(this LdapEntry ldapEntry, string attributeName, bool getBytes = false) { var attribute = ldapEntry.getAttribute(attributeName); if (attribute == null) { return(null); } if (!(string.Equals(attributeName, LdapConstants.ADSchemaAttributes.OBJECT_SID, StringComparison.OrdinalIgnoreCase) || getBytes)) { return(attribute.StringValue); } if (attribute.ByteValue == null) { return(null); } var value = new byte[attribute.ByteValue.Length]; Buffer.BlockCopy(attribute.ByteValue, 0, value, 0, attribute.ByteValue.Length); if (getBytes) { return(value); } return(DecodeSid(value)); }
/// <summary> /// Gets the ldap GUID /// </summary> /// <param name="entry">object entry</param> /// <returns>ldap GUID as string</returns> private string GetLdapGuid(LdapEntry entry) { string ldapGuid = null; try { LdapAttribute guidAttr = entry.getAttribute("objectGUID"); if (guidAttr != null && guidAttr.StringValue.Length != 0) { byte[] bGuid = new byte[8]; for (int i = 0; i < 8; i++) { bGuid[i] = (byte)guidAttr.ByteValue[i]; } Guid cGuid = new Guid( BitConverter.ToInt32(bGuid, 0), BitConverter.ToInt16(bGuid, 4), BitConverter.ToInt16(bGuid, 6), (byte)guidAttr.ByteValue[8], (byte)guidAttr.ByteValue[9], (byte)guidAttr.ByteValue[10], (byte)guidAttr.ByteValue[11], (byte)guidAttr.ByteValue[12], (byte)guidAttr.ByteValue[13], (byte)guidAttr.ByteValue[14], (byte)guidAttr.ByteValue[15]); ldapGuid = cGuid.ToString(); } } catch {} return(ldapGuid); }
/// <summary> /// Process the users, groups and container through this ldap connection /// </summary> /// <param name="conn">ldap connection</param> /// <param name="settings">ldapsettings</param> private void ProcessSearchObjects(LdapConnection conn, LdapSettings settings) { foreach (string searchContext in settings.SearchContexts) { string[] searchAttributes = { "objectClass" }; log.Debug("SearchObject: " + searchContext); try { LdapEntry ldapEntry = conn.Read(searchContext, searchAttributes); LdapAttribute attrObjectClass = ldapEntry.getAttribute("objectClass"); String[] values = attrObjectClass.StringValueArray; if (IsUser(values) == true) { // Process SearchDN as log.Debug("Processing User Object..."); ProcessSearchUser(conn, searchContext); } else if (IsGroup(values) == true) { // Process SearchDN as log.Debug("Processing Group Object..."); ProcessSearchGroup(conn, searchContext); } else if (IsContainer(values) == true) { // Process SearchDN as Container log.Debug("Processing Container Object..."); ProcessSearchContainer(conn, searchContext); } else { log.Debug("Invalid objectClass: " + values[0]); log.Debug(attrObjectClass.ToString()); } } catch (SimiasShutdownException s) { log.Error("ProcessSearchObjects SimiasShutdownException"); log.Error(s.Message); throw s; } catch (LdapException e) { log.Error("ProcessSearchObjects LdapException"); log.Error(e.LdapErrorMessage); log.Error(e.StackTrace); throw e; } catch (Exception e) { log.Error("ProcessSearchObjects Exception"); log.Error(e.Message); log.Error(e.StackTrace); throw e; } } }
public CreateEntryDialog(Connection connection, LdapEntry le) { if (connection == null) { throw new ArgumentNullException("connection"); } if (le == null) { throw new ArgumentNullException("le"); } conn = connection; Init(); LdapAttribute la = le.getAttribute("objectClass"); foreach (string s in la.StringValueArray) { attrListStore.AppendValues("objectClass", s, "Optional"); _objectClass.Add(s); } showAttributes(); createEntryDialog.Run(); while (errorOccured) { createEntryDialog.Run(); } createEntryDialog.Destroy(); }
public static string Guid(this LdapEntry entry) { var bytes = (byte[])(entry.getAttribute("objectGUID").ByteValue as object); var guid = new Guid(bytes); return(guid.ToString()); }
/// <summary> /// Checks if the user's password has expired /// </summary> /// <param name="entry">LdapEntry</param> /// <returns>true - password expired/false - password still valid or no policy</returns> private bool LoginPasswordExpired(LdapEntry entry) { bool expired = false; LdapAttribute attrExpiration = entry.getAttribute("passwordExpirationTime"); if (attrExpiration != null) { char[] exp = attrExpiration.StringValue.ToCharArray(); DateTime expiredPolicy = new DateTime( Convert.ToInt32(new String(exp, 0, 4)), Convert.ToInt32(new String(exp, 4, 2)), Convert.ToInt32(new String(exp, 6, 2)), Convert.ToInt32(new String(exp, 8, 2)), Convert.ToInt32(new String(exp, 10, 2)), Convert.ToInt32(new String(exp, 12, 2))); if (DateTime.UtcNow > expiredPolicy) { expired = true; } } return(expired); }
private Org SyncOrgFromEntry(LdapEntry rootEntry, Org parentOrg, LdapEntry entry) { string orgId = entry.Guid().ToLower(); Org org = this._org.GetOrgById(orgId) as Org; if (org != null) { if (entry.ContainsAttr("ou")) { org.Name = entry.getAttribute("ou").StringValue + string.Empty; } //设置其他属性的值 _org.UpdateOrg(org); return(org); } org = new Org { Id = orgId, ParentId = parentOrg.Id, }; //设置其他属性的值 this._org.AddOrg(org); return(org); }
void OnSaveBinaryValueActivate(object o, EventArgs args) { FileChooserDialog fcd = new FileChooserDialog( Mono.Unix.Catalog.GetString("Save binary as"), Gtk.Stock.Save, null, FileChooserAction.Save); fcd.AddButton(Gtk.Stock.Cancel, ResponseType.Cancel); fcd.AddButton(Gtk.Stock.Save, ResponseType.Ok); fcd.SelectMultiple = false; ResponseType response = (ResponseType)fcd.Run(); if (response == ResponseType.Ok) { string attributeName = GetAttributeName(); LdapEntry le = conn.Data.GetEntry(currentDN); LdapAttribute la = le.getAttribute(attributeName); WriteBytesToFile(fcd.Filename, SupportClass.ToByteArray(la.ByteValue)); } fcd.Destroy(); }
/// <summary> /// Searches an entry in the Ldap directory and returns the attribute value /// </summary> /// <param name="attrName">attribute whose value is required</param> /// <returns> value of the attribute stored in Ldap directory</returns> private string FindAttrValue(string attrName) { string aValue = null; string[] attrs = { attrName }; LdapSearchResults lsc = conn.Search(Fdn, LdapConnection.SCOPE_BASE, "objectClass=*", attrs, false); while (lsc.hasMore()) { LdapEntry nextEntry = null; try { nextEntry = lsc.next(); } catch (LdapException e) { // Exception is thrown, go for next entry throw e; } LdapAttribute attribute = nextEntry.getAttribute(attrName); aValue = attribute.StringValue; break; } return(aValue); }
void OnAddBinaryValueActivate(object o, EventArgs args) { FileChooserDialog fcd = new FileChooserDialog( Mono.Unix.Catalog.GetString("Select file to add as binary attribute"), Gtk.Stock.Open, null, FileChooserAction.Open); fcd.AddButton(Gtk.Stock.Cancel, ResponseType.Cancel); fcd.AddButton(Gtk.Stock.Open, ResponseType.Ok); fcd.SelectMultiple = false; ResponseType response = (ResponseType)fcd.Run(); if (response == ResponseType.Ok) { byte[] fileBytes = ReadFileBytes(fcd.Filename); if (fileBytes.Length == 0) { return; } string attributeName = GetAttributeName(); string attributeValue = Base64.encode(SupportClass.ToSByteArray(fileBytes)); LdapEntry le = conn.Data.GetEntry(currentDN); LdapAttribute la = le.getAttribute(attributeName); bool existing = false; if (la != null) { existing = true; } LdapAttribute newla = new LdapAttribute(attributeName); newla.addBase64Value(attributeValue); LdapModification lm; if (existing) { lm = new LdapModification(LdapModification.REPLACE, newla); } else { lm = new LdapModification(LdapModification.ADD, newla); } List <LdapModification> modList = new List <LdapModification> (); modList.Add(lm); Util.ModifyEntry(conn, currentDN, modList.ToArray()); this.Show(conn, conn.Data.GetEntry(currentDN), displayAll); } fcd.Destroy(); }
private static bool Enabled(LdapEntry entry, ParameterAccessor.Parts.Ldap ldap) { var accountDisabled = 2; return (!ldap.LdapExcludeAccountDisabled || (entry.getAttribute("UserAccountControl")?.StringValue.ToLong() & accountDisabled) == 0); }
public static string GetStringValue(this LdapEntry entry, string key) { var attr = entry.getAttribute(key); return(attr == null || string.IsNullOrEmpty(attr.StringValue) ? "" : attr.StringValue); }
public static string AttrStringValue(this LdapEntry entry, string attrName) { if (!entry.ContainsAttr(attrName)) { return(string.Empty); } return(entry.getAttribute(attrName).StringValue); }
private User GetUserInActiveDirectory(string username, string password) { User user = null; _connection.Connect(_ldapconfig.Hostname, LdapConnection.DEFAULT_SSL_PORT); _connection.Bind(string.IsNullOrWhiteSpace(_ldapconfig.Domain) ? username : $"{_ldapconfig.Domain}\\{username}", password); var resultSearch = _connection.Search( _ldapconfig.SearchBase, LdapConnection.SCOPE_SUB, string.Format(_ldapconfig.SearchFilter, username), new[] { "displayName", "sAMAccountName", "mail" }, false ); try { LdapEntry userAD = resultSearch.next(); if (userAD != null) { _connection.Bind(userAD.DN, password); if (_connection.Bound) { user = new User { Name = userAD.getAttribute("displayName").StringValue, Identity = userAD.getAttribute("sAMAccountName").StringValue, Email = userAD.getAttribute("mail").StringValue }; } //get roles List <string> groups = GetRoles(username).ToList(); IEnumerable <string> roles = groups.Where(stringToCheck => stringToCheck.Contains(_appConfig.RoleSystem)); user.Role = roles.Contains(_appConfig.RoleSystemAdm) ? "manager" : "user"; } } catch { throw new Exception("Login failed."); } return(user); }
private string ldapUserAccountControlValue(LdapEntry ldapUser) { int flags = int.Parse(ldapUser.getAttribute("userAccountControl")?.StringValue ?? "0"); string value = ""; switch (flags) { default: value = flags.ToString(); break; case 512: value = "Enabled Account"; break; case 514: value = "Disabled Account"; break; case 528: value = "Locked Out"; break; case 544: value = "Enabled, Password Not Required"; break; case 546: value = "Disabled, Password Not Required"; break; case 66048: value = "Enabled, Password Doesn't Expire"; break; case 66050: value = "Disabled, Password Doesn't Expire"; break; case 66080: value = "Enabled, Password Doesn't Expire & Not Required"; break; case 66082: value = "Disabled, Password Doesn't Expire & Not Required"; break; case 2080: value = "Interdomain Trust Account"; break; case 4194816: value = "Enabled, This account does not require Kerberos pre-authentication"; break; case 524800: value = "Enabled, Trusted For Delegation"; break; case 590336: value = "Enabled, Password Doesn't Expire & Password cannot be changed"; break; } return value; }
public static string[] GetAttributeArrayValue(this LdapEntry ldapEntry, string attributeName) { LdapAttribute attribute = ldapEntry.getAttribute(attributeName); if (attribute == null) { return(null); } return(attribute.StringValueArray); }
public User Login(string username, string password) { //TODO временно _connection.UserDefinedServerCertValidationDelegate += new Novell.Directory.Ldap.RemoteCertificateValidationCallback(MySSLHandler); _connection.Connect(_config.Url, _config.Port); _connection.Bind(_config.BindDn, _config.BindCredentials); // string searchFilter = $"(&(objectClass=User)(extensionAttribute1=*)(sAMAccountName={username}))";// string.Format(_config.SearchFilter, username); string searchFilter = string.Format(_config.SearchFilter, $"(sAMAccountName={username})"); LdapSearchResults result = _connection.Search( _config.SearchBase, LdapConnection.SCOPE_SUB, searchFilter, new[] { MemberOfAttribute, DisplayNameAttribute, SamAccountNameAttribute, "sn", "givenName", "distinguishedName", "cn" }, false ); if (!result.HasMore()) { return(null); } LdapEntry user = result.Next(); if (user != null) { _connection.Bind(user.DN, password); if (_connection.Bound) { return(new User { DisplayName = $"{user.getAttribute("sn")?.StringValue ?? "noSN"} {user.getAttribute("givenName")?.StringValue ?? "noGivenName"}", Sam = user.getAttribute(SamAccountNameAttribute)?.StringValue ?? "noSam", IsAdmin = user.getAttribute(MemberOfAttribute)?.StringValueArray.Contains(_config.AdminCn) ?? false, DistinguishedName = user.getAttribute("distinguishedName")?.StringValue ?? "noDn", Subordinates = GetSubordinates(user.getAttribute("distinguishedName")?.StringValue) }); } } _connection.Disconnect(); return(null); }
/// <summary>Gets the value of an attribute for the given /// entry. /// </summary> /// <param name="le">LdapEntry</param> /// <param name="attr">Attribute to lookup type</param> /// <returns>The value of the attribute (or an empty string if there is /// no value).</returns> public string GetAttributeValueFromEntry(LdapEntry le, string attr) { LdapAttribute la = le.getAttribute(attr); if (la != null) { return(la.StringValue); } return(""); }