} // end of Constructor protected override void StartSearchAndPolling() { // perform the search with no attributes returned mQueue = mConnection.Search(mSearchBase, // container to search mScope, // search container's subtree mFilter, // search filter, all objects mAttrs, // don't return attributes mTypesOnly, // return attrs and values or attrs only. null, // use default search queue mSearchConstraints); // use default search constraints int[] ids = mQueue.MessageIDs; if (ids.Length != 1) { throw new LdapException( null, LdapException.LOCAL_ERROR, "Unable to Obtain Message Id" ); } StartEventPolling(mQueue, mConnection, ids[0]); }
private static LdapEntry GetOneUserEntry( LdapConnection conn, LdapSettings ldapSettings, string search) { LdapSearchConstraints constraints = new LdapSearchConstraints(); LdapSearchQueue queue = null; queue = conn.Search( ldapSettings.RootDN, LdapConnection.SCOPE_SUB, ldapSettings.UserDNKey + "=" + search, null, false, (LdapSearchQueue)null, (LdapSearchConstraints)null); LdapEntry entry = null; if (queue != null) { LdapMessage message = queue.getResponse(); if (message != null) { if (message is LdapSearchResult) { entry = ((LdapSearchResult)message).Entry; } } } return(entry); }
/// <summary> /// Get Roles /// </summary> /// <param name="user"></param> /// <returns></returns> private IEnumerable <string> GetRoles(string user) { LdapSearchQueue searchQueue = _connection.Search( _ldapconfig.SearchBase, LdapConnection.SCOPE_SUB, string.Format(_ldapconfig.SearchFilter, user), new string[] { "cn", "memberOf" }, false, null as LdapSearchQueue); LdapMessage message; while ((message = searchQueue.getResponse()) != null) { if (message is LdapSearchResult searchResult) { LdapEntry entry = searchResult.Entry; foreach (string value in HandleEntry(entry)) { yield return(value); } } else { continue; } } IEnumerable <string> HandleEntry(LdapEntry entry) { LdapAttribute attr = entry.getAttribute("memberOf"); if (attr == null) { yield break; } foreach (string value in attr.StringValueArray) { string groupName = GetGroup(value); yield return(groupName); } } string GetGroup(string value) { Match match = Regex.Match(value, "^CN=([^,]*)"); if (!match.Success) { return(null); } return(match.Groups[1].Value); } }
private string IsUserExistsLDAP(string name, string pwd) { // Metemos los valores de configuración para conectarnos al ldap de Everis. int LdapPort = LdapConnection.DEFAULT_PORT; //int searchScope = LdapConnection.SCOPE_ONE; int LdapVersion = LdapConnection.Ldap_V3; //bool attributeOnly=true; String[] attrs = { LdapConnection.NO_ATTRS }; LdapConnection lc = new LdapConnection(); string resultado = ""; // Vamos a meter una restricción de tiempo. LdapSearchConstraints constraints = new LdapSearchConstraints(); constraints.TimeLimit = 10000; // ms try{ // Nos conectamos al servidor. lc.Connect(ldapHost, LdapPort); // Accedemos con las credenciales del usuario para ver si está. lc.Bind(LdapVersion, Configuration["connectionStrings:LDAPDomain"] + name, pwd); // Set values to search string base1 = "OU=Spain,OU=Europe,OU=Everis,DC=usersad,DC=everis,DC=int"; string[] attributes = new string[] { "displayName", "samaccountname" }; string filter = String.Format("(&(objectClass=user)(samaccountname={0}))", name); LdapSearchQueue lsc = lc.Search(base1, LdapConnection.SCOPE_SUB, filter, attributes, false, (LdapSearchQueue)null, (LdapSearchConstraints)null); LdapMessage msg; if ((msg = lsc.getResponse()) != null) { if (msg is LdapSearchResult) { LdapEntry nextEntry = ((LdapSearchResult)msg).Entry; LdapAttributeSet attributeSet = nextEntry.getAttributeSet(); Console.WriteLine("Nombre corto: " + attributeSet.getAttribute("samaccountname").StringValue); Console.WriteLine("Nombre Largo: " + attributeSet.getAttribute("displayName").StringValue); string[] ss = attributeSet.getAttribute("displayName").StringValue.Split(' '); string s2 = ss[0]; if (ss.Length > 1) { s2 += " " + ss[1]; } return(s2); } } lc.Disconnect(); } catch (LdapException e) { Console.WriteLine(e.Message); return(null); } catch (Exception) { Console.WriteLine("error"); return(null); } return(resultado); }
private int checkUser(String loginDN, String password) { // Metemos los valores de configuración para conectarnos al ldap de Everis. int LdapPort = LdapConnection.DEFAULT_PORT; //int searchScope = LdapConnection.SCOPE_ONE; int LdapVersion = LdapConnection.Ldap_V3; //bool attributeOnly=true; String[] attrs = { LdapConnection.NO_ATTRS }; LdapConnection lc = new LdapConnection(); int resultado = 0; // Vamos a meter una restricción de tiempo. LdapSearchConstraints constraints = new LdapSearchConstraints(); constraints.TimeLimit = 10000; // ms try{ // Nos conectamos al servidor. lc.Connect(Constants.ldapHost, LdapPort); // Accedemos con las credenciales del usuario para ver si está. lc.Bind(LdapVersion, loginDN, password); // Set values to search string base1 = "OU=Spain,OU=Europe,OU=Everis,DC=usersad,DC=everis,DC=int"; string[] attributes = new string[] { "displayName", "samaccountname" }; string filter = String.Format("(&(objectClass=user)(samaccountname={0}))", loginDN.Substring(8)); LdapSearchQueue lsc = lc.Search(base1, LdapConnection.SCOPE_SUB, filter, attributes, false, (LdapSearchQueue)null, (LdapSearchConstraints)null); LdapMessage msg; if ((msg = lsc.getResponse()) != null) { if (msg is LdapSearchResult) { LdapEntry nextEntry = ((LdapSearchResult)msg).Entry; LdapAttributeSet attributeSet = nextEntry.getAttributeSet(); Console.WriteLine("Nombre corto: " + attributeSet.getAttribute("samaccountname").StringValue); Console.WriteLine("Nombre Largo: " + attributeSet.getAttribute("displayName").StringValue); } } lc.Disconnect(); } catch (LdapException e) { resultado = e.ResultCode; } catch (Exception) { resultado = -1; } return(resultado); }
public bool IsUserExist(string userLoginId) { var ldapSettings = GetLDAPSettings(); Logger.Debug("Checking " + userLoginId); LdapConnection ldapConn = null; try { ldapConn = new LdapConnection(); ldapConn.Connect(ldapSettings.LdapServer, ldapSettings.LdapServerPort); ldapConn.Bind(ldapSettings.AdminDN, ldapSettings.AdminPassword); if (ldapConn.Bound) { LdapSearchQueue queue = ldapConn.Search(ldapSettings.SearchBase, LdapConnection.SCOPE_SUB, "uid=" + userLoginId, null, false, (LdapSearchQueue)null, (LdapSearchConstraints)null); LdapMessage message; message = queue.getResponse(); if (message == null || !(message is LdapSearchResult)) { return(false); } else { return(true); } } } catch (Exception ex) { Logger.Error("IsUserExist fialed.", ex); return(false); } finally { if (ldapConn != null) { ldapConn.Disconnect(); } } return(false); }
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()); }
/// <summary>Searches the directory /// </summary> /// <param name="searchBase">Where to start the search</param> /// <param name="searchScope">Scope of search</param> /// <param name="searchFilter">Filter to search for</param> /// <param name="searchAttrs">Attributes to search for</param> /// <returns>List of entries matching filter</returns> public LdapEntry[] Search(string searchBase, int searchScope, string searchFilter, string[] searchAttrs) { if (!conn.Connected) { return(null); } try { List <LdapEntry> retVal = new List <LdapEntry> (); RfcFilter rfcFilter = new RfcFilter(searchFilter); LdapSearchConstraints cons = new LdapSearchConstraints(); cons.MaxResults = 0; LdapSearchQueue queue = conn.Search(searchBase, searchScope, rfcFilter.filterToString(), searchAttrs, false, (LdapSearchQueue)null, cons); LdapMessage msg; while ((msg = queue.getResponse()) != null) { if (msg is LdapSearchResult) { LdapEntry entry = ((LdapSearchResult)msg).Entry; retVal.Add(entry); } } return(retVal.ToArray()); } catch (Exception e) { Log.Debug(e); return(null); } }
public static void Main(String[] args) { // Verify correct number of parameters if (args.Length != 4) { Console.WriteLine("Usage: mono AsynchronousSortControl <host name> " + "<login dn> <password> <container>"); Console.WriteLine("Example: mono AsynchronousSortControl Acme.com" + " \"cn=admin,o=Acme\" secret \"ou=Sales,o=Acme\""); Environment.Exit(0); } // Read command line arguments String ldapHost = args[0]; String loginDN = args[1]; String password = args[2]; String searchBase = args[3]; int MY_PORT = 389; int ldapVersion = LdapConnection.Ldap_V3; try { // Create a LdapConnection object LdapConnection lc = new LdapConnection(); // Connect to server lc.Connect(ldapHost, MY_PORT); lc.Bind(ldapVersion, loginDN, password); Console.WriteLine("Login succeeded"); // We will be searching for all objects String MY_FILTER = "(objectClass=*)"; // Results of the search should include givenname and cn String[] attrs = new String[2]; attrs[0] = "givenname"; attrs[1] = "cn"; // The results should be sorted using the cn attribute LdapSortKey[] keys = new LdapSortKey[1]; keys[0] = new LdapSortKey("cn"); // 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 = lc.SearchConstraints; cons.setControls(sort); lc.Constraints = cons; // Perform the search - ASYNCHRONOUS SEARCH USED HERE Console.WriteLine("Calling search request"); LdapSearchQueue queue = lc.Search(searchBase, LdapConnection.SCOPE_SUB, MY_FILTER, attrs, false, (LdapSearchQueue)null, (LdapSearchConstraints)null); LdapMessage message; while ((message = queue.getResponse()) != null) { // OPTION 1: the message is a search result reference if (message is LdapSearchResultReference) { // Not following referrals to keep things simple String[] urls = ((LdapSearchResultReference)message).Referrals; Console.WriteLine("Search result references:"); for (int i = 0; i < urls.Length; i++) { Console.WriteLine(urls[i]); } } // OPTION 2:the message is a search result else if (message is LdapSearchResult) { // Get the object name LdapEntry entry = ((LdapSearchResult)message).Entry; Console.WriteLine("\n" + entry.DN); Console.WriteLine("\tAttributes: "); // Get the attributes and print them out 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); // Print all values of the attribute IEnumerator allValues = attribute.StringValues; if (allValues != null) { while (allValues.MoveNext()) { String Value = (String)allValues.Current; Console.WriteLine("\t\t\t" + Value); } } } } // OPTION 3: The message is a search response else { LdapResponse response = (LdapResponse)message; int status = response.ResultCode; // the return code is Ldap success if (status == LdapException.SUCCESS) { Console.WriteLine("Asynchronous search succeeded."); } // the return code is referral exception else if (status == LdapException.REFERRAL) { String[] urls = ((LdapResponse)message).Referrals; Console.WriteLine("Referrals:"); for (int i = 0; i < urls.Length; i++) { Console.WriteLine(urls[i]); } } else { Console.WriteLine("Asynchronous search failed."); Console.WriteLine(response.ErrorMessage); } // Server should send back a control irrespective of the // status of the search request LdapControl[] controls = response.Controls; if (controls != null) { // Theoritically we could have multiple controls returned for (int i = 0; i < controls.Length; i++) { // We are looking for the LdapSortResponse Control class - the control // sent back in response to LdapSortControl if (controls[i] is LdapSortResponse) { Console.WriteLine("Received Ldap Sort Control fromserver"); // We must have an error code and maybe a string identifying // erring attribute in the response control. Get these. String bad = ((LdapSortResponse)controls[i]).FailedAttribute; int result = ((LdapSortResponse)controls[i]).ResultCode; // Print out error ccode (0 if no error) and any returned // attribute Console.WriteLine("Error code: " + result); if (bad != null) { Console.WriteLine("Offending " + "attribute: " + bad); } else { Console.WriteLine("No offending " + "attribute " + "returned"); } } } } } } // All done - disconnect if (lc.Connected == true) { lc.Disconnect(); } } catch (LdapException e) { Console.WriteLine(e.ToString()); } catch (Exception e) { Console.WriteLine("Error: " + e.ToString()); } }
/// <summary> Merges two message queues. It appends the current and /// future contents from another queue to this one. /// /// After the operation, queue2.getMessageIDs() /// returns an empty array, and its outstanding responses /// have been removed and appended to this queue. /// /// </summary> /// <param name="queue2"> The queue that is merged from. Following /// the merge, this queue object will no /// longer receive any data, and calls made /// to its methods will fail with a RuntimeException. /// The queue can be reactivated by using it in an /// Ldap request, after which it will receive responses /// for that request.. /// </param> public virtual void merge(LdapMessageQueue queue2) { LdapSearchQueue q = (LdapSearchQueue)queue2; agent.merge(q.MessageAgent); }
public List <LDAPUser> GetUserInfoList(List <string> LoginIdList) { var ldapSettings = GetLDAPSettings(); bool flag = false; string uidAttribute = "uid"; List <LDAPUser> userList = new List <LDAPUser>(); LdapConnection ldapConn = null; try { ldapConn = new LdapConnection(); ldapConn.Connect(ldapSettings.LdapServer, ldapSettings.LdapServerPort); ldapConn.Bind(ldapSettings.AdminDN, ldapSettings.AdminPassword); for (int i = 0; i < LoginIdList.Count; i++) { LoginIdList[i].ToUpper(); } //user.LoginId = userLoginId; //user.Name = userLoginId; StringBuilder QueryStr = new StringBuilder(); if (LoginIdList.Count == 1) { QueryStr.Append("uid=" + LoginIdList[0]); } else { QueryStr.Append("(|"); for (int i = 0; i < LoginIdList.Count; i++) { QueryStr.Append("(uid=" + LoginIdList[i] + ")"); } QueryStr.Append(")"); } if (ldapConn.Bound) { LdapSearchQueue queue = ldapConn.Search(ldapSettings.SearchBase, LdapConnection.SCOPE_SUB, QueryStr.ToString(), null, false, (LdapSearchQueue)null, (LdapSearchConstraints)null); LdapMessage message; while ((message = queue.getResponse()) != null) { LDAPUser user = new LDAPUser(); if (message is LdapSearchResult) { flag = false; LdapEntry entry = ((LdapSearchResult)message).Entry; 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; if (!Base64.isLDIFSafe(attributeVal)) { byte[] tbyte = SupportClass.ToByteArray(attributeVal); attributeVal = Base64.encode(SupportClass.ToSByteArray(tbyte)); } Logger.Debug("Attributes:" + attributeName + "value:" + attributeVal); if (uidAttribute.Equals(attributeName.Trim())) { user.LoginId = attributeVal; } if (ldapSettings.MailAttribute.Equals(attributeName.Trim())) { user.Mail = attributeVal; flag = true; } if (ldapSettings.NameAttribute.Equals(attributeName.Trim())) { user.Name = attributeVal; flag = true; } } if (flag == true) { if (!string.IsNullOrEmpty(user.LoginId) && !string.IsNullOrEmpty(user.Name) && !string.IsNullOrEmpty(user.Mail)) { userList.Add(user); } } } //end if } //end while } } catch (Exception ex) { Logger.Error("GetUserInfoList failed.", ex); userList.Clear(); //throw ex; } finally { if (ldapConn != null) { ldapConn.Disconnect(); } } return(userList); }
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)); }
protected override void StartSearchAndPolling() { // perform the search with no attributes returned mQueue = mConnection.Search(mSearchBase, // container to search mScope, // search container's subtree mFilter, // search filter, all objects mAttrs, // don't return attributes mTypesOnly, // return attrs and values or attrs only. null, // use default search queue mSearchConstraints); // use default search constraints int[] ids = mQueue.MessageIDs; if (ids.Length != 1) { throw new LdapException( null, LdapException.LOCAL_ERROR, "Unable to Obtain Message Id" ); } StartEventPolling(mQueue, mConnection, ids[0]); }
private int ldap_check(int serveruse) { try { // if (serveruse == 1) // Statusbar_Message("Retrieving username input"); // if (Username.Text.Equals("") == true) // { // Error_Handler("Input Error: Username field has been left blank."); // Statusbar_Message("Operation failed"); // return 0; // } //if (serveruse == 1) // Statusbar_Message("Retrieving password input"); // string userPasswd = Password.Text; // // if (Password.Text.Equals("") == true) // { // Error_Handler("Input Error: Password field has been left blank."); // Statusbar_Message("Operation failed"); // return 0; // } // // if (Context.SelectedIndex < 0) // { // Error_Handler("Invalid Context selected from the list."); // Statusbar_Message("Operation failed"); // return 0; // } // // string tdn = ""; // string[] tempdn = Context.Items[Context.SelectedIndex].ToString().Split('.'); // System.Collections.IEnumerator runner = tempdn.GetEnumerator(); // while(runner.MoveNext()) // { // if (runner.Current.Equals("uct") == false) // tdn = tdn + "OU="+ runner.Current + ","; // else // tdn = tdn + "O="+ runner.Current + ","; // } // tdn = tdn.Remove(tdn.Length-1,1); // string userDN = "CN=" + Username.Text.ToUpper() + "," + tdn; // if (serveruse == 1) // Statusbar_Message("Setting DN string as " + userDN); // // string ldapHost; int ldapPort; // int ldapVersion = LdapConnection.Ldap_V3; if (serveruse == 1) { ldapHost = "rep1.uct.ac.za"; ldapPort = LdapConnection.DEFAULT_PORT; } else { ldapHost = "rep2.uct.ac.za"; ldapPort = LdapConnection.DEFAULT_PORT; } Statusbar_Message("Setting LDAP server as " + ldapHost + ":" + ldapPort); // Statusbar_Message("Attempting to bind " + Username.Text + " to " + ldapHost + ":" + ldapPort); // Creating an LdapConnection instance LdapConnection ldapConn = new LdapConnection(); try { //Connect function will create a socket //ldapConn.SecureSocketLayer = true; ldapConn.Connect(ldapHost, ldapPort); //Bind function will Bind the user //ldapConn.startTLS(); // ldapConn.Bind(ldapVersion,userDN,userPasswd); //ldapConn.stopTLS(); } catch (System.Exception except) { Error_Handler(except); if (serveruse == 1) { Statusbar_Message("Contacting Secondary LDAP server"); ldap_check(2); return(0); } else { Statusbar_Message("Operation failed"); return(0); } } //LdapAttribute attr = new LdapAttribute("userPassword", userPasswd); //bool correct = ldapConn.Compare(userDN, attr); //label1_Message("Password Verify: " + correct); string stdn = ""; string[] stempdn = SearchContext.Text.Split('.'); System.Collections.IEnumerator srunner = stempdn.GetEnumerator(); while (srunner.MoveNext()) { if (srunner.Current.Equals("uct") == false) { stdn = stdn + "OU=" + srunner.Current + ","; } else { stdn = stdn + "O=" + srunner.Current + ","; } } stdn = stdn.Remove(stdn.Length - 1, 1); Statusbar_Message("Search DN string set as " + stdn); if (stdn.Equals("") == true) { Error_Handler("Input Error: Search DN field has been left blank."); Statusbar_Message("Operation failed"); return(0); } Statusbar_Message("Search Parameter string set as " + SearchParameter.Text); if (SearchParameter.Text.Equals("") == true) { Error_Handler("Input Error: Search Parameter field has been left blank."); Statusbar_Message("Operation failed"); return(0); } Statusbar_Message("Retrieving Object Details"); resultsreturned.Text = "0"; resultsreturned.Text = resultsreturned.Text + " RESULTS RETURNED"; resultsreturned.Refresh(); bool LoopsOn; LoopsOn = false; if (SearchParameter.Text.ToUpper() == "CN=*") { LoopsOn = true; } else { LoopsOn = false; } string[] searchparams; if (LoopsOn == false) { searchparams = new string[1] { SearchParameter.Text }; } else { searchparams = new string[702]; string[] outerloop = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" }; string[] innerloop = { "-", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" }; //searchparams = new string[676]; //string[] outerloop = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"}; //string[] innerloop = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"}; int current = 0; foreach (string outer in outerloop) { string c = outer; foreach (string inner in innerloop) { c = "CN=" + outer + inner + "*"; searchparams[current] = c; //label1_Message(current + ": " + c); current = current + 1; } } } //MessageBox.Show(searchparams.Length.ToString()); foreach (string arrsearchterm in searchparams) { // Searches in the Marketing container and return all child entries just below this //container i.e Single level search LdapSearchQueue queue = ldapConn.Search(stdn, LdapConnection.SCOPE_SUB, //"objectClass=*", //"CN=" + Username.Text.ToUpper(), arrsearchterm, null, false, (LdapSearchQueue)null, (LdapSearchConstraints)null); LdapMessage message; while ((message = queue.getResponse()) != null) { if (message is LdapSearchResult) { double doh = (Double.Parse(resultsreturned.Text.Replace(" RESULTS RETURNED", "")) + 1); resultsreturned.Text = doh.ToString(); resultsreturned.Text = resultsreturned.Text + " RESULTS RETURNED"; resultsreturned.Refresh(); LdapEntry entry = ((LdapSearchResult)message).Entry; //label1_Message("------------------------------------------------\n ENTRY:\n------------------------------------------------"); //// label1_Message(" " + entry.DN ); string writemessage = ""; writemessage = entry.DN.ToString().ToLower().Replace("cn=", ".").Replace("o=", ".").Replace("ou=", ".").Replace(",", ""); ActivityLogger(writemessage); } } } Statusbar_Message("Disconnecting from LDAP server"); ldapConn.Disconnect(); Statusbar_Message("Operation successfully completed"); sysTray.ShowBalloonTip("Operation successfully completed. " + resultsreturned.Text.ToLower() + ".", NotifyIconBalloonIconFlags.NIIF_INFO, "Novell Sub Object List Creator"); return(1); } catch (System.Exception except) { Error_Handler(except); Statusbar_Message("Operation failed"); } return(0); }
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)); }
//match the key to first name or last name public List <LDAPUser> GetUserListByName(string name, int rowCount) { var ldapSettings = GetLDAPSettings(); bool flag = false; string uidAttribute = "uid"; List <LDAPUser> userList = new List <LDAPUser>(); LdapConnection ldapConn = null; try { ldapConn = new LdapConnection(); ldapConn.Connect(ldapSettings.LdapServer, ldapSettings.LdapServerPort); ldapConn.Bind(ldapSettings.AdminDN, ldapSettings.AdminPassword); var queryStr = string.Format("(|(EdsSearchFirstNm={0})(EdsSearchLastNm={1}))", name, name); if (ldapConn.Bound) { //specify result's count var cons = ldapConn.SearchConstraints; cons.MaxResults = rowCount; //--- LdapSearchQueue queue = ldapConn.Search(ldapSettings.SearchBase, LdapConnection.SCOPE_SUB, queryStr, null, false, (LdapSearchQueue)null, cons); LdapMessage message; while ((message = queue.getResponse()) != null) { LDAPUser user = new LDAPUser(); if (message is LdapSearchResult) { flag = false; LdapEntry entry = ((LdapSearchResult)message).Entry; 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; if (!Base64.isLDIFSafe(attributeVal)) { byte[] tbyte = SupportClass.ToByteArray(attributeVal); attributeVal = Base64.encode(SupportClass.ToSByteArray(tbyte)); } Logger.Debug("Attributes:" + attributeName + "value:" + attributeVal); if (uidAttribute.Equals(attributeName.Trim())) { user.LoginId = attributeVal; } if (ldapSettings.MailAttribute.Equals(attributeName.Trim())) { user.Mail = attributeVal; flag = true; } if (ldapSettings.NameAttribute.Equals(attributeName.Trim())) { user.Name = attributeVal; flag = true; } } if (flag == true) { if (!string.IsNullOrEmpty(user.LoginId) && !string.IsNullOrEmpty(user.Name) && !string.IsNullOrEmpty(user.Mail)) { userList.Add(user); } } } //end if } //end while } } catch (Exception ex) { Logger.Error("GetUserListByName failed.", ex); userList.Clear(); //throw ex; } finally { if (ldapConn != null) { ldapConn.Disconnect(); } } return(userList); }
/// <summary> /// Process search container for each member /// </summary> /// <param name="conn">ldap connection</param> /// <param name="searchContainer">container to be processed</param> private void ProcessSearchContainer(LdapConnection conn, String searchContainer) { String searchFilter = "(|(objectclass=user)(objectclass=groupOfNames)(objectclass=dynamicGroup)(objectclass=group))"; //String searchFilter = "(objectclass=user)"; string[] searchAttributes = { "modifytimestamp", ldapSettings.NamingAttribute, "cn", "sn", "objectGUID", "givenName", "ou", "objectclass", "member", "groupMembership", "iFolderHomeServer" }; log.Debug("ProcessSearchContainer(" + searchContainer + ")"); int count = 0; LdapSearchConstraints searchConstraints = new LdapSearchConstraints(); searchConstraints.MaxResults = 0; LdapSearchQueue queue = conn.Search( searchContainer, LdapConnection.SCOPE_SUB, searchFilter, searchAttributes, false, (LdapSearchQueue)null, searchConstraints); LdapMessage ldapMessage; while ((ldapMessage = queue.getResponse()) != null) { // Check if the sync engine wants us to abort if (this.abort == true) { return; } if (ldapMessage is LdapSearchResult) { LdapEntry cEntry = ((LdapSearchResult)ldapMessage).Entry; if (cEntry == null) { continue; } try { ProcessUserEntry(conn, cEntry, "", ""); count++; } catch (SimiasShutdownException s) { log.Error(s.Message); throw s; } catch (LdapException e) { log.Error(" Failed processing: " + cEntry.DN); log.Error(e.LdapErrorMessage); log.Error(e.StackTrace); } catch (Exception e) { log.Error(" Failed processing: " + cEntry.DN); log.Error(e.Message); log.Error(e.StackTrace); } } } log.Debug("Processed " + count.ToString() + " entries"); }
public LDAPUser GetUserInfo(string userLoginId, out bool found) { var ldapSettings = GetLDAPSettings(); found = false; LDAPUser user = new LDAPUser(); string userId = userLoginId.ToUpper(); user.LoginId = userLoginId; user.Name = userLoginId; //string adminDN = "uid=AdminIMS,ou=adminaccount,o=lilly,dc=com"; //logger.Debug("adminDN:" + adminDN); //string adminPassword = "******"; //string searchBase = "o=lilly,dc=com"; //logger.Debug("searchBase:" + searchBase); //string mail = null; LdapConnection ldapConn = null; //logger.Debug("get mail for:" + userId); try { ldapConn = new LdapConnection(); ldapConn.Connect(ldapSettings.LdapServer, ldapSettings.LdapServerPort); ldapConn.Bind(ldapSettings.AdminDN, ldapSettings.AdminPassword); if (ldapConn.Bound) { //logger.Debug("Attributes:" + attributeName + "value:" + attributeVal); LdapSearchQueue queue = ldapConn.Search(ldapSettings.SearchBase, LdapConnection.SCOPE_SUB, "uid=" + userId, null, false, (LdapSearchQueue)null, (LdapSearchConstraints)null); LdapMessage message; while ((message = queue.getResponse()) != null) { if (message is LdapSearchResult) { LdapEntry entry = ((LdapSearchResult)message).Entry; 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; if (!Base64.isLDIFSafe(attributeVal)) { byte[] tbyte = SupportClass.ToByteArray(attributeVal); attributeVal = Base64.encode(SupportClass.ToSByteArray(tbyte)); } Logger.Debug("Attributes:" + attributeName + "value:" + attributeVal); if (ldapSettings.MailAttribute.Equals(attributeName.Trim())) { user.Mail = attributeVal; found = true; } if (ldapSettings.NameAttribute.Equals(attributeName.Trim())) { user.Name = attributeVal; found = true; } if (ldapSettings.CountryAttribute.Equals(attributeName.Trim())) { user.Country = attributeVal; found = true; } } } //end if } //end whil } // end if } catch (Exception ex) { Logger.Error("GetUserInfo failed.", ex); user = null; //throw ex; } finally { if (ldapConn != null) { ldapConn.Disconnect(); } } return(user); }
public DataTable GetUserList(string userID) { LdapConnection ldapConn = null; DataTable dt = null; try { ldapConn = new LdapConnection(); ldapConn.Connect("dsazone1.d51.lilly.com", 389); ldapConn.Bind("uid=AdminIMS,ou=adminaccount,o=lilly,dc=com", "r@nd0m!se"); if (ldapConn.Bound) { dt = new DataTable(); dt.Columns.Add(new DataColumn("EdsSearchFirstNm", typeof(String))); dt.Columns.Add(new DataColumn("EdsSearchLastNm", typeof(String))); dt.Columns.Add(new DataColumn("uid", typeof(String))); dt.Columns.Add(new DataColumn("EdsWorkCntryCd", typeof(String))); dt.Columns.Add(new DataColumn("employeeType", typeof(String))); dt.Columns.Add(new DataColumn("mail", typeof(String))); string tmp = string.Empty; LdapSearchQueue queue2 = ldapConn.Search("o=lilly,dc=com", LdapConnection.SCOPE_SUB, "EdsSearchFirstNm=*" + userID + "*", null, false, (LdapSearchQueue)null, (LdapSearchConstraints)null); LdapMessage msg22; while ((msg22 = queue2.getResponse()) != null) { if (msg22 is LdapSearchResult) { LdapEntry entry = ((LdapSearchResult)msg22).Entry; LdapAttributeSet attributeSet = entry.getAttributeSet(); System.Collections.IEnumerator ienum = attributeSet.GetEnumerator(); string attributeName = string.Empty; string attributeVal = string.Empty; DataRow dr = dt.NewRow(); while (ienum.MoveNext()) { LdapAttribute attribute = (LdapAttribute)ienum.Current; attributeName = attribute.Name; attributeVal = attribute.StringValue; if (attributeName.Equals("EdsSearchFirstNm") == true) { tmp = attributeVal; dr[0] = tmp; } if (attributeName.Equals("EdsSearchLastNm") == true) { tmp = attributeVal; dr[1] = tmp; } if (attributeName.Equals("uid") == true) { tmp = attributeVal; dr[2] = tmp; } if ((attributeName.Equals("EdsWorkCntryCd") == true) && (attributeVal.Equals("CN") == true)) { tmp = attributeVal; dr[3] = tmp; } if (attributeName.Equals("employeeType") == true) { tmp = attributeVal; dr[4] = tmp; } if (attributeName.Equals("mail") == true) { tmp = attributeVal; dr[5] = tmp; } } dt.Rows.Add(dr); } } } return(dt); } catch (Exception ex) { Logger.Error("GetUserList failed.", ex); return(dt); } finally { if (ldapConn != null) { ldapConn.Disconnect(); } } }
private int ldap_check(int serveruse) { try { if (serveruse == 1) { Statusbar_Message("Retrieving username input"); } if (Username.Text.Equals("") == true) { Error_Handler("Input Error: Username field has been left blank."); Statusbar_Message("Operation failed"); return(0); } if (serveruse == 1) { Statusbar_Message("Retrieving password input"); } string userPasswd = Password.Text; if (Password.Text.Equals("") == true) { Error_Handler("Input Error: Password field has been left blank."); Statusbar_Message("Operation failed"); return(0); } if (Context.SelectedIndex < 0) { Error_Handler("Invalid Context selected from the list."); Statusbar_Message("Operation failed"); return(0); } string tdn = ""; string[] tempdn = Context.Items[Context.SelectedIndex].ToString().Split('.'); System.Collections.IEnumerator runner = tempdn.GetEnumerator(); while (runner.MoveNext()) { if (runner.Current.Equals("uct") == false) { tdn = tdn + "OU=" + runner.Current + ","; } else { tdn = tdn + "O=" + runner.Current + ","; } } tdn = tdn.Remove(tdn.Length - 1, 1); string userDN = "CN=" + Username.Text.ToUpper() + "," + tdn; if (serveruse == 1) { Statusbar_Message("Setting DN string as " + userDN); } string ldapHost; int ldapPort; int ldapVersion = LdapConnection.Ldap_V3; if (serveruse == 1) { ldapHost = "rep1.uct.ac.za"; ldapPort = LdapConnection.DEFAULT_PORT; } else { ldapHost = "rep2.uct.ac.za"; ldapPort = LdapConnection.DEFAULT_PORT; } Statusbar_Message("Setting LDAP server as " + ldapHost + ":" + ldapPort); Statusbar_Message("Attempting to bind " + Username.Text + " to " + ldapHost + ":" + ldapPort); // Creating an LdapConnection instance LdapConnection ldapConn = new LdapConnection(); try { //Connect function will create a socket //ldapConn.SecureSocketLayer = true; ldapConn.Connect(ldapHost, ldapPort); //Bind function will Bind the user //ldapConn.startTLS(); ldapConn.Bind(ldapVersion, userDN, userPasswd); //ldapConn.stopTLS(); } catch (System.Exception except) { Error_Handler(except); if (serveruse == 1) { Statusbar_Message("Contacting Secondary LDAP server"); ldap_check(2); return(0); } else { Statusbar_Message("Operation failed"); return(0); } } //LdapAttribute attr = new LdapAttribute("userPassword", userPasswd); //bool correct = ldapConn.Compare(userDN, attr); //label1_Message("Password Verify: " + correct); Statusbar_Message("Retrieving User Account Attributes"); // Searches in the Marketing container and return all child entries just below this //container i.e Single level search LdapSearchQueue queue = ldapConn.Search(tdn, LdapConnection.SCOPE_SUB, //"objectClass=*" "CN=" + Username.Text.ToUpper(), null, false, (LdapSearchQueue)null, (LdapSearchConstraints)null); LdapMessage message; while ((message = queue.getResponse()) != null) { if (message is LdapSearchResult) { LdapEntry entry = ((LdapSearchResult)message).Entry; label1_Message("------------------------------------------------\n ENTRY:\n------------------------------------------------"); label1_Message(" " + entry.DN); label1_Message("------------------------------------------------\n ATTRIBUTES:\n------------------------------------------------"); LdapAttributeSet attributeSet = entry.getAttributeSet(); System.Collections.IEnumerator ienum = attributeSet.GetEnumerator(); while (ienum.MoveNext()) { LdapAttribute attribute = (LdapAttribute)ienum.Current; string attributeName = attribute.Name; //if (attributeName.Equals("groupMembership") == true) { System.Collections.IEnumerator ienum2 = attribute.StringValues; while (ienum2.MoveNext()) { //string gr =(string)ienum.Current; //label1.Text = label1.Text + " \n " + attributeName + " value:" + gr; label1_Message(" Attribute: " + attributeName + "\n Value: " + ienum2.Current.ToString() + ""); } } } } } Statusbar_Message("Disconnecting from LDAP server"); ldapConn.Disconnect(); Statusbar_Message("Operation successfully completed"); return(1); } catch (System.Exception except) { Error_Handler(except); Statusbar_Message("Operation failed"); } return(0); }
/// <summary> Check the queue for a response. If a response has been received, /// print the response information. /// </summary> static private bool checkForAChange(LdapSearchQueue queue) { LdapMessage message; bool result = true; try { //check if a response has been received so we don't block //when calling getResponse() if (queue.isResponseReceived()) { message = queue.getResponse(); if (message != null) { // is the response a search result reference? if (message is LdapSearchResultReference) { String[] urls = ((LdapSearchResultReference)message).Referrals; Console.Out.WriteLine("\nSearch result references:"); for (int i = 0; i < urls.Length; i++) { Console.Out.WriteLine(urls[i]); } } // is the response a search result? else if (message is LdapSearchResult) { LdapControl[] controls = message.Controls; for (int i = 0; i < controls.Length; i++) { if (controls[i] is LdapEntryChangeControl) { LdapEntryChangeControl ecCtrl = (LdapEntryChangeControl)controls[i]; int changeType = ecCtrl.ChangeType; Console.Out.WriteLine("\n\nchange type: " + getChangeTypeString(changeType)); if (changeType == LdapPersistSearchControl.MODDN) { Console.Out.WriteLine("Prev. DN: " + ecCtrl.PreviousDN); } if (ecCtrl.HasChangeNumber) { Console.Out.WriteLine("Change Number: " + ecCtrl.ChangeNumber); } LdapEntry entry = ((LdapSearchResult)message).Entry; Console.Out.WriteLine("entry: " + entry.DN); } } } // the message is a search response else { LdapResponse response = (LdapResponse)message; int resultCode = response.ResultCode; if (resultCode == LdapException.SUCCESS) { Console.Out.WriteLine("\nUnexpected success response."); result = false; } else if (resultCode == LdapException.REFERRAL) { String[] urls = ((LdapResponse)message).Referrals; Console.Out.WriteLine("\n\nReferrals:"); for (int i = 0; i < urls.Length; i++) { Console.Out.WriteLine(urls[i]); } } else { Console.Out.WriteLine("Persistent search failed."); throw new LdapException(response.ErrorMessage, resultCode, response.MatchedDN); } } } } } catch (LdapException e) { Console.Out.WriteLine("Error: " + e.ToString()); result = false; } return(result); }
static void Main(string[] args) { if (args.Length != 5) { Console.WriteLine("Usage: mono SearchPersist <host name> <ldap port> <login dn>" + " <password> <search base>"); Console.WriteLine("Example: mono SearchPersist Acme.com 389" + " \"cn=admin,o=Acme\"" + " secret \"ou=sales,o=Acme\""); return; } int ldapVersion = LdapConnection.Ldap_V3; String ldapHost = args[0]; int ldapPort = Convert.ToInt32(args[1]);; String loginDN = args[2]; String password = args[3]; String searchBase = args[4]; LdapSearchQueue queue = null; LdapSearchConstraints constraints; LdapPersistSearchControl psCtrl; LdapConnection lc = new LdapConnection(); constraints = new LdapSearchConstraints(); try { // connect to the server lc.Connect(ldapHost, ldapPort); // authenticate to the server lc.Bind(ldapVersion, loginDN, password); //Create the persistent search control psCtrl = new LdapPersistSearchControl( LdapPersistSearchControl.ANY, // any change true, //only get changes true, //return entry change controls true); //control is critcal // add the persistent search control to the search constraints constraints.setControls(psCtrl); // perform the search with no attributes returned String[] noAttrs = { LdapConnection.NO_ATTRS }; queue = lc.Search( searchBase, // container to search LdapConnection.SCOPE_SUB, // search container's subtree "(objectClass=*)", // search filter, all objects noAttrs, // don't return attributes false, // return attrs and values, ignored null, // use default search queue constraints); // use default search constraints } catch (LdapException e) { Console.WriteLine("Error: " + e.ToString()); try { lc.Disconnect(); } catch (LdapException e2) { } Environment.Exit(1); } catch (Exception e) { Console.WriteLine("Error: " + e.Message); return; } Console.WriteLine("Monitoring the events for {0} minutes..", TIME_OUT_IN_MINUTES); Console.WriteLine(); //Set the timeout value timeOut = DateTime.Now.AddMinutes(TIME_OUT_IN_MINUTES); try { //Monitor till the timeout happens while (DateTime.Now.CompareTo(timeOut) < 0) { if (!checkForAChange(queue)) { break; } System.Threading.Thread.Sleep(10); } } catch (System.IO.IOException e) { System.Console.Out.WriteLine(e.Message); } catch (System.Threading.ThreadInterruptedException e) { } //Disconnect from the server before exiting try { lc.Abandon(queue); //abandon the search lc.Disconnect(); } catch (LdapException e) { Console.Out.WriteLine(); Console.Out.WriteLine("Error: " + e.ToString()); } Environment.Exit(0); }