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> /// process this user and add all attributes /// </summary> /// <param name="entry">user entry</param> private void ProcessUserEntry(LdapEntry entry) { log.Debug("ProcessUserEntry(" + entry.DN + ")"); string commonName = String.Empty; string firstName = String.Empty; string lastName = String.Empty; string fullName = String.Empty; string distinguishedName = String.Empty; string ldapGuid = null; 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; } 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( null, commonName, firstName, lastName, fullName, distinguishedName, propertyList); } else { state.ProcessMember( null, commonName, firstName, lastName, fullName, distinguishedName, null); } } }
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 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); } }
/// <summary> /// The SimiasAdmin is processed differently than normal simias users because /// the account is aleady created in the Simias store before LdapSync runs /// so the GUID has already been created. The SimiasAdmin must always exist in the /// store and the DN entry in the store must be correct with the Distinguished /// Name in the directory. LdapSync counts on the AdminDN entry in Simias.config /// to be updated if the admin is moved in the directory. /// </summary> /// <param name="conn">ldap connection</param> private void ProcessSimiasAdmin(LdapConnection conn) { // Since the first version of the iFolder 3.0 only // exposes a username, firstname, lastname and full // name, we'll limit the scope of the search string[] searchAttributes = { "modifytimestamp", ldapSettings.NamingAttribute, "cn", "sn", "uid", "givenName" }; char[] dnDelimiters = { ',', '=' }; LdapEntry entry = null; LdapAttribute timeStampAttr = null; Member cMember = null; Property dn = null; string ldapGuid = null; log.Debug("ProcessSimiasAdmin( " + ldapSettings.AdminDN + ")"); string namingContext = ""; entry = conn.Read("", new string[] { "namingContexts" }); if (entry != null) { namingContext = entry.getAttribute("namingContexts").StringValue; } if (domain == null) { store = Store.GetStore(); domain = store.GetDomain(store.DefaultDomain); if (domain == null) { throw new SimiasException("Enterprise domain does not exist!"); } } // If the DN property has never been set on the SimiasAdmin, // set it now cMember = domain.Owner; dn = cMember.Properties.GetSingleProperty("DN"); if (dn == null || dn.Value.ToString() == "") { if (ldapSettings.AdminDN != null && ldapSettings.AdminDN != "") { dn = new Property("DN", ldapSettings.AdminDN); cMember.Properties.ModifyProperty(dn); } } // Check if the Simias Admin has changed in configuration if (ldapSettings.AdminDN != null && ldapSettings.AdminDN != "" && dn.Value.ToString() != ldapSettings.AdminDN) { ChangeSimiasAdmin(conn); cMember = domain.Owner; } // The Simias admin is tracked in the directory by the directory // guid. Make sure the guid is stored in the node Property lguidProp = cMember.Properties.GetSingleProperty("LdapGuid"); if (lguidProp == null) { // This must be the first time thru so let's get the directory // entry based on the configured DN try { entry = conn.Read(ldapSettings.AdminDN, searchAttributes); } catch (LdapException lEx) { log.Error("The Simias Administrator does not exist in the Ldap directory as configured in Simias.config!"); log.Error(lEx.Message); } catch (Exception e1) { log.Error("The Simias Administrator does not exist in the Ldap directory as configured in Simias.config!"); log.Error(e1.Message); } if (entry != null) { ldapGuid = GetLdapGuid(entry); lguidProp = new Property("LdapGuid", ldapGuid); lguidProp.LocalProperty = true; cMember.Properties.ModifyProperty(lguidProp); } } else { ldapGuid = lguidProp.Value.ToString(); } if (ldapGuid != null) { try { entry = null; // Now go find the SimiasAdmin in the Ldap directory string guidFilter = BuildGuidFilter(ldapGuid); LdapSearchResults results = conn.Search( namingContext, LdapConnection.SCOPE_SUB, "(&(objectclass=inetOrgPerson)" + guidFilter + ")", searchAttributes, false); if (results.hasMore() == true) { entry = results.next(); } } catch (LdapException e) { log.Error(e.LdapErrorMessage); log.Error(e.StackTrace); } catch (Exception e) { log.Error(e.Message); log.Error(e.StackTrace); } if (entry != null) { // // check if the ldap object's time stamp has changed // try { timeStampAttr = entry.getAttribute("modifytimestamp"); Property pStamp = cMember.Properties.GetSingleProperty("LdapTimeStamp"); if ((pStamp == null) || (pStamp != null && (string)pStamp.Value != timeStampAttr.StringValue)) { // The time stamp changed let's look at first and // last name try { bool changed = false; // If we're tracking by ldap see if the naming attribute // has changed LdapAttribute namingAttr = entry.getAttribute(ldapSettings.NamingAttribute); if (namingAttr != null && namingAttr.StringValue.Length != 0) { if (namingAttr.StringValue != cMember.Name) { cMember.Name = namingAttr.StringValue; } } LdapAttribute givenAttr = entry.getAttribute("givenName"); if (givenAttr != null && givenAttr.StringValue.Length != 0) { if (givenAttr.StringValue != cMember.Given) { changed = true; cMember.Given = givenAttr.StringValue; } } LdapAttribute sirAttr = entry.getAttribute("sn"); if (sirAttr != null && sirAttr.StringValue.Length != 0) { if (sirAttr.StringValue != cMember.Family) { cMember.Family = sirAttr.StringValue; changed = true; } } // If the entry has changed and we have a valid // family and given if (changed == true && cMember.Given != null && cMember.Given != "" && cMember.Family != null && cMember.Family != "") { cMember.FN = cMember.Given + " " + cMember.Family; } // Did the distinguished name change? Property dnProp = cMember.Properties.GetSingleProperty("DN"); if (dnProp != null && (dnProp.ToString() != entry.DN)) { dnProp.Value = entry.DN; cMember.Properties.ModifyProperty("DN", dnProp); } } catch {} pStamp = new Property("LdapTimeStamp", timeStampAttr.StringValue); pStamp.LocalProperty = true; cMember.Properties.ModifyProperty(pStamp); } } catch {} } else { log.Error("The Simias administrator could not be verified in the directory!"); log.Error("Please update Simias.config with a valid Ldap user"); } } else { log.Error("The Simias administrator could not be verified in the directory!"); log.Error("Please update Simias.config with a valid Ldap user"); } // Now matter what always update the sync guid so // the SimiasAdmin won't be deleted from Simias cMember.Properties.ModifyProperty(state.SyncGuid); domain.Commit(cMember); }
public static bool IsOrganizationalUnit(this LdapEntry entry) { return(entry.ObjectClass().Contains("organizationalunit")); }
public EditAdUserViewDialog(Connection connection, LdapEntry le) : base(connection, null) { currentEntry = le; Init(); string displayName = conn.Data.GetAttributeValueFromEntry(currentEntry, "displayName"); gnNameLabel.Text = displayName; gnFirstNameEntry.Text = conn.Data.GetAttributeValueFromEntry(currentEntry, "givenName"); gnInitialsEntry.Text = conn.Data.GetAttributeValueFromEntry(currentEntry, "initials"); gnLastNameEntry.Text = conn.Data.GetAttributeValueFromEntry(currentEntry, "sn"); gnDisplayName.Text = displayName; gnDescriptionEntry.Text = conn.Data.GetAttributeValueFromEntry(currentEntry, "description"); gnOfficeEntry.Text = conn.Data.GetAttributeValueFromEntry(currentEntry, "physicalDeliveryOfficeName"); gnTelephoneNumberEntry.Text = conn.Data.GetAttributeValueFromEntry(currentEntry, "telephoneNumber"); gnEmailEntry.Text = conn.Data.GetAttributeValueFromEntry(currentEntry, "mail"); gnWebPageEntry.Text = conn.Data.GetAttributeValueFromEntry(currentEntry, "wWWHomePage"); adStreetTextView.Buffer.Text = conn.Data.GetAttributeValueFromEntry(currentEntry, "streetAddress"); adPOBoxEntry.Text = conn.Data.GetAttributeValueFromEntry(currentEntry, "postOfficeBox"); adCityEntry.Text = conn.Data.GetAttributeValueFromEntry(currentEntry, "l"); adStateEntry.Text = conn.Data.GetAttributeValueFromEntry(currentEntry, "st"); adZipEntry.Text = conn.Data.GetAttributeValueFromEntry(currentEntry, "postalCode"); adCountryEntry.Text = conn.Data.GetAttributeValueFromEntry(currentEntry, "co"); tnHomeEntry.Text = conn.Data.GetAttributeValueFromEntry(currentEntry, "homePhone"); tnPagerEntry.Text = conn.Data.GetAttributeValueFromEntry(currentEntry, "pager"); tnMobileEntry.Text = conn.Data.GetAttributeValueFromEntry(currentEntry, "mobile"); tnFaxEntry.Text = conn.Data.GetAttributeValueFromEntry(currentEntry, "facsimileTelephoneNumber"); tnIPPhoneEntry.Text = conn.Data.GetAttributeValueFromEntry(currentEntry, "ipPhone"); tnNotesTextView.Buffer.Text = conn.Data.GetAttributeValueFromEntry(currentEntry, "info"); ozTitleEntry.Text = conn.Data.GetAttributeValueFromEntry(currentEntry, "title"); ozDeptEntry.Text = conn.Data.GetAttributeValueFromEntry(currentEntry, "department"); ozCompanyEntry.Text = conn.Data.GetAttributeValueFromEntry(currentEntry, "company"); accLoginNameEntry.Text = conn.Data.GetAttributeValueFromEntry(currentEntry, "userPrincipalName"); proPathEntry.Text = conn.Data.GetAttributeValueFromEntry(currentEntry, "profilePath"); proLogonScriptEntry.Text = conn.Data.GetAttributeValueFromEntry(currentEntry, "scriptPath"); proLocalPathEntry.Text = conn.Data.GetAttributeValueFromEntry(currentEntry, "homeDirectory"); adUserDialog.Title = conn.Data.GetAttributeValueFromEntry(currentEntry, "cn") + " Properties"; adUserDialog.Run(); while (missingValues || errorOccured) { if (missingValues) { missingValues = false; } else if (errorOccured) { errorOccured = false; } adUserDialog.Run(); } adUserDialog.Destroy(); }
public bool SearchUser(Models.Environment enviro, ref User user) { bool rval = false; try { string server = "", bindPwd = ""; switch (enviro) { case Models.Environment.QA: server = GetStringValue("S_ldap_ED_server_QA"); bindPwd = GetStringValue("S_ldap_ED_bindPwd_QA"); break; case Models.Environment.Dev: server = GetStringValue("S_ldap_ED_server_Dev"); bindPwd = GetStringValue("S_ldap_ED_bindPwd_Dev"); break; default: // Prod server = GetStringValue("S_ldap_ED_server"); bindPwd = GetStringValue("S_ldap_ED_bindPwd"); break; } ILdapConnection ldapConn = new LdapConnection() { SecureSocketLayer = GetBoolValue("S_ldap_ED_isSSL") }; ldapConn.Connect(server, GetIntValue("S_ldap_ED_port")); ldapConn.Bind(GetStringValue("S_ldap_ED_bindName"), bindPwd); string userSearch = String.Format(GetStringValue("S_ldap_ED_userNameFrmt"), user.login_id); string baseSearch = ""; // "ou=People,o=eaton.com"; LdapSearchResults search = ldapConn.Search(baseSearch, LdapConnection.SCOPE_SUB, userSearch, null, false); if (search != null) // && search.Count > 0) { LdapEntry le = search.First <LdapEntry>(); if (le != null) { string name = le.DN; LdapAttributeSet set = le.getAttributeSet(); if (set != null) { IEnumerator ienum = set.GetEnumerator(); while (ienum.MoveNext()) { LdapAttribute attribute = (LdapAttribute)ienum.Current; string attributeName = attribute.Name; string attributeVal = attribute.StringValue; if (String.Compare(attributeName, GetStringValue("S_ED_FirstName"), true) == 0) { user.first_name = attributeVal; } else if (String.Compare(attributeName, GetStringValue("S_ED_LastName"), true) == 0) { user.last_name = attributeVal; } else if (String.Compare(attributeName, GetStringValue("S_ED_Email"), true) == 0) { user.email = attributeVal; } else { user.attributes.Add(attributeName, attributeVal); } } } } } } catch (Exception ex) { Trace.WriteLine("Exception in SearchUser(), details: " + ex.ToString()); throw ex; } return(rval); }
/// <summary> /// For this entry, get all the ldap attributes such as Names, group property and home server /// </summary> /// <param name="conn">ldap connection</param> /// <param name="entry">entry for this user/member</param> /// <param name="group">group</param> /// <param name="groupList">list of 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 groupmembership = ""; string iFolderHomeServer = ""; 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; } if (firstName != null && lastName != null) { if (FullNameDisplay == "FirstNameLastName") { fullName = firstName + " " + lastName; } else { fullName = lastName + " " + firstName; } } else { fullName = commonName; } 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 += ";"; } } 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( null, commonName, firstName, lastName, fullName, distinguishedName, propertyList, Group, groupmembers, groupmembership, iFolderHomeServer); } else { state.ProcessMember( null, commonName, firstName, lastName, fullName, distinguishedName, null, Group, groupmembers, groupmembership, iFolderHomeServer); } } }
// read and print search results public static bool searchDynamicGroupEntry(LdapConnection lc, String searchBase) { bool status = true; int searchScope = LdapConnection.SCOPE_BASE; String[] attrList = new String[] { "member" }; String searchFilter = "(objectclass=*)"; /* 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; try { LdapSearchResults searchResults = lc.Search(searchBase, searchScope, searchFilter, attrList, // return only "member" attr false, // return attrs and values cons); // time out value LdapEntry nextEntry = null; // Read and print search results. We expect only one entry */ if ((nextEntry = searchResults.Next()) != null) { LdapAttributeSet attributeSet = nextEntry.getAttributeSet(); IEnumerator allAttributes = attributeSet.GetEnumerator(); if (allAttributes.MoveNext()) { // found member(s) in this group LdapAttribute attribute = (LdapAttribute)allAttributes.Current; String attributeName = attribute.Name; IEnumerator allValues = attribute.StringValues; if (allValues != null) { while (allValues.MoveNext()) { String Value = (String)allValues.Current; Console.WriteLine(" " + attributeName + " : " + Value); } } } else { // no member(s) found in this group Console.WriteLine(" No objects matched the " + " memberQueryURL filter.\n "); } } } catch (LdapException e) { Console.WriteLine("Error: " + e.ToString()); status = false; } return(status); }
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> /// Determines the existence of an object /// </summary> /// <param name="key">The property</param> /// <param name="value">The property value</param> /// <returns></returns> private bool Exists(string key, string value) { LdapEntry obj = ForLdapEntry(key, value); return(obj != null); }
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); }
public List <DomainObject> ConvertLdapResultsToDomainObjects(LdapEntry result) { return(null); }
/// <summary> /// Queries and fills the ldap message for the selected computer /// Gets the attribute list from AD for computer schema attribute. /// search for the attributes dNSHostName, cn or name and displays them in a controls /// </summary> /// <param name="ce"></param> /// <param name="servername"></param> /// <param name="name"></param> /// <param name="dirnode"></param> public void SetData(CredentialEntry ce, string servername, string name, ADUCDirectoryNode dirnode) { try { this.dirnode = dirnode; int ret = -1; List <LdapEntry> ldapEntries = null; ret = dirnode.LdapContext.ListChildEntriesSynchronous (dirnode.DistinguishedName, LdapAPI.LDAPSCOPE.BASE, "(objectClass=*)", null, false, out ldapEntries); if (ldapEntries == null || ldapEntries.Count == 0) { return; } LdapEntry ldapNextEntry = ldapEntries[0]; string[] attrsList = ldapNextEntry.GetAttributeNames(); if (attrsList != null) { foreach (string attr in attrsList) { string sValue = ""; LdapValue[] attrValues = ldapNextEntry.GetAttributeValues(attr, dirnode.LdapContext); if (attrValues != null && attrValues.Length > 0) { foreach (LdapValue value in attrValues) { sValue = sValue + "," + value.stringData; } } if (sValue.StartsWith(",")) { sValue = sValue.Substring(1); } sValue = sValue.Substring(0, sValue.Length); if (string.Compare(sValue, "") == 0) { sValue = "<Not Set>"; } if (string.Compare(attr, "cn") == 0) { this.lblComputerName.Text = sValue; } if (string.Compare(attr, "sAMAccountName") == 0) { if (sValue.EndsWith("$")) { this.txtCName.Text = sValue.Substring(0, sValue.Length - 1); } else { this.txtCName.Text = sValue; } } if (string.Compare(attr, "description") == 0) { this.txtDescription.Text = sValue; _editObject.Description = sValue; } if (string.Compare(attr, "dNSHostName") == 0) { this.txtDNSName.Text = sValue; } if (string.Compare(attr, "userAccountControl") == 0) { int userCtrlVal = 0; if (attrValues != null && attrValues.Length > 0) { userCtrlVal = Convert.ToInt32(attrValues[0].stringData); } string userCtrlBinStr = UserGroupUtils.DecimalToBase(userCtrlVal, 16); _editObject.UserCtrlBinStr = userCtrlVal; this.txtRole.Text = "Workstation or server"; if (userCtrlBinStr.Length >= 3) { //Determine role of computer if (userCtrlBinStr.Length == 3) { //examine the third position from the left (2=NORMAL_ACCOUNT) if (userCtrlBinStr[0] == '2') { this.txtRole.Text = "Normal computer"; } //examine the third position from the left (2=INTERDOMAIN_TRUST_ACCOUNT) if (userCtrlBinStr[0] == '8') { this.txtRole.Text = "Inter domain trust computer"; } } else { //examine the forth position from the left (2=WORKSTATION_TRUST_ACCOUNT) if (userCtrlBinStr[userCtrlBinStr.Length - 4] == '1') { this.txtRole.Text = "Workstation or server"; } //examine the forth position from the left (2=SERVER_TRUST_ACCOUNT) if (userCtrlBinStr[userCtrlBinStr.Length - 4] == '2') { this.txtRole.Text = "Domain controller"; } } } if (userCtrlBinStr.Length >= 5) { //Determine whether this user is TRUSTED_FOR_DELEGATION //examine the fifth position from the left (8=TRUSTED_FOR_DELEGATION, 0=NOT TRUSTED) //TRUSTED_FOR_DELEGATION if (userCtrlBinStr[userCtrlBinStr.Length - 5] == '8') { this.checkBoxTrust.CheckedChanged -= new System.EventHandler(this.checkBoxTrust_CheckedChanged); checkBoxTrust.Checked = true; this.checkBoxTrust.CheckedChanged += new System.EventHandler(this.checkBoxTrust_CheckedChanged); } else if (userCtrlBinStr[userCtrlBinStr.Length - 5] == '0') { checkBoxTrust.Checked = false; } } else { checkBoxTrust.Checked = false; } _editObject.DelegateTrust = checkBoxTrust.Checked; } } } UpdateOriginalData(); UpdateApplyButton(); } catch (Exception e) { container.ShowError(e.Message); } }
static void Main(string[] args) { if (args.Length != 6) { Console.WriteLine("Usage: mono Search <host name> <ldap port> <login dn>" + " <password> <search base>" + " <search filter>"); Console.WriteLine("Example: mono Search 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]; 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; } }
public static bool IsUser(this LdapEntry entry) { return(entry.ObjectClass().Contains("user")); }
public static void Run(string[] args) { if (args.Length != 6) { Usage(); return; } string ldapHost = args[0]; int ldapPort = Convert.ToInt32(args[1]); String loginDN = args[2]; String password = args[3]; String searchBase = args[4]; String searchFilter = args[5]; try { using (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 ex) { Printer.Error(ex.ToString()); // Exception is thrown, go for next entry continue; } Console.WriteLine("--------------------------------------------------------------------------------"); Console.WriteLine(nextEntry.DN); Console.WriteLine("--------------------------------------------------------------------------------"); LdapAttributeSet attributeSet = nextEntry.getAttributeSet(); 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)); } Printer.PrintAttribute(attributeName, attributeVal); } } } } catch (LdapException ex) { Printer.Error(ex.ToString()); return; } catch (Exception ex) { Printer.Error(ex.ToString()); return; } }
public static bool ContainsAttr(this LdapEntry entry, string attrName) { LdapAttribute ldapAttribute = new LdapAttribute(attrName); return(entry.getAttributeSet().Contains(ldapAttribute)); }
public override void OnEditEntry(Connection connection, LdapEntry le) { new EditContactsViewDialog(connection, le); }
public void RefreshSchema() { try { const string baseDN = "cn=schemacontext"; ILdapMessage ldMsg = null; try { List <ILdapEntry> attributesResponse = _conn.SearchAndGetEntries(baseDN, LdapScope.SCOPE_SUBTREE, "(objectclass=attributeschema)", null, 0, ref ldMsg); List <ILdapEntry> schemaResponse = _conn.SearchAndGetEntries(baseDN, LdapScope.SCOPE_SUBTREE, "(objectclass=classschema)", null, 0, ref ldMsg); if (attributesResponse.Count == 0 || schemaResponse.Count == 0) { throw new Exception("Failed to get schema"); } var schemaDict = new Dictionary <string, Dictionary <string, object> >(); var attrDict = new Dictionary <string, Dictionary <string, object> >(); CollectData(schemaResponse, OBJECTCLASSES, schemaDict); CollectData(attributesResponse, ATTRIBUTETYPES, attrDict); ParseAttributes(attrDict); ParseObjectClasses(schemaDict); } finally { if (ldMsg != null) { (ldMsg as LdapMessage).FreeMessage(); } } } catch (Exception e) { if (string.Equals(e.Message, "Failed to get schema")) { const string baseDN = "cn=aggregate,cn=schemacontext"; var attribs = new string[] { ATTRIBUTETYPES, OBJECTCLASSES }; ILdapMessage ldMsg = null; try { List <ILdapEntry> response = _conn.SearchAndGetEntries(baseDN, LdapScope.SCOPE_SUBTREE, "(objectClass=*)", attribs, 0, ref ldMsg); if (response.Count == 0) { throw new Exception("Failed to get schema, possibly server version is incompatible."); } LdapEntry baseEntry = (LdapEntry)response[0]; var dict = CollectData(baseEntry); ParseAttributes(dict[ATTRIBUTETYPES]); ParseObjectClasses(dict[OBJECTCLASSES]); } finally { if (ldMsg != null) { (ldMsg as LdapMessage).FreeMessage(); } } } else { throw e; } } }
private LdapEntry LocateLdapUser(string username) { var foundUser = false; LdapEntry ldapUser = null; using (var ldapClient = new LdapConnection { SecureSocketLayer = _config.UseSsl }) { try { if (_config.SkipSslVerify) { ldapClient.UserDefinedServerCertValidationDelegate += LdapClient_UserDefinedServerCertValidationDelegate; } ldapClient.Connect(_config.LdapServer, _config.LdapPort); if (_config.UseStartTls) { ldapClient.StartTls(); } ldapClient.Bind(_config.LdapBindUser, _config.LdapBindPassword); } catch (Exception e) { _logger.LogError(e, "Failed to Connect or Bind to server"); throw new AuthenticationException("Failed to Connect or Bind to server"); } finally { ldapClient.UserDefinedServerCertValidationDelegate -= LdapClient_UserDefinedServerCertValidationDelegate; } if (!ldapClient.Connected) { _logger.LogWarning("LDAP not connected"); return(null); } var ldapUsers = ldapClient.Search(_config.LdapBaseDn, 2, SearchFilter, LdapUsernameAttributes, false); if (ldapUsers == null) { _logger.LogWarning("No LDAP users found from query"); throw new AuthenticationException("No users found in LDAP Query"); } _logger.LogDebug("Search: {1} {2} @ {3}", _config.LdapBaseDn, SearchFilter, _config.LdapServer); while (ldapUsers.HasMore() && foundUser == false) { var currentUser = ldapUsers.Next(); foreach (var attr in LdapUsernameAttributes) { var toCheck = GetAttribute(currentUser, attr); if (toCheck?.StringValueArray != null) { foreach (var name in toCheck.StringValueArray) { if (username == name) { ldapUser = currentUser; foundUser = true; } } } } } if (foundUser == false) { _logger.LogError("Found no users matching {1} in LDAP search.", username); throw new AuthenticationException("Found no LDAP users matching provided username."); } } return(ldapUser); }
/// <summary> /// If the configured Simias Admin is different than the SimiasAdmin /// identified in the store, make all the changes necessary to /// make the configured admin the store admin. /// </summary> /// <param name="conn">ldap connection</param> private void ChangeSimiasAdmin(LdapConnection conn) { char[] dnDelimiters = { ',', '=' }; LdapEntry entry = null; Property dn; string commonName; string ldapGuid; string[] searchAttributes = { "cn", "sn", "uid" }; try { // Nothing in the config for a SimiasAdmin - we're done here if (ldapSettings.AdminDN == null || ldapSettings.AdminDN == "") { return; } // If the SimiasAdmin has been changed in the Simias.config, which BTW // is not something that is exposed in the normal management UI, // we need to verify the new SimiasAdmin exists in the directory, // check if the new admin exists in local domain memberlist (and // if he doesn't create him), transfer default domain ownership // to the new SimiasAdmin and lastly transfer ownership of all // orphaned iFolders to the new SimiasAdmin. try { entry = conn.Read(OpenSync.ldapSettings.AdminDN, searchAttributes); } catch (LdapException lEx) { log.Error("Could not verify the newly configured Simias Administrator in the directory"); log.Error(lEx.Message); } catch (Exception e1) { log.Error("Could not verify the newly configured Simias Administrator in the directory"); log.Error(e1.Message); } if (entry == null) { return; } ldapGuid = GetLdapGuid(entry); if (ldapGuid == null || ldapGuid == "") { return; } // Get the common name from the Simias.config.AdminDN entry string[] components = OpenSync.ldapSettings.AdminDN.Split(dnDelimiters); commonName = (components[0].ToLower() == "cn") ? components[1] : components[0]; if (commonName == null || commonName == "") { return; } store = Store.GetStore(); if (domain == null) { domain = store.GetDomain(store.DefaultDomain); if (domain == null) { throw new SimiasException("Enterprise domain does not exist!"); } } Member member = domain.GetMemberByName(commonName); if (member == null) { // Create the member with the Ldap guid member = new Member(commonName, ldapGuid, Simias.Storage.Access.Rights.ReadOnly); member.Properties.ModifyProperty("DN", ldapSettings.AdminDN); } Property lguid = new Property("LdapGuid", ldapGuid); lguid.LocalProperty = true; member.Properties.ModifyProperty(lguid); domain.Commit(member); // Transfer ownership of all collections owned by the // previous admin that have the orphaned property Property orphaned; ICSList subList = store.GetCollectionsByOwner(domain.Owner.ID, domain.ID); foreach (ShallowNode sn in subList) { // Get the collection object for this node. Collection c = store.GetCollectionByID(sn.CollectionID); if (c != null) { orphaned = c.Properties.GetSingleProperty("OrphanedOwner"); if (orphaned != null) { dn = c.Owner.Properties.GetSingleProperty("DN"); if (dn != null) { c.PreviousOwner = dn.Value.ToString(); c.Commit(); } c.Commit(c.ChangeOwner(member, Simias.Storage.Access.Rights.ReadWrite)); } } } // For now I'm just going to leave the LdapGuid property // on the old SimiasAdmin dn = domain.Owner.Properties.GetSingleProperty("DN"); if (dn != null) { domain.PreviousOwner = dn.Value.ToString(); domain.Commit(); } domain.Commit(domain.ChangeOwner(member, Simias.Storage.Access.Rights.ReadWrite)); } catch (Exception vsa) { log.Error(vsa.Message); log.Error(vsa.StackTrace); } }
public static string[] GetAttributeArrayValue(this LdapEntry ldapEntry, string attributeName) { var attribute = ldapEntry.getAttribute(attributeName); return(attribute == null ? null : attribute.StringValueArray); }
/// <summary> /// process each member of this container /// </summary> /// <param name="conn">ldap connection</param> /// <param name="searchContainer">container to be searched</param> private void ProcessSearchContainer(LdapConnection conn, String searchContainer) { String searchFilter = "(objectclass=inetOrgPerson)"; string[] searchAttributes = { "modifytimestamp", ldapSettings.NamingAttribute, "cn", "sn", "uid", "givenName", "ou" }; 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(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"); }
private void CommitEntry() { PropertyCollection properties = GetProperties(false); if (!Nflag) { System.Collections.ArrayList modList = new System.Collections.ArrayList(); foreach (string attribute in properties.PropertyNames) { LdapAttribute attr = null; if (properties [attribute].Mbit) { switch (properties [attribute].Count) { case 0: attr = new LdapAttribute(attribute, new string [0]); modList.Add(new LdapModification(LdapModification.DELETE, attr)); break; case 1: string val = (string)properties [attribute].Value; attr = new LdapAttribute(attribute, val); modList.Add(new LdapModification(LdapModification.REPLACE, attr)); break; default: object [] vals = (object [])properties [attribute].Value; string [] aStrVals = new string [properties [attribute].Count]; Array.Copy(vals, 0, aStrVals, 0, properties [attribute].Count); attr = new LdapAttribute(attribute, aStrVals); modList.Add(new LdapModification(LdapModification.REPLACE, attr)); break; } properties [attribute].Mbit = false; } } if (modList.Count > 0) { LdapModification[] mods = new LdapModification[modList.Count]; Type mtype = typeof(LdapModification); mods = (LdapModification[])modList.ToArray(mtype); ModEntry(mods); } } else { LdapAttributeSet attributeSet = new LdapAttributeSet(); foreach (string attribute in properties.PropertyNames) { if (properties [attribute].Count == 1) { string val = (string)properties [attribute].Value; attributeSet.Add(new LdapAttribute(attribute, val)); } else { object[] vals = (object [])properties [attribute].Value; string[] aStrVals = new string [properties [attribute].Count]; Array.Copy(vals, 0, aStrVals, 0, properties [attribute].Count); attributeSet.Add(new LdapAttribute(attribute, aStrVals)); } } LdapEntry newEntry = new LdapEntry(Fdn, attributeSet); conn.Add(newEntry); Nflag = false; } }
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); }
public static IWebHost BuildWebHost() => new WebHostBuilder() .UseKestrel(options => options.AddServerHeader = false) .UseContentRoot(Directory.GetCurrentDirectory()) .ConfigureAppConfiguration((hostingContext, config) => { var env = hostingContext.HostingEnvironment; config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true); config.AddEnvironmentVariables(); AppSettings = config.Build().Get <AppSettings>(); }) .ConfigureLogging((hostingContext, logging) => { if (hostingContext.HostingEnvironment.IsDevelopment()) { logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging")); logging.AddConsole(); } }) .UseDefaultServiceProvider((context, options) => { options.ValidateScopes = context.HostingEnvironment.IsDevelopment(); }) .ConfigureServices(services => { services.AddRouting(); if (AppSettings.Cors.Enabled) { services.AddCors(); } }) .Configure(app => { app.ConfigureCors(AppSettings); app.UseRouter(r => { r.MapGet("users", async context => { using (var cn = new LdapConnection()) { cn.Connect(AppSettings.Ldap.Host, AppSettings.Ldap.Port); cn.Bind(AppSettings.Ldap.User, AppSettings.Ldap.Password); string @base = GetBase(context); if (string.IsNullOrEmpty(@base)) { context.Response.StatusCode = 400; await context.Response.WriteAsync("No base defined."); return; } string[] attrs = GetAttrs(context); IEnumerable <Filter> filters = context.Request.Query.GetFilters().ToList(); var builder = new LdapQueryBuilder(SearchType.User); if (filters.Any()) { foreach (Filter filter in filters) { builder.AddFilter(filter); } } string ldapQuery = builder.Build(); LdapSearchResults ldapResults = cn.Search(@base, LdapConnection.SCOPE_SUB, ldapQuery, attrs, false); var entries = new List <LdapEntry>(); var array = new JArray(); while (ldapResults.hasMore()) { LdapEntry user = ldapResults.next(); var attrSet = user.getAttributeSet(); JObject @object = new JObject(); foreach (LdapAttribute ldapAttribute in attrSet) { @object.Add(ldapAttribute.Name, ldapAttribute?.StringValue); } array.Add(@object); entries.Add(user); } string json = array.ToString(); context.Response.ContentType = "application/json"; await context.Response.WriteAsync(json); } }); }); }) .Build();
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; }
public ADRenameUserDlg(ADUCDirectoryNode dirnode, string parentDN) : this() { this.ParentDN = parentDN; this._dirnode = dirnode; this.renameUserInfo = new RenameUserInfo(); int ret = -1; List <LdapEntry> ldapEntries = null; ret = _dirnode.LdapContext.ListChildEntriesSynchronous( _dirnode.DistinguishedName, LdapAPI.LDAPSCOPE.BASE, "(objectClass=*)", null, false, out ldapEntries); if (ldapEntries == null || ldapEntries.Count == 0) { return; } LdapEntry ldapNextEntry = ldapEntries[0]; string[] attrsList = ldapNextEntry.GetAttributeNames(); if (attrsList != null) { foreach (string attr in attrsList) { string sValue = ""; LdapValue[] attrValues = ldapNextEntry.GetAttributeValues(attr, _dirnode.LdapContext); if (attrValues != null && attrValues.Length > 0) { foreach (LdapValue value in attrValues) { sValue = sValue + "," + value.stringData; } } if (sValue.StartsWith(",")) { sValue = sValue.Substring(1); } if (string.Compare(sValue, "") == 0) { sValue = "<Not Set>"; } if (string.Compare(attr, "cn") == 0) { this.FullNametextbox.Text = sValue; renameUserInfo.fullName = sValue; } if (string.Compare(attr, "displayName") == 0) { this.displaynametextBox.Text = sValue; renameUserInfo.displayName = sValue; } if (string.Compare(attr, "givenName") == 0) { this.FnametextBox.Text = sValue; renameUserInfo.fName = sValue; } if (string.Compare(attr, "initials") == 0) { this.InitialtextBox.Text = sValue; renameUserInfo.initials = sValue; } if (string.Compare(attr, "sn") == 0) { this.LnametextBox.Text = sValue; renameUserInfo.lName = sValue; } if (string.Compare(attr, "userPrincipalName") == 0) { string[] pre = sValue.Split('@'); this.logonNametextBox.Text = pre[0].Trim(); renameUserInfo.logonName = sValue; } if (string.Compare(attr, "sAMAccountName") == 0) { this.userlogonPretextBox.Text = sValue; renameUserInfo.userPrelogonname = sValue; } } } string[] prefixes = dirnode.LdapContext.DomainName.Split('.'); string prefix = string.Concat(prefixes[0].ToUpper(), "\\"); this.prelogontextBox.Text = prefix; this.domainNamecomboBox.Items.Add(dirnode.LdapContext.DomainName); this.domainNamecomboBox.SelectedIndex = 0; }