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 (KeyNotFoundException) { } catch (Exception e) { new SysLogModel(context: context, e: e, logs: logs); } } return(string.Empty); }
public static User FromLdapEntry(LdapEntry ldapEntry) { return(new User { DisplayName = ldapEntry.GetAttribute("name").StringValue, FirstName = ldapEntry.GetAttribute("givenname").StringValue, UserName = ldapEntry.GetAttribute("samaccountname").StringValue, MailAddress = ldapEntry.GetAttribute("mail").StringValue }); }
public static DateTime?GetDateTimeAttribute(this LdapEntry entry, LdapAttr attr) { var val = entry.GetAttribute(attr); if (val == null && attr.Optional) { return(null); } return(DateTime.ParseExact(entry.GetAttribute(attr), LdapConstants.DateFormat, CultureInfo.InvariantCulture)); }
/// <summary> /// Converts the data from the LDAP result /// </summary> /// <returns>The LDAP.</returns> /// <param name="entry">Entry.</param> private Group ConvertfromLdap(LdapEntry entry, Boolean _listCN = false) { var group = new Group(); group.Name = entry.GetAttribute("name").StringValue; if (entry.GetAttribute("description") != null) { group.Description = entry.GetAttribute("description").StringValue; } //var sid = ConvertByteToStringSid((byte[])(Array)entry.GetAttribute("objectSid").ByteValue); //group.ID = sid; group.DN = entry.GetAttribute("distinguishedName").StringValue; if (entry.GetAttribute("memberOf") != null) { var moff = entry.GetAttribute("memberOf").StringValues; while (moff.MoveNext()) { String gmoff = ""; if (moff != null && moff.Current != null) { gmoff = moff.Current; } group.MemberOf.Add(gmoff); } } if (entry.GetAttribute("member") != null) { var m = entry.GetAttribute("member").StringValues; while (m.MoveNext()) { String member = ""; if (m != null && m.Current != null) { member = m.Current; if (_listCN) { var regex = new Regex("^(?:CN=)(?<cn>[^,]+?)(?:,)"); var result = regex.Match(member); member = result.Groups["cn"].Value; } group.Member.Add(member); } } } return(group); }
public MemberInfo(LdapEntry e, LDAPUtils ldap) { ldap.logger.LogInformation("Reading user info for " + e.Dn); DN = e.Dn; FullName = GetOptAttr(e, "cn"); FirstName = GetOptAttr(e, "givenName"); Surname = GetOptAttr(e, "sn"); UID = GetOptAttr(e, "uid"); DisplayName = GetOptAttr(e, "displayName"); Mail = GetOptAttr(e, "mail"); Address = GetOptAttr(e, "postalAddress"); Flat = GetOptAttr(e, "roomNumber"); TelephoneNumber = GetOptAttr(e, "telephoneNumber"); Password = GetOptAttr(e, "userPassword"); if (!Int32.TryParse(GetOptAttr(e, "employeeNumber"), out DjangoAccount)) { DjangoAccount = -1; } var memof = e.GetAttribute("memberOf"); if (memof != null) { Groups = memof.StringValueArray; } else { Groups = new string[] { }; } }
/// <summary> /// Converts the data from the LDAP result /// </summary> /// <returns>The LDAP.</returns> /// <param name="entry">Entry.</param> private OU ConvertfromLdap(LdapEntry entry) { var ou = new OU(); ou.Name = entry.GetAttribute("name").StringValue; if (entry.GetAttribute("description") != null) { ou.Description = entry.GetAttribute("description").StringValue; } ou.DN = entry.GetAttribute("distinguishedName").StringValue; return(ou); }
private static bool Enabled(LdapEntry entry, ParameterAccessor.Parts.Ldap ldap) { var accountDisabled = 2; return (!ldap.LdapExcludeAccountDisabled || (entry.GetAttribute("UserAccountControl")?.StringValue.ToLong() & accountDisabled) == 0); }
/// <summary> /// Converts a ldap entry to the ldap model object. /// </summary> /// <param name="entry">Entry to convert.</param> public virtual void ProvideEntry(LdapEntry entry) { this.Id = entry.GetAttribute(LdapProperties.CommonName); this.Dn = entry.DN; this.Entry = entry; // load properties with reflection foreach (KeyValuePair <PropertyInfo, LdapAttr> kv in this.Properties) { object value; switch (Type.GetTypeCode(kv.Value.Type)) { case TypeCode.Int16: case TypeCode.Int32: case TypeCode.Int64: value = entry.GetIntAttribute(kv.Value); break; case TypeCode.Boolean: bool?boolval = entry.GetBoolAttribute(kv.Value); value = boolval ?? false; break; case TypeCode.DateTime: value = entry.GetDateTimeAttribute(kv.Value); break; case TypeCode.Object: if (kv.Value.Type == typeof(List <string>)) { value = entry.GetStringListAttribute(kv.Value); break; } value = null; break; default: value = entry.GetAttribute(kv.Value); break; } kv.Key.SetValue(this, value); } }
public static LdapAttribute?TryGetAttribute(this LdapEntry conn, string attribute) { try { return(conn.GetAttribute(attribute)); } catch { return(null); } }
private LdapAttribute GetAttribute(LdapEntry userEntry, string attr) { try { return(userEntry.GetAttribute(attr)); } catch (Exception e) { _logger.LogWarning(e, "Error getting LDAP attribute"); return(null); } }
/// <summary> /// The previous behavior of Novell was to return null if the key was not in the collection. However, this have been changed /// and it now throws a key not found exception instead. /// /// This method repeat the previous behavior. /// </summary> /// <param name="ldapEntry">LdapEntry that we extend</param> /// <param name="attribute">The key attribute we are looking for.</param> /// <returns>Returns the LdapAttribute or NULL when not found.</returns> public static LdapAttribute GetNullableAttribute(this LdapEntry ldapEntry, string attribute) { try { var ldapAttr = ldapEntry.GetAttribute(attribute); return(ldapAttr); } catch (KeyNotFoundException) { return(null); } }
static string GetOptAttr(LdapEntry e, string name) { if (e == null) { return(""); } var a = e.GetAttribute(name); if (a == null) { return(""); } return(a.StringValue ?? ""); }
public static string Attribute(this LdapEntry entry, string attrName) { try { LdapAttribute attr = entry.GetAttribute(attrName); if (null == attr) { return(null); } return(attr.StringValue); } catch (KeyNotFoundException) { } return(string.Empty); }
public static IList <string> ArrayAttribute(this LdapEntry entry, string attrName) { try { LdapAttribute attr = entry.GetAttribute(attrName); if (null == attr) { return(null); } return(attr.StringValueArray.ToList()); } catch { } return(new string[0]); }
private string GetAttributeValue(LdapEntry entity, string attributeKey) { if (!String.IsNullOrEmpty(attributeKey)) { var entityAttributes = entity.GetAttributeSet(); if (entityAttributes.ContainsKey(attributeKey)) { var attrValue = entity.GetAttribute(attributeKey); if (attrValue != null && !String.IsNullOrEmpty(attrValue.StringValue)) { return(attrValue.StringValue); } } } return(null); }
private User MapSearchResult(LdapEntry entry) { var user = new User { Id = entry.GetAttribute("bcgovGUID")?.StringValue ?? string.Empty, UserName = entry.GetAttribute("sAMAccountName")?.StringValue ?? string.Empty, FirstName = entry.GetAttribute("givenName")?.StringValue ?? string.Empty, LastName = entry.GetAttribute("sn")?.StringValue ?? string.Empty, Email = entry.GetAttribute("mail")?.StringValue ?? string.Empty, UserPrincipalName = entry.GetAttribute("userPrincipalName")?.StringValue ?? string.Empty }; return(user); }
private static bool Enabled(LdapEntry entry, ParameterAccessor.Parts.Ldap ldap) { var accountDisabled = 2; if (!ldap.LdapExcludeAccountDisabled) { return(true); } if (entry.GetAttributeSet().Any(o => o.Key == "userAccountControl")) { var userAccountControl = entry.GetAttribute("userAccountControl")?.StringValue; return(userAccountControl.IsNullOrEmpty() ? true : (userAccountControl.ToLong() & accountDisabled) == 0); } else { return(true); } }
public static T ConvertLdapEntry <T>(ILogger logger, LdapEntry entry, Func <string, LdapAttribute, object> retrieveValue = null) { var attributes = GetLdapAttributes <T>(); var properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(x => x.IsDefined(typeof(LdapUserAttribute), true)).ToList(); var data = Activator.CreateInstance <T>(); foreach (var a in attributes) { try { var e = entry.GetAttribute(a); if (e != null) { var prop = properties.Where(x => (x.GetCustomAttributes(typeof(LdapUserAttribute)).First() as LdapUserAttribute).AttributeName == a).First(); if (retrieveValue == null) { typeof(T).GetProperty(prop.Name).SetValue(data, e.StringValue); } else { var val = retrieveValue(prop.Name, e); typeof(T).GetProperty(prop.Name).SetValue(data, val); } } } catch (KeyNotFoundException kex) { logger.LogWarning($"Attribute {a} not found in directory entry! ({kex.Message})"); continue; } catch (Exception ex) { logger.LogError($"Error converting and LdapEntry to a c# object: {ex.Message}"); } } return(data); }
public static bool?GetBoolAttribute(this LdapEntry entry, LdapAttr attr) { var strVal = entry.GetAttribute(attr); return(strVal == null ? null : (bool?)(strVal == "TRUE")); }
private User ConvertfromLdap(LdapEntry entry) { var user = new User(); user.Name = entry.GetAttribute("name").StringValue; user.Account = entry.GetAttribute("sAMAccountName").StringValue; if (entry.GetAttribute("userPrincipalName") != null) { user.Login = entry.GetAttribute("userPrincipalName").StringValue; } if (entry.GetAttribute("description") != null) { user.Description = entry.GetAttribute("description").StringValue; } var sid = ConvertByteToStringSid((byte[])(Array)entry.GetAttribute("objectSid").ByteValue); user.ID = sid; user.DN = entry.GetAttribute("distinguishedName").StringValue; if (entry.GetAttribute("givenName") != null) { user.GivenName = entry.GetAttribute("givenName").StringValue; } if (entry.GetAttribute("sn") != null) { user.Surname = entry.GetAttribute("sn").StringValue; } if (entry.GetAttribute("mail") != null) { user.Mail = entry.GetAttribute("mail").StringValue; } if (entry.GetAttribute("mobile") != null) { user.Mobile = entry.GetAttribute("mobile").StringValue; } var attrMo = entry.GetAttribute("memberOf"); if (attrMo != null) { var mofs = attrMo.StringValues; while (mofs.MoveNext()) { var group = new Group(); if (mofs != null && mofs.Current != null) { group.DN = mofs.Current; } user.MemberOf.Add(group); } } return(user); }
public AuthResult Authenticate(string username, string password) { if (!ValidateLDAPField(username)) { logger.LogWarning("Tried LDAP injection: " + username); return(new AuthResult { ValidCredentrials = false, Active = false }); } RfcFilter query = new RfcFilter(); var UTF8 = System.Text.Encoding.UTF8; query.StartNestedFilter(RfcFilter.And); query.AddAttributeValueAssertion(RfcFilter.EqualityMatch, "objectClass", UTF8.GetBytes("inetOrgPerson")); query.StartNestedFilter(RfcFilter.Or); var usernameBytes = UTF8.GetBytes(username); query.AddAttributeValueAssertion(RfcFilter.EqualityMatch, "mailPrimaryAddress", usernameBytes); query.AddAttributeValueAssertion(RfcFilter.EqualityMatch, "mail", usernameBytes); query.AddAttributeValueAssertion(RfcFilter.EqualityMatch, "uid", usernameBytes); query.EndNestedFilter(RfcFilter.Or); query.EndNestedFilter(RfcFilter.And); var resmq = Search(Params.DN("ou=Members"), LdapConnection.ScopeOne, query, new string[] { "displayName", "memberOf" }); LdapEntry res = null; AuthResult ar = new AuthResult(); LdapMessage msg; while ((msg = resmq.GetResponse()) != null) { if (msg is LdapSearchResult) { LdapEntry r = ((LdapSearchResult)msg).Entry; if (res != null) { logger.LogError("LDAP login returned multiple results: " + username); return(new AuthResult { ValidCredentrials = false, Active = false }); } res = r; logger.LogInformation("LDAP login found user DN: " + res.Dn); } } if (res == null) { logger.LogError("LDAP login failed to find account: " + username); return(new AuthResult { ValidCredentrials = false, Active = false }); } ar.ValidCredentrials = false; ar.Active = false; ar.SuperAdmin = false; ar.DN = res.Dn; ar.DisplayName = res.GetAttribute("displayName").StringValue ?? res.Dn; // try login using (LdapConnection userConn = new LdapConnection { SecureSocketLayer = false }) { userConn.Connect(Params.Host, Params.Port); if (!userConn.Connected) { throw new System.Exception("Could not connect to the LDAP server at " + Params.Host + ":" + Params.Port); } try { userConn.Bind(ar.DN, password); } catch (LdapException) { logger.LogError("LDAP login: wrong password for account: " + ar.DN); return(new AuthResult { ValidCredentrials = false, Active = false }); } if (!userConn.Bound) { logger.LogError("LDAP login: could not bind account: " + ar.DN); return(new AuthResult { ValidCredentrials = false, Active = false }); } } ar.ValidCredentrials = true; var groups = res.GetAttribute("memberOf").StringValueArray; ar.Active = groups.Contains(Params.DN("cn=AllMembers,ou=Groups")); ar.SuperAdmin = groups.Contains(Params.DN("cn=InternetSpecialists,ou=Groups")) || groups.Contains(Params.DN("cn=DirectoryEditors,ou=Groups")); foreach (var group in groups) { logger.LogDebug("Group: " + group); } return(ar.Active ? ar : new AuthResult { ValidCredentrials = true, Active = false }); }
public static int?GetIntAttribute(this LdapEntry entry, LdapAttr attr) { var strVal = entry.GetAttribute(attr); return(strVal == null ? null : (int?)int.Parse(strVal)); }
public static string GetAttribute(this LdapEntry entry, LdapAttr attr) { return(entry.GetAttribute(attr.LdapName, attr.Optional)); }
public AuthResult Login(string userName, string password) { using LdapConnection _connection = new LdapConnection { SecureSocketLayer = _config.SecureSocketLayer }; try { _connection.Connect(_config.ServerHost, _config.ServerPort); _connection.Bind(_config.BindDN, _config.BindPassword); string userFilter = string.Format(_config.UserFilter, userName); ILdapSearchResults result = _connection.Search( _config.BaseDN, LdapConnection.ScopeSub, userFilter, new[] { DisplayName, Email, UserName }, false ); /* * WARNING: Do not check result.Count == 0; * "Count doesn't return "correctly" because is not blocking and doesn't wait to get the results and is * returning whatever is available at that moment. It is true that this behavior * is not the most expected one :) - and it may have an easy fix. * It will return correctly after calling hasMore - which is blocking (e.g. wait for the result). * Probably will be useful to make the "async" methods match the .net style. * And even make the sync methods to return IEnumerable as will make the usage easier. Happy to take pull requests :)" * https://github.com/dsbenghe/Novell.Directory.Ldap.NETStandard/issues/4 */ if (!result.HasMore()) { return(new AuthResult { Errors = new List <string> { "Invalid user" } }); } LdapEntry user = result.Next(); _connection.Bind(user.Dn, password); if (_connection.Bound) { return(new AuthResult { AppUser = new AppUser { Email = user.GetAttribute(Email).StringValue, DisplayName = user.GetAttribute(DisplayName).StringValue, UserName = user.GetAttribute(UserName).StringValue, } }); } else { return(new AuthResult { Errors = new List <string> { "Invalid user" } }); } } catch (Exception ex) { return(new AuthResult { Errors = new List <string> { ex.Message } }); } }