/** * Prints the DN and attributes in an LDAPEntry to System.out. * This method used TreeSet to sort the attributes by name. */ public static void PrintEntry(LdapEntry entry) { /* To print an entry, * -- Loop through all the attributes * -- Loop through all the attribute values */ Console.WriteLine(entry.DN); Console.WriteLine("\tAttributes: "); LdapAttributeSet attributeSet = entry.getAttributeSet(); IEnumerator allAttributes = attributeSet.GetEnumerator(); while (allAttributes.MoveNext()) { LdapAttribute attribute = (LdapAttribute)(allAttributes.Current); string attributeName = attribute.Name; Console.WriteLine("\t\t" + attributeName); IEnumerator allValues = attribute.StringValues; if (allValues != null) { while (allValues.MoveNext()) { String Value = (String)allValues.Current; Console.WriteLine("\t\t\t" + Value); } } } return; }
public sbyte[] GetLdapInfo(string num, string attr) { string filter = string.Format("telephoneNumber={0}", num); LdapConnection conn = GetConnection(); LdapSearchResults result = conn.Search("dc=renstech,dc=com", LdapConnection.SCOPE_SUB, filter, null, false); while (result.hasMore()) { LdapEntry nextEntry; try { nextEntry = result.next(); } catch (LdapException) { continue; } LdapAttributeSet attributeSet = nextEntry.getAttributeSet(); System.Collections.IEnumerator ienum = attributeSet.GetEnumerator(); while (ienum.MoveNext()) { LdapAttribute attribute = (LdapAttribute)ienum.Current; string attributeName = attribute.Name; if (attributeName == attr) { return(attribute.ByteValue); } //string attributeVal = attribute.StringValue; } } return(null); }
public static void GetRootDSE(LdapConnection conn) { LdapEntry rootEntry = conn.Read(""); LdapAttributeSet attributeSet = rootEntry.getAttributeSet(); System.Collections.IEnumerator ienum = attributeSet.GetEnumerator(); while (ienum.MoveNext()) { LdapAttribute attribute = (LdapAttribute)ienum.Current; string attributeName = attribute.Name; if (string.Equals(attributeName, "supportedCapabilities", StringComparison.InvariantCultureIgnoreCase)) { System.Console.WriteLine("Eureka"); } // string attributeVal = attribute.StringValue; foreach (string temp in attribute.StringValueArray) { string attributeVal = temp; if (!Base64.isLDIFSafe(attributeVal)) { byte[] tbyte = SupportClass.ToByteArray(attributeVal); attributeVal = Base64.encode(SupportClass.ToSByteArray(tbyte)); } // End if (!Base64.isLDIFSafe(attributeVal)) Console.WriteLine(attributeName + "value:" + attributeVal); } // Next temp } }
public IList <KeyValuePair <string, string> > GetEntryAttributes(LdapDomain ldapDomain, string searchDn) { List <KeyValuePair <string, string> > _attributes = new List <KeyValuePair <string, string> >(); IList <LdapNodeObject> entries = new List <LdapNodeObject>(); var ldapConn = GetConnection(ldapDomain); var entry = ldapConn.Read(searchDn); // Get the attribute set of the entry LdapAttributeSet attributeSet = entry.getAttributeSet(); System.Collections.IEnumerator ienum = attributeSet.GetEnumerator(); // Parse through the attribute set to get the attributes and //the corresponding values while (ienum.MoveNext()) { LdapAttribute attribute = (LdapAttribute)ienum.Current; string attributeName = attribute.Name; string attributeVal = attribute.StringValue; if (attributeName == "objectGUID") { attributeVal = new Guid((Byte[])(Array)attribute?.ByteValue).ToString(); } _attributes.Add(new KeyValuePair <string, string>(attributeName, attributeVal)); } return(_attributes); }
public void userList() { string LDAP_server = "localhost"; int ldapPort = 1920; string loginON = "uid=admin,ou=system"; string password = "******"; string searchBase = "ou=user,o=Company"; string searchFilter = "ObjectClass=UserLogin,Password,Name,TelNo,Email"; try { LdapConnection conn = new LdapConnection(); Console.WriteLine("Connecting to " + LDAP_server); conn.Connect(LDAP_server, ldapPort); conn.Bind(loginON, password); string[] requiredAttri = { "cn", "sn", "uid" }; LdapSearchResults result = conn.Search(searchBase, LdapConnection.SCOPE_SUB, searchFilter, requiredAttri, false); while (result.hasMore()) { LdapEntry nextEntry = null; try { nextEntry = result.next(); } catch (LdapException ex) { Console.WriteLine("LDAPconnection error:" + ex.LdapErrorMessage); continue; } Console.WriteLine("\n" + nextEntry.DN); LdapAttributeSet ldapattri = nextEntry.getAttributeSet(); System.Collections.IEnumerator ienum = ldapattri.GetEnumerator(); while (ienum.MoveNext()) { LdapAttribute attri = (LdapAttribute)ienum.Current; string attriName = attri.Name; string attriVal = attri.StringValue; Console.WriteLine("\t" + attriName + "\tValue = \t" + attriVal); } } conn.Disconnect(); } catch (LdapException ex) { Console.WriteLine("LDAPconnection error:" + ex.LdapErrorMessage); return; } catch (Exception ex) { Console.WriteLine("LDAPconnection error:" + ex.Message); return; } }
static void DoSearch(string ldapHost, int ldapPort, string loginDN, string password, string searchBase, string searchFilter) { try { LdapConnection conn = new LdapConnection(); Console.WriteLine("Connecting to:" + ldapHost); conn.Connect(ldapHost, ldapPort); conn.Bind(loginDN, password); LdapSearchResults lsc = conn.Search(searchBase, LdapConnection.SCOPE_SUB, searchFilter, null, false); while (lsc.hasMore()) { LdapEntry nextEntry = null; try { nextEntry = lsc.next(); } catch (LdapException e) { Console.WriteLine("Error: " + e.LdapErrorMessage); // Exception is thrown, go for next entry continue; } Console.WriteLine("\n" + nextEntry.DN); LdapAttributeSet attributeSet = nextEntry.getAttributeSet(); System.Collections.IEnumerator ienum = attributeSet.GetEnumerator(); while (ienum.MoveNext()) { LdapAttribute attribute = (LdapAttribute)ienum.Current; string attributeName = attribute.Name; string attributeVal = attribute.StringValue; if (!Base64.isLDIFSafe(attributeVal)) { byte[] tbyte = SupportClass.ToByteArray(attributeVal); attributeVal = Base64.encode(SupportClass.ToSByteArray(tbyte)); } Console.WriteLine(attributeName + "value:" + attributeVal); } } conn.Disconnect(); } catch (LdapException e) { Console.WriteLine("Error:" + e.LdapErrorMessage); return; } catch (Exception e) { Console.WriteLine("Error:" + e.Message); return; } }
// Maps all sent LDAP Properties of the user into a Dictionary public static Dictionary <string, string> GetLdapUser(string ldapUid) { try { LdapConnection conn = new LdapConnection(); conn.Connect(LdapHost, LdapPort); var lsc = conn.Search("ou=People,dc=fh-augsburg,dc=de", LdapConnection.SCOPE_ONE, $"uid={ldapUid}", null, false); var newDict = new Dictionary <string, string>(); while (lsc.hasMore()) { LdapEntry nextEntry = null; try { nextEntry = lsc.next(); } catch (LdapException e) { Console.WriteLine("Error: " + e.LdapErrorMessage); // Exception is thrown, go for next entry continue; } LdapAttributeSet attributeSet = nextEntry.getAttributeSet(); System.Collections.IEnumerator ienum = attributeSet.GetEnumerator(); while (ienum.MoveNext()) { LdapAttribute attribute = (LdapAttribute)ienum.Current; string attributeName = attribute.Name; string attributeVal = attribute.StringValue; if (!Base64.isLDIFSafe(attributeVal)) { byte[] tbyte = SupportClass.ToByteArray(attributeVal); attributeVal = Base64.encode(SupportClass.ToSByteArray(tbyte)); } newDict.Add(attributeName, attributeVal); } } conn.Disconnect(); return(newDict); } catch (LdapException e) { Console.WriteLine("Error:" + e.LdapErrorMessage); return(null); } catch (Exception e) { Console.WriteLine("Error:" + e.Message); return(null); } }
// Obtains an email address, given an employee ID. public string EmailByEmployeeId(string employeeId) { // If the OverrideEmail config setting is set to a string, then // we just return it. It will be the user email instead of looking // up their email. if (!string.IsNullOrWhiteSpace(OverrideEmail)) { return(OverrideEmail); } // Otherwise, continue on, using the LDAP connection to filter by // the employee ID and find the user's mail (email) attribute. using (var ldapConnection = new LdapConnection()) { ldapConnection.Connect(Host, Port); ldapConnection.Bind(Username, Password); ILdapSearchResults results = ldapConnection.Search( Base, LdapConnection.ScopeSub, $"(employeeID={employeeId})", new string[] { "mail" }, false ); while (results.HasMore()) { LdapEntry nextEntry = results.Next(); LdapAttributeSet attributes = nextEntry.GetAttributeSet(); System.Collections.IEnumerator ienum = attributes.GetEnumerator(); // Parse through the attribute set to get the attributes and the // corresponding values while (ienum.MoveNext()) { LdapAttribute attribute = (LdapAttribute)ienum.Current; string attributeName = attribute.Name; string attributeVal = attribute.StringValue; if (attributeName == "mail") { // Success. Return the mail attribute value, which // is the user's email address. return(attributeVal); } } } // Return blank if we don't find an email for that employee. return(""); } }
public static IList <LdapAttribute> GetLdapEntryAttributes(this LdapEntry entry) { IList <LdapAttribute> attributes = new List <LdapAttribute>(); LdapAttributeSet attributeSet = entry.GetAttributeSet(); System.Collections.IEnumerator ienum = attributeSet.GetEnumerator(); while (ienum.MoveNext()) { LdapAttribute attribute = (LdapAttribute)ienum.Current; attributes.Add(attribute); } return(attributes); }
// returns whether connection is e-dir or not. Also updates treeMatched with true or false depending on whether dirTreeName matches with the // tree name corresponding to connections's treeName public static bool IseDirectory(LdapConnection connection, string dirTreeName, out string treeName) { LdapAttribute attr = null; LdapEntry entry = null; bool eDirectory = false; treeName = null; LdapSearchResults lsc = connection.Search("", LdapConnection.SCOPE_BASE, "objectClass=*", null, false); while (lsc.hasMore()) { entry = null; try { entry = lsc.next(); } catch (LdapException e) { Console.WriteLine("Error: " + e.LdapErrorMessage); continue; } LdapAttributeSet attributeSet = entry.getAttributeSet(); System.Collections.IEnumerator ienum = attributeSet.GetEnumerator(); while (ienum.MoveNext()) { attr = (LdapAttribute)ienum.Current; string attributeName = attr.Name; string attributeVal = attr.StringValue; if (String.Equals(attributeName, "directoryTreeName")) { treeName = attributeVal; } if (String.Equals(attributeVal, "Novell, Inc.") == true) { eDirectory = true; } } } return(eDirectory); }
/// <summary> /// Valida si el usuario tiene el rol asignado /// </summary> /// <param name="conn">Conexion activa del lda de novell</param> /// <param name="usuario">Id de usuario a validar</param> /// <returns>Si el usuario tiene asignado el rol</returns> private bool TieneRolAbax(LdapConnection conn, String usuario) { var rolBaseDN = ConfigurationManager.AppSettings.Get("DNBaseRolLDAPNovell"); LdapSearchResults gruposAbax = conn.Search(rolBaseDN, LdapConnection.SCOPE_BASE, "objectClass=*", null, false); bool tieneRolUsuario = false; while (gruposAbax.hasMore()) { LdapEntry grupoEntry = null; try { grupoEntry = gruposAbax.next(); LdapAttributeSet attributeSet = grupoEntry.getAttributeSet(); System.Collections.IEnumerator ienum = attributeSet.GetEnumerator(); while (ienum.MoveNext()) { LdapAttribute attribute = (LdapAttribute)ienum.Current; string attributeName = attribute.Name; if (attributeName.Equals("member")) { foreach (var miembro in attribute.StringValueArray) { if (miembro.Contains(usuario)) { tieneRolUsuario = true; break; } } } } } catch (Exception e) { continue; } } return(tieneRolUsuario); }
private static string VerifyUser(string username, string password) { string searchBase = "ou=KSU,dc=KS,dc=mil,dc=no"; int searchScope = LdapConnection.SCOPE_SUB; string searchFilter = "(sAMAccountName=" + username + ")"; LdapConnection ldapConn = new LdapConnection(); ldapConn.Connect("ks.mil.no", 389); ldapConn.Bind("ks\\" + username, password); Console.WriteLine(ldapConn.Connected); string[] attr = { "sAMAccountName", "mail", "displayName", "department", "userPrincipalName", "title" }; LdapSearchQueue queue = ldapConn.Search(searchBase, searchScope, searchFilter, attr, false, (LdapSearchQueue)null, (LdapSearchConstraints)null); LdapMessage message; StringBuilder sb = new StringBuilder(); while ((message = queue.getResponse()) != null) { if (message is LdapSearchResult) { LdapEntry entry = ((LdapSearchResult)message).Entry; // System.Console.Out.WriteLine("\n" + entry.DN); // System.Console.Out.WriteLine("\tAttributes: "); LdapAttributeSet attributeSet = entry.getAttributeSet(); System.Collections.IEnumerator ienum = attributeSet.GetEnumerator(); while (ienum.MoveNext()) { LdapAttribute attribute = (LdapAttribute)ienum.Current; string attributeName = attribute.Name; string attributeVal = attribute.StringValue; sb.AppendLine(attributeName + ": " + attributeVal); } } } //Procced //While all the required entries are parsed, disconnect ldapConn.Disconnect(); return(sb.ToString()); }
public static string lookingForGroupDN(LdapConnection lc, String searchBase, string groupName) { string searchFilter = String.Concat("(&(objectCategory=Group)(cn=", groupName, "))"); string dn = ""; int searchScope = LdapConnection.SCOPE_SUB; String[] attrList = new String[] { "distinguishedName" }; LdapSearchConstraints cons = new LdapSearchConstraints(); cons.TimeLimit = 10000; try { LdapSearchResults searchResults = lc.Search(searchBase, searchScope, searchFilter, attrList, false, cons); // time out value LdapEntry nextEntry = null; if ((nextEntry = searchResults.next()) != null) { LdapAttributeSet attributeSet = nextEntry.getAttributeSet(); System.Collections.IEnumerator ienum = attributeSet.GetEnumerator(); while (ienum.MoveNext()) { LdapAttribute attribute = (LdapAttribute)ienum.Current; dn = attribute.StringValue; } } } catch (LdapException e) { Console.WriteLine("ERROR: Cannot find the group DN {0} (Maybe wrong groupname? ) ", groupName); throw new System.Exception(e.ToString()); } return(dn); }
public static void Main(System.String[] args) { /* Check if we have the correct number of command line arguments */ if (args.Length != 4) { System.Console.Error.WriteLine("Usage: mono VLVControl <host name> <login dn>" + " <password> <container>"); System.Console.Error.WriteLine("Example: mono VLVControl Acme.com \"cn=admin,o=Acme\" secret" + " \"ou=Sales,o=Acme\""); System.Environment.Exit(1); } /* Parse the command line arguments */ System.String LdapHost = args[0]; System.String loginDN = args[1]; System.String password = args[2]; System.String searchBase = args[3]; int LdapPort = LdapConnection.DEFAULT_PORT; int LdapVersion = LdapConnection.Ldap_V3; LdapConnection conn = new LdapConnection(); try { // connect to the server conn.Connect(LdapHost, LdapPort); // bind to the server conn.Bind(LdapVersion, loginDN, password); System.Console.Out.WriteLine("Succesfully logged in to server: " + LdapHost); /* Set default filter - Change this line if you need a different set * of search restrictions. Read the "NDS and Ldap Integration Guide" * for information on support by Novell eDirectory of this * functionaliry. */ System.String MY_FILTER = "cn=*"; /* We are requesting that the givenname and cn fields for each * object be returned */ System.String[] attrs = new System.String[2]; attrs[0] = "givenname"; attrs[1] = "cn"; // We will be sending two controls to the server LdapControl[] requestControls = new LdapControl[2]; /* Create the sort key to be used by the sort control * Results should be sorted based on the cn attribute. * See the "NDS and Ldap Integration Guide" for information on * Novell eDirectory support of this functionaliry. */ LdapSortKey[] keys = new LdapSortKey[1]; keys[0] = new LdapSortKey("cn"); // Create the sort control requestControls[0] = new LdapSortControl(keys, true); /* Create the VLV Control. * These two fields in the VLV Control identify the before and * after count of entries to be returned */ int beforeCount = 0; int afterCount = 2; /* The VLV control request can specify the index * using one of the two methods described below: * * TYPED INDEX: Here we request all objects that have cn greater * than or equal to the letter "a" */ requestControls[1] = new LdapVirtualListControl("a", beforeCount, afterCount); /* The following code needs to be enabled to specify the index * directly * int offset = 0; - offset of the index * int contentCount = 3; - our estimate of the search result size * requestControls[1] = new LdapVirtualListControl(offset, * beforeCount, afterCount, contentCount); */ // Set the controls to be sent as part of search request LdapSearchConstraints cons = conn.SearchConstraints; cons.setControls(requestControls); conn.Constraints = cons; // Send the search request - Synchronous Search is being used here System.Console.Out.WriteLine("Calling Asynchronous Search..."); LdapSearchResults res = conn.Search(searchBase, LdapConnection.SCOPE_SUB, MY_FILTER, attrs, false, (LdapSearchConstraints)null); // Loop through the results and print them out while (res.HasMore()) { /* Get next returned entry. Note that we should expect a Ldap- * Exception object as well just in case something goes wrong */ LdapEntry nextEntry = null; try { nextEntry = res.Next(); } catch (LdapException e) { if (e is LdapReferralException) { continue; } else { System.Console.Out.WriteLine("Search stopped with exception " + e.ToString()); break; } } /* Print out the returned Entries distinguished name. */ System.Console.Out.WriteLine(); System.Console.Out.WriteLine(nextEntry.DN); /* Get the list of attributes for the current entry */ LdapAttributeSet findAttrs = nextEntry.getAttributeSet(); /* Convert attribute list to Enumeration */ System.Collections.IEnumerator enumAttrs = findAttrs.GetEnumerator(); System.Console.Out.WriteLine("Attributes: "); /* Loop through all attributes in the enumeration */ while (enumAttrs.MoveNext()) { LdapAttribute anAttr = (LdapAttribute)enumAttrs.Current; /* Print out the attribute name */ System.String attrName = anAttr.Name; System.Console.Out.WriteLine("" + attrName); // Loop through all values for this attribute and print them System.Collections.IEnumerator enumVals = anAttr.StringValues; while (enumVals.MoveNext()) { System.String aVal = (System.String)enumVals.Current; System.Console.Out.WriteLine("" + aVal); } } } // Server should send back a control irrespective of the // status of the search request LdapControl[] controls = res.ResponseControls; if (controls == null) { System.Console.Out.WriteLine("No controls returned"); } else { // We are likely to have multiple controls returned for (int i = 0; i < controls.Length; i++) { /* Is this the Sort Response Control. */ if (controls[i] is LdapSortResponse) { System.Console.Out.WriteLine("Received Ldap Sort Control from " + "Server"); /* We could have an error code and maybe a string * identifying erring attribute in the response control. */ System.String bad = ((LdapSortResponse)controls[i]).FailedAttribute; int result = ((LdapSortResponse)controls[i]).ResultCode; // Print out error code (0 if no error) and any // returned attribute System.Console.Out.WriteLine("Error code: " + result); if ((System.Object)bad != null) { System.Console.Out.WriteLine("Offending " + "attribute: " + bad); } else { System.Console.Out.WriteLine("No offending " + "attribute " + "returned"); } } /* Is this a VLV Response Control */ if (controls[i] is LdapVirtualListResponse) { System.Console.Out.WriteLine("Received VLV Response Control from " + "Server..."); /* Get all returned fields */ int firstPosition = ((LdapVirtualListResponse)controls[i]).FirstPosition; int ContentCount = ((LdapVirtualListResponse)controls[i]).ContentCount; int resultCode = ((LdapVirtualListResponse)controls[i]).ResultCode; System.String context = ((LdapVirtualListResponse)controls[i]).Context; /* Print out the returned fields. Typically you would * have used these fields to reissue another VLV request * or to display the list on a GUI */ System.Console.Out.WriteLine("Result Code => " + resultCode); System.Console.Out.WriteLine("First Position => " + firstPosition); System.Console.Out.WriteLine("Content Count => " + ContentCount); if ((System.Object)context != null) { System.Console.Out.WriteLine("Context String => " + context); } else { System.Console.Out.WriteLine("No Context String in returned" + " control"); } } } } /* We are done - disconnect */ if (conn.Connected) { conn.Disconnect(); } } catch (LdapException e) { System.Console.Out.WriteLine(e.ToString()); } catch (System.IO.IOException e) { System.Console.Out.WriteLine("Error: " + e.ToString()); } catch (Exception e) { System.Console.WriteLine("Error: " + e.Message); } }
public static Task <bool> LoginAsync(string username, string password) { CancellationTokenSource cts = new CancellationTokenSource(); CancellationToken cancellationToken = cts.Token; LdapConnection conn = null; return(Task.Factory.StartNew(() => { conn = new LdapConnection(); conn.Connect(Host, Port); if (!string.IsNullOrEmpty(username)) { try { conn.Bind(dn, pa); } catch (Exception e) { conn.Disconnect(); return false; } string searchBase = filter; int searchScope = LdapConnection.ScopeSub; string searchFilter = "uid=" + username.Trim(); LdapSearchQueue queue = conn.Search(searchBase, searchScope, searchFilter, null, false, (LdapSearchQueue)null, (LdapSearchConstraints)null); LdapMessage message; while ((message = queue.GetResponse()) != null) { try { string msg = message.ToString(); LdapEntry entry = ((LdapSearchResult)message).Entry; LdapAttributeSet attributeSet = entry.GetAttributeSet(); System.Collections.IEnumerator ienum = attributeSet.GetEnumerator(); LdapAttribute cn = attributeSet.GetAttribute("cn"); string idUser = cn.StringValue; try { conn.Bind("cn=" + idUser + "," + filter, password); } catch (Exception e) { conn.Disconnect(); return false; } conn.Disconnect(); return true; } catch (Exception e) { conn.Disconnect(); return false; } } } return false; }, cancellationToken)); }
public static Task <bool> ModifyAsync(string oldUsername, string username, string password, string nombre, string apellido, string email) { CancellationTokenSource cts = new CancellationTokenSource(); CancellationToken cancellationToken = cts.Token; LdapConnection conn = null; return(Task.Factory.StartNew(() => { conn = new LdapConnection(); conn.Connect(Host, Port); if (!string.IsNullOrEmpty(username)) { try { conn.Bind(dn, pa); } catch (Exception e) { conn.Disconnect(); return false; } string searchBase = filter; int searchScope = LdapConnection.ScopeSub; string searchFilter = "uid=" + username.Trim(); LdapSearchQueue queue = conn.Search(searchBase, searchScope, searchFilter, null, false, (LdapSearchQueue)null, (LdapSearchConstraints)null); LdapMessage message; while ((message = queue.GetResponse()) != null) { try { string msg = message.ToString(); LdapEntry entry = ((LdapSearchResult)message).Entry; LdapAttributeSet attributeSet = entry.GetAttributeSet(); System.Collections.IEnumerator ienum = attributeSet.GetEnumerator(); LdapAttribute cn = attributeSet.GetAttribute("cn"); string idUser = cn.StringValue; try { conn.Delete("cn=" + idUser + "," + filter); LdapAttributeSet ldapAttributeSet = new LdapAttributeSet(); ldapAttributeSet.Add(new LdapAttribute("cn", nombre + " " + apellido)); ldapAttributeSet.Add(new LdapAttribute("sn", username)); ldapAttributeSet.Add(new LdapAttribute("homeDirectory", "/home/users/" + username)); ldapAttributeSet.Add(new LdapAttribute("objectClass", new string[] { "inetOrgPerson", "posixAccount", "top" })); ldapAttributeSet.Add(new LdapAttribute("uid", username)); ldapAttributeSet.Add(new LdapAttribute("givenName", nombre)); ldapAttributeSet.Add(new LdapAttribute("uidNumber", "1000")); ldapAttributeSet.Add(new LdapAttribute("gidNumber", "500")); ldapAttributeSet.Add(new LdapAttribute("mail", email)); ldapAttributeSet.Add(new LdapAttribute("userPassword", password)); LdapEntry ldapEntry = new LdapEntry("cn=" + nombre + " " + apellido + "," + filter, ldapAttributeSet); conn.Add(ldapEntry); } catch (Exception e) { conn.Disconnect(); return false; } conn.Disconnect(); return true; } catch (Exception e) { conn.Disconnect(); return false; } } } return false; }, cancellationToken)); }
public static string SearchLDAP(string ldapHost, string port, string loginDN, string password, string searchBase, string searchFilter) { int ldapPort = System.Convert.ToInt32(port); LogToFile("************ DeviceEntry started: ldapHost = " + ldapHost + " ************"); try { LdapConnection conn = new LdapConnection(); Console.WriteLine("Connecting to:" + ldapHost); LogToFile("DeviceEntry: Connecting to:" + ldapHost); conn.Connect(ldapHost, ldapPort); conn.Bind(loginDN, password); LdapSearchResults lsc = conn.Search(searchBase, LdapConnection.SCOPE_SUB, searchFilter, null, false); while (lsc.hasMore()) { Console.WriteLine("DAF:lsc.hasMore\n"); LogToFile("\n"); LdapEntry nextEntry = null; try { nextEntry = lsc.next(); } catch (LdapException e) { Console.WriteLine("LdapException: " + e.LdapErrorMessage); LogToFile("DeviceEntry:LdapInfo " + e.LdapErrorMessage); // Exception is thrown, go for next entry continue; } Console.WriteLine("*********************************\n" + nextEntry.DN); LogToFile("DeviceEntry:" + nextEntry.DN); LdapAttributeSet attributeSet = nextEntry.getAttributeSet(); System.Collections.IEnumerator ienum = attributeSet.GetEnumerator(); while (ienum.MoveNext()) { LdapAttribute attribute = (LdapAttribute)ienum.Current; string attributeName = attribute.Name; string attributeVal = attribute.StringValue; if (!Base64.isLDIFSafe(attributeVal)) { byte[] tbyte = SupportClass.ToByteArray(attributeVal); attributeVal = Base64.encode(SupportClass.ToSByteArray(tbyte)); } Console.WriteLine(attributeName + " value = :" + attributeVal); LogToFile("DeviceEntry: Attribute:" + attributeName + ": value = :" + attributeVal); } } conn.Disconnect(); } catch (LdapException e) { Console.WriteLine("Error:" + e.LdapErrorMessage); LogToFile("DeviceEntry:LdapInfo:" + e.LdapErrorMessage); return("Error"); } catch (Exception e) { Console.WriteLine("Error:" + e.Message); LogToFile("DeviceEntry:Exception Error:" + e.Message); return("Error"); } LogToFile("\n"); return("OK"); }
public static void Main(System.String[] args) { /* Check if we have the correct number of command line arguments */ if (args.Length < 4) { System.Console.Error.WriteLine("Usage: mono PGControl <host name> <login dn>" + " <password> <container> [ssl]"); System.Console.Error.WriteLine("Example: mono PGControl Acme.com \"cn=admin,o=Acme\" secret" + " \"ou=Sales,o=Acme\""); System.Console.Error.WriteLine("\tfor test over a secure connection add SSL argument"); System.Console.Error.WriteLine("Example: mono PGControl Acme.com \"cn=admin,o=Acme\" secret" + " \"ou=Sales,o=Acme\" ssl"); System.Environment.Exit(1); } /* Parse the command line arguments */ System.String LdapHost = args[0]; System.String loginDN = args[1]; System.String password = args[2]; System.String searchBase = args[3]; System.Boolean ssl = false; if (args.Length == 5 && String.Equals(args[4], "ssl", StringComparison.OrdinalIgnoreCase)) { ssl = true; } /*System.String LdapHost = "23.20.46.132"; * System.String loginDN = "cn=read-only-admin, dc=example,dc=com"; * System.String password = "******"; * System.String searchBase = "dc=example,dc=com";*/ /*System.String LdapHost = @"192.168.50.133"; * System.String loginDN = @"*****@*****.**"; * System.String password = @"admin1!"; * System.String searchBase = @"dc=rem,dc=dev";*/ int LdapPort = LdapConnection.DEFAULT_PORT; // If user asked for LDAPS, change the port if (ssl) { LdapPort = LdapConnection.DEFAULT_SSL_PORT; } int LdapVersion = LdapConnection.Ldap_V3; LdapConnection conn = new LdapConnection(); try { // turn SSL on/off conn.SecureSocketLayer = ssl; // We don't require a valided SSL certificate to run the sample // If our certificated is not validated by a CA, we want to validate it ourselves. if (ssl) { conn.UserDefinedServerCertValidationDelegate += new CertificateValidationCallback(ValidationCallback); } conn.Connect(LdapHost, LdapPort); // bind to the server conn.Bind(LdapVersion, loginDN, password); System.Console.Out.WriteLine("Successfully logged in to server: " + LdapHost); /* * Set default filter - Change this line if you need a different set * of search restrictions. Read the "NDS and Ldap Integration Guide" * for information on support by Novell eDirectory of this * functionaliry. */ System.String MY_FILTER = "cn=*"; /* * We are requesting that the givenname and cn fields for each * object be returned */ System.String[] attrs = new System.String[3]; attrs[0] = "givenName"; attrs[1] = "cn"; attrs[2] = "gidNumber"; // We will be sending two controls to the server LdapSearchConstraints cons = conn.SearchConstraints; // hardcoded results page size int pageSize = 2; // initially, cookie must be set to an empty string System.String cookie = ""; do { LdapControl[] requestControls = new LdapControl[1]; requestControls[0] = new LdapPagedResultsControl(pageSize, cookie); cons.setControls(requestControls); conn.Constraints = cons; // Send the search request - Synchronous Search is being used here //System.Console.Out.WriteLine("Calling Asynchronous Search..."); LdapSearchResults res = conn.Search(searchBase, LdapConnection.SCOPE_SUB, MY_FILTER, attrs, false, (LdapSearchConstraints)null); // Loop through the results and print them out while (res.hasMore()) { /* * Get next returned entry. Note that we should expect a Ldap- * Exception object as well, just in case something goes wrong */ LdapEntry nextEntry = null; try { nextEntry = res.next(); } catch (LdapException e) { if (e is LdapReferralException) { continue; } else { System.Console.Out.WriteLine("Search stopped with exception " + e.ToString()); break; } } /* Print out the returned Entries distinguished name. */ System.Console.Out.WriteLine(); System.Console.Out.WriteLine(nextEntry.DN); /* Get the list of attributes for the current entry */ LdapAttributeSet findAttrs = nextEntry.getAttributeSet(); /* Convert attribute list to Enumeration */ System.Collections.IEnumerator enumAttrs = findAttrs.GetEnumerator(); System.Console.Out.WriteLine("Attributes: "); /* Loop through all attributes in the enumeration */ while (enumAttrs.MoveNext()) { LdapAttribute anAttr = (LdapAttribute)enumAttrs.Current; /* Print out the attribute name */ System.String attrName = anAttr.Name; // if (attrName != "cn") // continue; // System.Console.Out.Write("\t{0}: ", attrName); System.Console.Out.Write("" + attrName); // Loop through all values for this attribute and print them System.Collections.IEnumerator enumVals = anAttr.StringValues; while (enumVals.MoveNext()) { System.String aVal = (System.String)enumVals.Current; System.Console.Out.Write(" = {0}; ", aVal); } System.Console.Out.WriteLine(""); } } // Server should send back a control irrespective of the // status of the search request LdapControl[] controls = res.ResponseControls; if (controls == null) { System.Console.Out.WriteLine("No controls returned"); } else { // Multiple controls could have been returned foreach (LdapControl control in controls) { /* Is this the LdapPagedResultsResponse control? */ if (control is LdapPagedResultsResponse) { LdapPagedResultsResponse response = new LdapPagedResultsResponse(control.ID, control.Critical, control.getValue()); cookie = response.Cookie; // Cookie is an opaque octet string. The chacters it contains might not be printable. byte[] hexCookie = System.Text.Encoding.ASCII.GetBytes(cookie); StringBuilder hex = new StringBuilder(hexCookie.Length); foreach (byte b in hexCookie) { hex.AppendFormat("{0:x}", b); } System.Console.Out.WriteLine("Cookie: {0}", hex.ToString()); System.Console.Out.WriteLine("Size: {0}", response.Size); } } } // if cookie is empty, we are done. } while (!String.IsNullOrEmpty(cookie)); /* We are done - disconnect */ if (conn.Connected) { conn.Disconnect(); } } catch (LdapException e) { System.Console.Out.WriteLine(e.ToString()); } catch (System.IO.IOException e) { System.Console.Out.WriteLine("Error: " + e.ToString()); } catch (Exception e) { System.Console.WriteLine("Error: " + e.Message); } }
public static void UserList(string objectDN, string password, string searchBase) { LdapConnection conn = new LdapConnection(); try { Console.WriteLine("Connecting to " + ldapHost); // Connect to the LDAP server using the host and the port // ldap//<host>:<port> conn.Connect(ldapHost, ldapPort); conn.Bind(objectDN, password); string[] requiredAttributes = { "cn", "sn", "uid", "userPassword" }; string searchFilter = "objectClass=inetOrgPerson"; ILdapSearchResults lsc = conn.Search(searchBase, LdapConnection.ScopeSub, searchFilter, requiredAttributes, false); while (lsc.HasMore()) { LdapEntry nextEntry = null; try { nextEntry = lsc.Next(); } catch (LdapException e) { Console.WriteLine("Error : " + e.LdapErrorMessage); continue; } Console.WriteLine("\n" + nextEntry.Dn); LdapAttributeSet attributeSet = nextEntry.GetAttributeSet(); IEnumerator ienum = attributeSet.GetEnumerator(); while (ienum.MoveNext()) { LdapAttribute attribute = (LdapAttribute)ienum.Current; string attributeName = attribute.Name; string attributeVal = attribute.StringValue; Console.WriteLine("\t" + attributeName + "\tvalue = \t" + attributeVal); } } conn.Disconnect(); } catch (LdapException e) { Console.WriteLine("Error: " + e.LdapErrorMessage); return; } catch (Exception e) { Console.WriteLine("Error: " + e.Message); return; } finally { conn.Disconnect(); } }
/// <summary> /// Find user in Active Directory by using UPN /// </summary> /// <param name="userPrincipalName">UserPrincipalName of user</param> /// <returns>Return CustomUser object</returns> public static async Task <ApplicationUser> FindByUserPrincipalNameAsync(string userPrincipalName) { string loginDN = AuthenticationSettings.LDAPLoginUPN; string password = AuthenticationSettings.LDAPLoginPassword; string searchBase = AuthenticationSettings.LDAPHostServerSearchBase; string searchFilter = "(userPrincipalName=" + userPrincipalName + ")"; ApplicationUser objApplicationUser = new ApplicationUser(); LdapSearchResults lsc = null; using (LdapConnection conn = ActiveDirectoryHelper.GetLDAPConnnection()) { conn.Bind(loginDN, password); lsc = conn.Search(searchBase, LdapConnection.SCOPE_SUB, searchFilter, null, false); // Only one record yield if search through UPN in active directory while (lsc.hasMore()) { LdapEntry nextEntry = null; nextEntry = lsc.next(); LdapAttributeSet attributeSet = nextEntry.getAttributeSet(); System.Collections.IEnumerator ienum = attributeSet.GetEnumerator(); Dictionary <string, string> adProperties = new Dictionary <string, string>(); while (ienum.MoveNext()) { LdapAttribute attribute = (LdapAttribute)ienum.Current; string attributeName = attribute.Name; string attributeVal = attribute.StringValue; if (!Base64.isLDIFSafe(attributeVal)) { byte[] tbyte = SupportClass.ToByteArray(attributeVal); attributeVal = Base64.encode(SupportClass.ToSByteArray(tbyte)); } adProperties.Add(attributeName, attributeVal); } string objectSid = string.Empty; string givenName = string.Empty; string sn = string.Empty; string upn = string.Empty; adProperties.TryGetValue("objectSid", out objectSid); adProperties.TryGetValue("givenName", out givenName); adProperties.TryGetValue("sn", out sn); adProperties.TryGetValue("userPrincipalName", out upn); objApplicationUser.ObjectSid = objectSid; objApplicationUser.FirstName = givenName; objApplicationUser.LastName = sn; objApplicationUser.UserPrincipalName = upn; await Task.Yield(); return(objApplicationUser); } } return(null); }
private void DoSearch() { InitBlock(); String[] attrs = new String[PropertiesToLoad.Count]; PropertiesToLoad.CopyTo(attrs, 0); LdapSearchConstraints cons = _conn.SearchConstraints; if (SizeLimit > 0) { cons.MaxResults = SizeLimit; } if (ServerTimeLimit != DefaultTimeSpan) { cons.ServerTimeLimit = (int)ServerTimeLimit.TotalSeconds; } int connScope = LdapConnection.SCOPE_SUB; switch (_SearchScope) { case SearchScope.Base: connScope = LdapConnection.SCOPE_BASE; break; case SearchScope.OneLevel: connScope = LdapConnection.SCOPE_ONE; break; case SearchScope.Subtree: connScope = LdapConnection.SCOPE_SUB; break; default: connScope = LdapConnection.SCOPE_SUB; break; } LdapSearchResults lsc = _conn.Search(SearchRoot.Fdn, connScope, Filter, attrs, PropertyNamesOnly, cons); while (lsc.hasMore()) { LdapEntry nextEntry = null; try { nextEntry = lsc.next(); } catch (LdapException e) { switch (e.ResultCode) { // in case of this return codes exception should not be thrown case LdapException.SIZE_LIMIT_EXCEEDED: case LdapException.TIME_LIMIT_EXCEEDED: case LdapException.REFERRAL: continue; default: throw e; } } DirectoryEntry de = new DirectoryEntry(_conn); PropertyCollection pcoll = new PropertyCollection(); // de.SetProperties(); de.Path = DirectoryEntry.GetLdapUrlString(_Host, _Port, nextEntry.DN); LdapAttributeSet attributeSet = nextEntry.getAttributeSet(); System.Collections.IEnumerator ienum = attributeSet.GetEnumerator(); if (ienum != null) { while (ienum.MoveNext()) { LdapAttribute attribute = (LdapAttribute)ienum.Current; string attributeName = attribute.Name; pcoll[attributeName].AddRange(attribute.StringValueArray); // de.Properties[attributeName].AddRange(attribute.StringValueArray); // de.Properties[attributeName].Mbit=false; } } if (!pcoll.Contains("ADsPath")) { pcoll["ADsPath"].Add(de.Path); } // _SrchColl.Add(new SearchResult(de,PropertiesToLoad)); _SrchColl.Add(new SearchResult(de, pcoll)); } return; }
static void Main(string[] args) { if (args.Length != 6) { Console.WriteLine("Usage: mono SortSearch <host name> <ldap port> <login dn>" + " <password> <search base>" + " <search filter>"); Console.WriteLine("Example: mono SortSearch Acme.com 389" + " \"cn=admin,o=Acme\"" + " secret \"ou=sales,o=Acme\"" + " \"(objectclass=*)\""); return; } string ldapHost = args[0]; int ldapPort = System.Convert.ToInt32(args[1]); String loginDN = args[2]; String password = args[3]; String searchBase = args[4]; String searchFilter = args[5]; String[] attrs = new String[1]; attrs[0] = "sn"; LdapSortKey[] keys = new LdapSortKey[1]; keys[0] = new LdapSortKey("sn"); try { LdapConnection conn = new LdapConnection(); conn.Connect(ldapHost, ldapPort); conn.Bind(loginDN, password); // Create a LDAPSortControl object - Fail if cannot sort LdapSortControl sort = new LdapSortControl(keys, true); // Set the Sort control to be sent as part of search request LdapSearchConstraints cons = conn.SearchConstraints; cons.setControls(sort); conn.Constraints = cons; Console.WriteLine("Connecting to:" + ldapHost); LdapSearchResults lsc = conn.Search(searchBase, LdapConnection.SCOPE_SUB, searchFilter, attrs, false, (LdapSearchConstraints)null); while (lsc.hasMore()) { LdapEntry nextEntry = null; try { nextEntry = lsc.next(); } catch (LdapException e) { Console.WriteLine("Error: " + e.LdapErrorMessage); // Exception is thrown, go for next entry continue; } Console.WriteLine("\n" + nextEntry.DN); LdapAttributeSet attributeSet = nextEntry.getAttributeSet(); System.Collections.IEnumerator ienum = attributeSet.GetEnumerator(); while (ienum.MoveNext()) { LdapAttribute attribute = (LdapAttribute)ienum.Current; string attributeName = attribute.Name; string attributeVal = attribute.StringValue; Console.WriteLine(attributeName + "value:" + attributeVal); } } conn.Disconnect(); } catch (LdapException e) { Console.WriteLine("Error:" + e.LdapErrorMessage); Console.WriteLine("Error:" + e.ToString()); return; } catch (Exception e) { Console.WriteLine("Error:" + e.Message); return; } }
public GxSimpleCollection <string> GetAttribute(string name, string context, GXProperties atts) { string filter = ""; if (atts.Count == 0) { filter = "(" + name + "=*)"; } else { for (int i = 0; i < atts.Count; i++) { filter += "(" + atts.GetKey(i).Trim() + "=" + atts[i].Trim() + ")"; } if (atts.Count > 1) { filter = "(&" + filter + ")"; } } GxSimpleCollection <string> sc = new GxSimpleCollection <string>(); try { #if NETCORE if (!GXUtil.IsWindowsPlatform) { NovellConnect(); string searchBase = context; int searchScope = LdapConnection.ScopeSub; string searchFilter = filter; ILdapSearchResults lsc = _conn.Search(searchBase, searchScope, searchFilter, new string[] { name }, false); while (lsc.HasMore()) { LdapEntry nextEntry = null; try { nextEntry = lsc.Next(); } catch (LdapException) { continue; } LdapAttributeSet attributeSet = nextEntry.GetAttributeSet(); IEnumerator ienum = attributeSet.GetEnumerator(); StringBuilder sb = new StringBuilder(); while (ienum.MoveNext()) { LdapAttribute attribute = (LdapAttribute)ienum.Current; string attributeVal = attribute.StringValue; sb.Append(attributeVal + " "); } sc.Add(sb.ToString() + " "); } } else #endif { if (_entry != null) { _entry.Close(); _entry = null; } string context1; if (context.Trim().Length == 0) { context1 = ""; } else { context1 = "/" + context; } AuthenticationTypes at = getAuthentication(); _entry = new DirectoryEntry("LDAP://" + getPath() + context1, _user, _password, at); DirectorySearcher ds = new DirectorySearcher(_entry, filter, new string[] { name }); foreach (SearchResult result in ds.FindAll()) { PropertyValueCollection values = (PropertyValueCollection)(result.GetDirectoryEntry().Properties[name]); StringBuilder sb = new StringBuilder(); for (int i = 0; i < values.Count; i++) { sb.Append(values[i].ToString() + " "); } sc.Add(sb.ToString()); } } } catch (Exception ex) { GXLogging.Error(log, "GetAttribute Method Error.", ex); } return(sc); }
private async Task <bool> FindUser(string userName, LdapAuthenticationModeModel ldapAuthenticationMode, string password, bool testLogin, bool syncLdapAttributes) { try { var adminDistinguishedName = $"cn={ldapAuthenticationMode.Account},{ldapAuthenticationMode.BaseDn}"; // Search for user in directory var searchBase = $"{ldapAuthenticationMode.BaseDn}"; var searchFilter = $"(cn = {userName})"; try { logger.Info($"Attempting to connect to LDAP connection. Hostname '{ldapAuthenticationMode.HostName}', Port '{ldapAuthenticationMode.Port}'"); ldapConnectionClient.Connect(ldapAuthenticationMode.HostName, ldapAuthenticationMode.Port); logger.Info($"Attempting to bind with DN '{adminDistinguishedName}'"); ldapConnectionClient.Bind(adminDistinguishedName, ldapAuthenticationMode.Password); } catch (Exception ex) { // User not authenticated logger.Error(ex, "LDAP admin account user not authenticated."); return(false); } LdapSearchResults lsc = ldapConnectionClient.Search(searchBase, LdapConnection.SCOPE_SUB, searchFilter, null, false); while (lsc.hasMore()) { LdapEntry ldapEntry; try { ldapEntry = lsc.next(); } catch (LdapException ex) { logger.Warn("Warning on LDAP search: " + ex.LdapErrorMessage); continue; } // User found, try to log in if (testLogin) { try { logger.Info($"Attempting to connect to LDAP connection. Hostname '{ldapAuthenticationMode.HostName}', Port '{ldapAuthenticationMode.Port}'"); ldapTestConnectionClient.Connect(ldapAuthenticationMode.HostName, ldapAuthenticationMode.Port); logger.Info($"Attempting to bind with DN '{ldapEntry.DN}'"); ldapTestConnectionClient.Bind(ldapEntry.DN, password); } catch (Exception ex) { // User not authenticated logger.Error(ex, "LDAP user not authenticated."); return(false); } } // Login successful. Sync attributes if (syncLdapAttributes) { LdapAttributeSet attributeSet = ldapEntry.getAttributeSet(); System.Collections.IEnumerator ienum = attributeSet.GetEnumerator(); var attributeValues = new Dictionary <string, string>(); while (ienum.MoveNext()) { var attribute = (LdapAttribute)ienum.Current; attributeValues.Add(attribute.Name, attribute.StringValue); } await SyncLdapAttributeToUserField(userName, ldapAuthenticationMode.LdapAttributes, attributeValues); } return(true); } // If we reached this point, we were not able authenticate the user return(false); } catch (Exception ex) { logger.Error(ex, "General error during LDAP authentication process."); return(false); } }
public static DomainObject ConvertLDAPProperty(LdapEntry result) { DomainObject obj = new DomainObject(); LdapAttributeSet attributeSet = result.getAttributeSet(); System.Collections.IEnumerator ienum = attributeSet.GetEnumerator(); while (ienum.MoveNext()) { LdapAttribute attr = (LdapAttribute)ienum.Current; switch (attr.Name.ToLower()) { case "objectsid": //Will need to convert this to a string obj.objectsid = attr.StringValue; break; case "sidhistory": obj.sidhistory = attr.StringValueArray; break; case "grouptype": obj.grouptype = (GroupTypeEnum)Enum.Parse(typeof(GroupTypeEnum), attr.StringValue); break; case "samaccounttype": obj.samaccounttype = (SamAccountTypeEnum)Enum.Parse(typeof(SamAccountTypeEnum), attr.StringValue); break; case "objectguid": //Will need to conver this to a string obj.objectguid = attr.StringValue; break; case "useraccountcontrol": //convertme break; case "ntsecuritydescriptor": //convertme break; case "accountexpires": if (long.Parse(attr.StringValue) >= DateTime.MaxValue.Ticks) { obj.accountexpires = DateTime.MaxValue; } try { obj.accountexpires = DateTime.FromFileTime(long.Parse(attr.StringValue)); } catch (ArgumentOutOfRangeException) { obj.accountexpires = DateTime.MaxValue; } break; case "lastlogon": DateTime dateTime = DateTime.MinValue; //Not sure if this syntax is right. if (attr.StringValues.GetType().Name == "System.MarshalByRefObject") { var comobj = (MarshalByRefObject)attr.StringValues; int high = (int)comobj.GetType().InvokeMember("HighPart", System.Reflection.BindingFlags.GetProperty, null, comobj, null); int low = (int)comobj.GetType().InvokeMember("LowPart", System.Reflection.BindingFlags.GetProperty, null, comobj, null); dateTime = DateTime.FromFileTime(int.Parse("0x" + high + "" + low, System.Globalization.NumberStyles.HexNumber)); } else { dateTime = DateTime.FromFileTime(long.Parse(attr.StringValue)); } obj.lastlogon = dateTime; break; case "pwdlastset": if (attr.StringValues.GetType().Name == "System.MarshalByRefObject") { var comobj = (MarshalByRefObject)attr.StringValues; int high = (int)comobj.GetType().InvokeMember("HighPart", System.Reflection.BindingFlags.GetProperty, null, comobj, null); int low = (int)comobj.GetType().InvokeMember("LowPart", System.Reflection.BindingFlags.GetProperty, null, comobj, null); dateTime = DateTime.FromFileTime(int.Parse("0x" + high + "" + low, System.Globalization.NumberStyles.HexNumber)); } else { dateTime = DateTime.FromFileTime(long.Parse(attr.StringValue)); } obj.pwdlastset = dateTime; break; case "lastlogoff": if (attr.StringValues.GetType().Name == "System.MarshalByRefObject") { var comobj = (MarshalByRefObject)attr.StringValues; int high = (int)comobj.GetType().InvokeMember("HighPart", System.Reflection.BindingFlags.GetProperty, null, comobj, null); int low = (int)comobj.GetType().InvokeMember("LowPart", System.Reflection.BindingFlags.GetProperty, null, comobj, null); dateTime = DateTime.FromFileTime(int.Parse("0x" + high + "" + low, System.Globalization.NumberStyles.HexNumber)); } else { dateTime = DateTime.FromFileTime(long.Parse(attr.StringValue)); } obj.lastlogoff = dateTime; break; case "badpasswordtime": if (attr.StringValues.GetType().Name == "System.MarshalByRefObject") { var comobj = (MarshalByRefObject)attr.StringValues; int high = (int)comobj.GetType().InvokeMember("HighPart", System.Reflection.BindingFlags.GetProperty, null, comobj, null); int low = (int)comobj.GetType().InvokeMember("LowPart", System.Reflection.BindingFlags.GetProperty, null, comobj, null); dateTime = DateTime.FromFileTime(int.Parse("0x" + high + "" + low, System.Globalization.NumberStyles.HexNumber)); } else { dateTime = DateTime.FromFileTime(long.Parse(attr.StringValue)); } obj.badpasswordtime = dateTime; break; default: { string property = "0"; if (attr.StringValue.GetType().Name == "System.MarshalByRefObject") { var comobj = (MarshalByRefObject)attr.StringValues; int high = (int)comobj.GetType().InvokeMember("HighPart", System.Reflection.BindingFlags.GetProperty, null, comobj, null); int low = (int)comobj.GetType().InvokeMember("LowPart", System.Reflection.BindingFlags.GetProperty, null, comobj, null); property = int.Parse("0x" + high + "" + low, System.Globalization.NumberStyles.HexNumber).ToString(); } else if (attr.StringValueArray.Length == 1) { property = attr.StringValueArray[0]; } else { List <string> propertyList = new List <string>(); foreach (object prop in attr.StringValueArray) { propertyList.Add(prop.ToString()); } property = String.Join(", ", propertyList.ToArray()); } string attribName = attr.Name.ToLower(); if (attribName == "samaccountname") { obj.samaccountname = property; } else if (attribName == "distinguishedname") { obj.distinguishedname = property; } else if (attribName == "cn") { obj.cn = property; } else if (attribName == "admincount") { obj.admincount = property; } else if (attribName == "serviceprincipalname") { obj.serviceprincipalname = property; } else if (attribName == "name") { obj.name = property; } else if (attribName == "description") { obj.description = property; } else if (attribName == "memberof") { obj.memberof = property; } else if (attribName == "logoncount") { obj.logoncount = property; } else if (attribName == "badpwdcount") { obj.badpwdcount = property; } else if (attribName == "whencreated") { obj.whencreated = property; } else if (attribName == "whenchanged") { obj.whenchanged = property; } else if (attribName == "codepage") { obj.codepage = property; } else if (attribName == "objectcategory") { obj.objectcategory = property; } else if (attribName == "usnchanged") { obj.usnchanged = property; } else if (attribName == "instancetype") { obj.instancetype = property; } else if (attribName == "objectclass") { obj.objectclass = property; } else if (attribName == "iscriticalsystemobject") { obj.iscriticalsystemobject = property; } else if (attribName == "usncreated") { obj.usncreated = property; } else if (attribName == "dscorepropagationdata") { obj.dscorepropagationdata = property; } else if (attribName == "adspath") { obj.adspath = property; } else if (attribName == "countrycode") { obj.countrycode = property; } else if (attribName == "primarygroupid") { obj.primarygroupid = property; } else if (attribName == "msds_supportedencryptiontypes") { obj.msds_supportedencryptiontypes = property; } else if (attribName == "showinadvancedviewonly") { obj.showinadvancedviewonly = property; } } break; } } return(obj); }
/// <summary> /// For given user entry, attach all ldap properties /// </summary> /// <param name="conn">ldap connection</param> /// <param name="entry">entry to be processed</param> /// <param name="group">group </param> /// <param name="groupList">list of all groups</param> private void ProcessUserEntry(LdapConnection conn, LdapEntry entry, string group, string groupList) { log.Debug("ProcessUserEntry(" + entry.DN + ")"); string commonName = String.Empty; string firstName = null; string lastName = null; string fullName = null; string distinguishedName = String.Empty; string ldapGuid = null; bool Group = false; string groupmembers = String.Empty; string groupmembership = String.Empty; string iFolderHomeServer = String.Empty; char[] dnDelimiters = { ',', '=' }; LdapAttribute timeStampAttr = null; bool attrError = false; string FullNameDisplay = ""; store = Store.GetStore(); Domain domain = store.GetDomain(store.DefaultDomain); if (domain != null) { FullNameDisplay = domain.UsersFullNameDisplay; } try { // get the last update time timeStampAttr = entry.getAttribute("modifytimestamp"); ldapGuid = GetLdapGuid(entry); distinguishedName = entry.DN; // retrieve from configuration the directory attribute configured // for naming in Simias. LdapAttribute cAttr = entry.getAttribute(ldapSettings.NamingAttribute); if (cAttr != null && cAttr.StringValue.Length != 0) { commonName = cAttr.StringValue; } else if (ldapSettings.NamingAttribute.ToLower() == LdapSettings.DefaultNamingAttribute.ToLower()) { // If the naming attribute is default (cn) then we want to continue // to work the way we previously did so we don't break any existing installs. // // If the distinguishing attribute did not exist, // then make the Simias username the first component // of the ldap DN. string[] components = entry.DN.Split(dnDelimiters); commonName = components[1]; } LdapAttribute givenAttr = entry.getAttribute("givenName"); if (givenAttr != null && givenAttr.StringValue.Length != 0) { firstName = givenAttr.StringValue as string; } LdapAttribute sirAttr = entry.getAttribute("sn"); if (sirAttr != null && sirAttr.StringValue.Length != 0) { lastName = sirAttr.StringValue as string; } LdapAttribute objectAttr = entry.getAttribute("objectclass"); String[] values = objectAttr.StringValueArray; if (IsGroup(values) == true) { Group = true; } LdapAttribute iFolderHomeAttr = entry.getAttribute("iFolderHomeServer"); if (iFolderHomeAttr != null && iFolderHomeAttr.StringValue.Length != 0) { iFolderHomeServer = iFolderHomeAttr.StringValue as string; } if (Group == true) { if (isGropuAlreadyprocessed(groupList, distinguishedName) == true) { return; } LdapAttributeSet attributeSet = entry.getAttributeSet(); System.Collections.IEnumerator ienum = attributeSet.GetEnumerator(); while (ienum.MoveNext()) { LdapAttribute attribute = (LdapAttribute)ienum.Current; string attributeName = attribute.Name; System.Collections.IEnumerator enumVals = attribute.StringValues; if (attributeName.ToLower() == "member" || attributeName.ToLower() == "uniquemember") { while (enumVals.MoveNext()) { if (isGropuAlreadyprocessed(groupList, (System.String)enumVals.Current) == false) { groupmembers += (System.String)enumVals.Current; groupmembers += ";"; } } } } groupList += distinguishedName; groupList += ";"; ProcessSearchGroup(conn, groupmembers, distinguishedName, groupList); } if (group != null && group != String.Empty) { groupmembership = group; groupmembership += ";"; } if (firstName != null && lastName != null) { if (FullNameDisplay == "FirstNameLastName") { fullName = firstName + " " + lastName; } else { fullName = lastName + " " + firstName; } } else { fullName = commonName; } } catch (Exception gEx) { log.Error(gEx.Message); log.Error(gEx.StackTrace); state.ReportError(gEx.Message); attrError = true; } // No exception were generated gathering member info // so call the sync engine to process this member if (attrError == false) { if (timeStampAttr != null && timeStampAttr.StringValue.Length != 0) { Property ts = new Property("LdapTimeStamp", timeStampAttr.StringValue); ts.LocalProperty = true; Property[] propertyList = { ts }; state.ProcessMember( ldapGuid, commonName, firstName, lastName, fullName, distinguishedName, propertyList, Group, groupmembers, groupmembership, iFolderHomeServer); } else { state.ProcessMember( ldapGuid, commonName, firstName, lastName, fullName, distinguishedName, null, Group, groupmembers, groupmembership, iFolderHomeServer); } } }
public LDAPUser GetUserData(string sAMAccountName) { LDAPUser user = new LDAPUser(); string dn = Environment.GetEnvironmentVariable("BIND_DN"); string dnPass = Environment.GetEnvironmentVariable("BIND_DN_PASSWORD"); string ldapHost = Environment.GetEnvironmentVariable("LDAP_HOST"); string ldapSearchBase = Environment.GetEnvironmentVariable("LDAP_SEARCH_BASE"); LdapConnection conn = new LdapConnection(); conn.Connect(ldapHost, LdapConnection.DEFAULT_PORT); conn.Bind(dn, dnPass); LdapSearchResults lsc = conn.Search(ldapSearchBase, LdapConnection.SCOPE_SUB, "sAMAccountName=" + sAMAccountName, null, false); while (lsc.hasMore()) { LdapEntry nextEntry = null; try { nextEntry = lsc.next(); } catch (LdapException e) { Console.WriteLine("Error: " + e.LdapErrorMessage); // Exception is thrown, go for next entry continue; } user.DN = nextEntry.DN; LdapAttributeSet attributeSet = nextEntry.getAttributeSet(); System.Collections.IEnumerator ienum = attributeSet.GetEnumerator(); while (ienum.MoveNext()) { LdapAttribute attribute = (LdapAttribute)ienum.Current; string attributeName = attribute.Name; string attributeVal = attribute.StringValue; if (!Base64.isLDIFSafe(attributeVal)) { byte[] tbyte = SupportClass.ToByteArray(attributeVal); attributeVal = Base64.encode(SupportClass.ToSByteArray(tbyte)); } if (attributeName == "mail") { user.Email = attributeVal; } if (attributeName == "cn") { user.FullName = attributeVal; } if (attributeName == "sAMAccountName") { user.UserName = attributeVal; } } } conn.Disconnect(); return(user); }
private async Task <bool> ValidateCredentialsAsync(string uid, TTenant tenant) { _logger.Info("ValidateCredentialsAsync against ldap host"); int ldapPort = await _settings.GetLdapServerPort(tenant?.Id); string ldapHost = await _settings.GetLdapHost(tenant?.Id); var loginDN = await _settings.GetLdapLoginDn(tenant?.Id); var loginPassword = await _settings.GetPassword(tenant?.Id); var ldapSearchBase = await _settings.GetLdapUserSearchBase(tenant?.Id); string searchLdapUser = uid; string searchFilter = "(objectclass=*)"; string searchBase = $"uid={searchLdapUser}, {ldapSearchBase}"; // "ou = scientists, dc = example, dc = com"; //"uid=gauss, dc=example, dc=com"; LdapSearchConstraints constraints = new LdapSearchConstraints { }; try { using (var cn = new LdapConnection()) { // connect cn.Connect(ldapHost, ldapPort); cn.Bind(loginDN, loginPassword); LdapSearchResults searchResults = cn.Search( searchBase, LdapConnection.SCOPE_SUB, searchFilter, null, // no specified attributes false, // false = return attr and value constraints); while (searchResults.HasMore()) { if (searchResults.Count == 1) { LdapEntry nextEntry = null; try { nextEntry = searchResults.Next(); } catch (LdapException e) { _logger.Error("Error: " + e.LdapErrorMessage); //Exception is thrown, go for next entry continue; } LdapEntries = new Dictionary <string, string>(); _logger.Debug(nextEntry.DN); // Get the attribute set of the entry LdapAttributeSet attributeSet = nextEntry.getAttributeSet(); System.Collections.IEnumerator ienum = attributeSet.GetEnumerator(); // Parse through the attribute set to get the attributes and the corresponding values while (ienum.MoveNext()) { LdapAttribute attribute = (LdapAttribute)ienum.Current; string attributeName = attribute.Name; string attributeVal = attribute.StringValue; _logger.Debug(attributeName + "value:" + attributeVal); LdapEntries.Add(attributeName, attributeVal); } return(true); } } } } catch (LdapException ldapEx) { throw new AbpException(ldapEx.ToString()); // ocassional time outs } catch (Exception ex) { throw new AbpException(ex.ToString()); } return(false); }
public static void Main(String[] args) { if (args.Length != 4) { Console.WriteLine("Usage: mono ListGroups <host name> <login dn>" + " <password> <group dn>\n"); Console.WriteLine("Example: mono ListGroups Acme.com" + " \"cn=admin,o=Acme\" secret " + " cn=salesGroup,ou=sales,o=acme\n"); Environment.Exit(0); } int ldapPort = LdapConnection.DEFAULT_PORT; int searchScope = LdapConnection.SCOPE_BASE; int ldapVersion = LdapConnection.Ldap_V3; int i; IEnumerator objClass = null; IEnumerator queryURL = null; IEnumerator identity = null; IEnumerator excludedMember = null; IEnumerator member = null; bool isGroup = false, isDynamicGroup = false; String[] attrs = new String[] { "objectClass", "memberQueryURL", "dgIdentity", "excludedMember", "member" }; /* Since reading members of a dynamic group could potentially involve * a significant directory search, we use a timeout. Setting * time out to 10 seconds */ LdapSearchConstraints cons = new LdapSearchConstraints(); cons.TimeLimit = 10000; String ldapHost = args[0]; String loginDN = args[1]; String password = args[2]; String groupDN = args[3]; LdapConnection lc = new LdapConnection(); try { // connect to the server lc.Connect(ldapHost, ldapPort); // bind to the server lc.Bind(ldapVersion, loginDN, password); Console.WriteLine("\n\tReading object :" + groupDN); LdapSearchResults searchResults = lc.Search(groupDN, // object to read searchScope, // scope - read single object null, // search filter attrs, // return only required attributes false, // return attrs and values cons); // time out value // Examine the attributes that were returned and extract the data LdapEntry nextEntry = null; try { nextEntry = searchResults.next(); } catch (LdapException e) { Console.WriteLine("Error: " + e.ToString()); Environment.Exit(1); } LdapAttributeSet attributeSet = nextEntry.getAttributeSet(); IEnumerator allAttributes = attributeSet.GetEnumerator(); while (allAttributes.MoveNext()) { LdapAttribute attribute = (LdapAttribute)allAttributes.Current; String attributeName = attribute.Name; // Save objectclass values if (attributeName.ToUpper().Equals("objectClass".ToUpper())) { objClass = attribute.StringValues; } // Save the memberQueryURL attribute if present else if (attributeName.ToUpper().Equals("memberQueryURL".ToUpper())) { queryURL = attribute.StringValues; } // Save the dgIdentity attribute if present else if (attributeName.ToUpper().Equals("dgIdentity".ToUpper())) { identity = attribute.StringValues; } // Save the excludedMember attribute if present else if (attributeName.ToUpper().Equals("excludedMember".ToUpper())) { excludedMember = attribute.StringValues; } /* Save the member attribute. This may also show up * as uniqueMember */ else if (attributeName.ToUpper().Equals("member".ToUpper()) || attributeName.ToUpper().Equals("uniqueMember".ToUpper())) { member = attribute.StringValues; } } /* Verify that this is a group object (i.e. objectClass contains * the value "group", "groupOfNames", or "groupOfUniqueNames"). * Also determine if this is a dynamic group object * (i.e. objectClass contains the value "dynamicGroup" or * "dynamicGroupAux"). */ while (objClass.MoveNext()) { String objectName = (String)objClass.Current; if (objectName.ToUpper().Equals("group".ToUpper()) || objectName.ToUpper().Equals("groupOfNames".ToUpper()) || objectName.ToUpper().Equals("groupOfUniqueNames".ToUpper())) { isGroup = true; } else if (objectName.ToUpper().Equals("dynamicGroup".ToUpper()) || objectName.ToUpper().Equals("dynamicGroupAux".ToUpper())) { isGroup = isDynamicGroup = true; } } if (!isGroup) { Console.WriteLine("\tThis object is NOT a group object." + "Exiting.\n"); Environment.Exit(0); } /* If this is a dynamic group, display its memberQueryURL, identity * and excluded member list. */ if (isDynamicGroup) { if ((queryURL != null) && (queryURL.MoveNext())) { Console.WriteLine("\tMember Query URL:"); while (queryURL.MoveNext()) { Console.WriteLine("\t\t" + queryURL.Current); } } if ((identity != null) && (identity.MoveNext())) { Console.WriteLine("\tIdentity for search:" + identity.Current); } if ((excludedMember != null) && (excludedMember.MoveNext())) { Console.WriteLine("\tExcluded member list:"); while (excludedMember.MoveNext()) { Console.WriteLine("\t\t" + excludedMember.Current); } } } // Print the goup's member list if (member != null && member.MoveNext()) { Console.WriteLine("\n\tMember list:"); while (member.MoveNext()) { Console.WriteLine("\t\t" + member.Current); } } // disconnect with the server lc.Disconnect(); } catch (LdapException e) { Console.WriteLine("Error: " + e.ToString()); Environment.Exit(1); } catch (Exception e) { Console.WriteLine("Error: " + e.ToString()); } Environment.Exit(0); }
public ApiResultAd?GetUserInfo(string username, string pw) { _logger.Information("START Novell.Directory.Ldap.LdapPasswordChangeProvider.GetUserInfo"); var result = new ApiResultAd(); try { var cleanUsername = CleaningUsername(username); _logger.Information("Zyborg.PerformPasswordChange: cleanUsername="******"{Username}", cleanUsername); _logger.Information("Zyborg.PerformPasswordChange: searchFilter=" + searchFilter); _logger.Warning("LDAP query: {0}", searchFilter); using var ldap = BindToLdap(); var search = ldap.Search( _options.LdapSearchBase, LdapConnection.ScopeSub, searchFilter, new[] { "distinguishedName" }, false, _searchConstraints); // We cannot use search.Count here -- apparently it does not // wait for the results to return before resolving the count // but fortunately hasMore seems to block until final result if (!search.HasMore()) { _logger.Warning("Unable to find username: [{0}]", cleanUsername); //result.Errors = new ApiErrorItem(ApiErrorCode.InvalidCredentials, "Mật khẩu không đúng!"); result.Errors = new ApiErrorItem(_options.HideUserNotFound ? ApiErrorCode.InvalidCredentials : ApiErrorCode.UserNotFound, _options.HideUserNotFound ? "Invalid credentials" : "Username could not be located"); return(result); } if (search.Count > 1) { _logger.Warning("Found multiple with same username: [{0}] - Count {1}", cleanUsername, search.Count); // Hopefully this should not ever happen if AD is preserving SAM Account Name // uniqueness constraint, but just in case, handling this corner case result.Errors = new ApiErrorItem(ApiErrorCode.UserNotFound, "Multiple matching user entries resolved"); return(result); } var userDN = search.Next().Dn; while (search.HasMore()) { LdapEntry nextEntry = null; try { nextEntry = search.Next(); } catch (LdapException e) { _logger.Error("Error: " + e.LdapErrorMessage); //Console.WriteLine("Error: " + e.LdapErrorMessage); // Exception is thrown, go for next entry continue; } _logger.Warning("==>User: "******"\n" + nextEntry.Dn); LdapAttributeSet attributeSet = nextEntry.GetAttributeSet(); System.Collections.IEnumerator ienum = attributeSet.GetEnumerator(); while (ienum.MoveNext()) { LdapAttribute attribute = (LdapAttribute)ienum.Current; string attributeName = attribute.Name; string attributeVal = attribute.StringValue; _logger.Warning(attributeName + " value:" + attributeVal); //Console.WriteLine(attributeName + "value:" + attributeVal); } } //LdapAttributeSet attributeSet = new LdapAttributeSet(); //attributeSet.GetAttribute(""); if (_options.LdapStartTls) { ldap.StopTls(); } ldap.Disconnect(); } catch (LdapException ex) { result.Errors = ParseLdapException(ex); _logger.Warning(ex.Message); return(result); } #pragma warning disable CA1031 // Do not catch general exception types catch (Exception ex) #pragma warning restore CA1031 // Do not catch general exception types { result.Errors = ex is ApiErrorException apiError ? apiError.ToApiErrorItem() : new ApiErrorItem(ApiErrorCode.InvalidCredentials, $"Failed to update password: {ex.Message}"); _logger.Warning(ex.Message); return(result); } // Everything seems to have worked: return(null); }