public Search ( System base_Renamed, int scope, System filter, System attrs, bool typesOnly, LdapSearchQueue queue ) : LdapSearchQueue | ||
base_Renamed | System | |
scope | int | The scope of the entries to search. The following
/// are the valid options:
///
|
filter | System | Search filter specifying the search criteria. /// /// |
attrs | System | Names of attributes to retrieve. /// /// |
typesOnly | bool | If true, returns the names but not the values of /// the attributes found. If false, returns the /// names and values for attributes found. /// /// |
queue | LdapSearchQueue | Handler for messages returned from a server in /// response to this request. If it is null, a /// queue object is created internally. /// /// |
Résultat | LdapSearchQueue |
// 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 UserViewModel Login(string username, string password) { // Creating an LdapConnection instance var ldapConn = new LdapConnection(); var tempDomainName = new StringBuilder(100); if (!string.IsNullOrEmpty(_settings.DomainName)) { tempDomainName.Append(_settings.DomainName); tempDomainName.Append('\\'); } tempDomainName.Append(username); //Connect function will create a socket connection to the server ldapConn.Connect(_settings.Address, _settings.PortNumber); //Bind function will Bind the user object Credentials to the Server ldapConn.Bind(tempDomainName.ToString(), password); var uservm = new UserViewModel() { UserName = username, Name = username }; var cons = ldapConn.SearchConstraints; cons.ReferralFollowing = true; ldapConn.Constraints = cons; var attributes = _settings.Attributes?.Trim() == "" ? null : _settings.Attributes?.Split(",").Select(s => s.Trim()); var lsc = ldapConn.Search(_settings.DistinguishedName, (int)Enum.Parse <SearchScope>(_settings.SearchScope), $"(sAMAccountName={username})", attributes?.ToArray(), false, (LdapSearchConstraints)null); while (lsc.HasMore()) { LdapEntry nextEntry = null; nextEntry = lsc.Next(); var attributeSet = nextEntry.GetAttributeSet(); System.Collections.IEnumerator ienum = attributeSet.GetEnumerator(); while (ienum.MoveNext()) { var attribute = (LdapAttribute)ienum.Current; var attributeName = attribute.Name; var attributeVal = attribute.StringValue; uservm.CustomClaims.Add(new Claim(attributeName, attributeVal)); } } return(uservm); }
public User Login(string userName, string password) { User user = new User(); using (var cn = new Novell.Directory.Ldap.LdapConnection()) { cn.Connect(config.Path, config.Port); try { cn.Bind(config.UserDomainName + "\\" + userName, password); } catch (Exception e) { Console.WriteLine(e.Message); Console.WriteLine("Failed login attempt for user " + userName); user = null; return(user); } string filter = "sAMAccountname=" + userName; string baseStr = "OU=BLS,DC=blacklanternsecurity,DC=com"; LdapSearchResults result = (LdapSearchResults)cn.Search(baseStr, LdapConnection.ScopeSub, filter, null, false); LdapEntry entry = null; try { entry = result.First(); } catch (LdapException e) { Console.WriteLine("Error: " + e.LdapErrorMessage); } LdapAttributeSet attributeSet = entry.GetAttributeSet(); user.DisplayName = attributeSet.GetAttribute("displayName").StringValue; user.GivenName = attributeSet.GetAttribute("givenName").StringValue; user.UserName = userName; return(user); } }
/// <summary> /// Checks whether the entry exists in the Ldap directory or not /// </summary> /// <param name="lconn"> /// Connection used to communicate with directory /// </param> /// <param name="epath"> /// path of the entry /// </param> /// <returns> /// true of the entry exists in the Ldap directory /// false if entry doesn't exists /// </returns> private static bool CheckEntry(LdapConnection lconn, string epath) { LdapUrl lUrl=new LdapUrl(epath); string eDn=lUrl.getDN(); if(eDn==null) { eDn = String.Empty; } // rootDSE is a "virtual" entry that always exists else if (String.Compare (eDn,"rootDSE",true) == 0) return true; string[] attrs={"objectClass"}; try { LdapSearchResults lsc=lconn.Search( eDn, LdapConnection.SCOPE_BASE, "objectClass=*", attrs, false); while(lsc.hasMore()) { LdapEntry nextEntry = null; try { nextEntry = lsc.next(); } catch(LdapException e) { // Exception is thrown, go for next entry throw e; } break; } } catch(LdapException le) { if(le.ResultCode == LdapException.NO_SUCH_OBJECT) { return false; } else { throw le; } } catch(Exception e) { throw e; } return true; }
public async Task ValidateAsync(ResourceOwnerPasswordValidationContext context) { try { if (String.IsNullOrEmpty(context.UserName) || String.IsNullOrEmpty(context.Password)) { context.Result = new GrantValidationResult(TokenRequestErrors.InvalidRequest, "As credenciais do usuário são obrigatórias", null); return; } string cpfMok = null; switch (context.UserName) { case "sisgp_gestor": cpfMok = "08056275029"; break; case "sisgp_cg": cpfMok = "95387502500"; break; case "sisgp_coget": cpfMok = "43321040565"; break; case "sisgp_coordenador": cpfMok = "25715446597"; break; case "sisgp_diretor": cpfMok = "39178470510"; break; case "sisgp_servidor": cpfMok = "08152972541"; break; case "sisgp_servidor1": cpfMok = "59516301002"; break; case "sisgp_servidor2": cpfMok = "18761704091"; break; case "sisgp_servidor3": cpfMok = "07721701007"; break; case "sisgp_servidor4": cpfMok = "51884275087"; break; } Pessoa pessoa = null; if (!string.IsNullOrEmpty(cpfMok)) { //if (context.Password.ToUpper() == "S20211014") //{ pessoa = await this.PessoaRepository.ObterPorCriteriosAsync(null, cpfMok); //} } else { if (this.Options.Value.Configurations == null) { context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, "As configurações do LDAP são inválidas", null); } else { pessoa = await Task.Run(() => { foreach (var configuration in this.Options.Value.Configurations) { using (var connection = new Novell.Directory.Ldap.LdapConnection()) { try { connection.Connect(configuration.Url, configuration.Port); connection.Bind(configuration.BindDN, configuration.BindPassword); } catch { context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, "Não foi possível pesquisar no LDAP. A autenticação do usuário de serviço falhou", null); return(null); } List <string> attibutes = new List <string>(); if (!String.IsNullOrEmpty(configuration.SisrhIdAttributeFilter)) { attibutes.Add(configuration.SisrhIdAttributeFilter); } if (!String.IsNullOrEmpty(configuration.EmailAttributeFilter)) { attibutes.Add(configuration.EmailAttributeFilter); } if (!String.IsNullOrEmpty(configuration.CpfAttributeFilter)) { attibutes.Add(configuration.CpfAttributeFilter); } var searchFilter = String.Format(configuration.SearchFilter, context.UserName); var entities = connection.Search( configuration.SearchBaseDC, Novell.Directory.Ldap.LdapConnection.ScopeSub, searchFilter, attibutes.ToArray(), false); while (entities.HasMore()) { var entity = entities.Next(); var entityAttributes = entity.GetAttributeSet(); //Valida o password connection.Bind(entity.Dn, context.Password); var sisrhId = GetAttributeValue(entity, configuration.SisrhIdAttributeFilter); if (!String.IsNullOrEmpty(sisrhId)) { var _pessoa = this.PessoaRepository.ObterAsync(Int64.Parse(sisrhId)); if (_pessoa != null) { return(_pessoa); } } string email = GetAttributeValue(entity, configuration.EmailAttributeFilter); string cpf = GetAttributeValue(entity, configuration.CpfAttributeFilter); var dadosPessoa = this.PessoaRepository.ObterPorCriteriosAsync(email, cpf); if (dadosPessoa != null) { return(dadosPessoa); } } } } return(null); }); } } if (pessoa != null) { context.Result = new GrantValidationResult(pessoa.PessoaId.ToString(), "password", null, "local", null); } else { if (context.Result == null) { context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, "Não foi encontrado usuário com esse login", null); } } } catch (Novell.Directory.Ldap.LdapException ex) { context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, ex.Message, null); context.Result.Error = ex.StackTrace.ToString(); } }
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); }
public static void Main( String[] args ) { if (args.Length != 5) { Console.Error.WriteLine("Usage: mono List <host name> <login dn>" + " <password> <search base>\n" + " <search filter>"); Console.Error.WriteLine("Example: mono List Acme.com \"cn=admin,o=Acme\"" + " secret \"ou=sales,o=Acme\"\n" + " \"(objectclass=*)\""); Environment.Exit(1); } int LdapPort = LdapConnection.DEFAULT_PORT; int searchScope = LdapConnection.SCOPE_ONE; int LdapVersion = LdapConnection.Ldap_V3;; bool attributeOnly = true; String[] attrs = {LdapConnection.NO_ATTRS}; String ldapHost = args[0]; String loginDN = args[1]; String password = args[2]; String searchBase = args[3]; String searchFilter = args[4]; LdapConnection lc = new LdapConnection(); try { // connect to the server lc.Connect( ldapHost, LdapPort ); // bind to the server lc.Bind( LdapVersion, loginDN, password ); LdapSearchResults searchResults = lc.Search( searchBase, // container to search searchScope, // search scope searchFilter, // search filter attrs, // "1.1" returns entry name only attributeOnly); // no attributes are returned // print out all the objects while ( searchResults.hasMore() ) { LdapEntry nextEntry = null; try { nextEntry = searchResults.next(); } catch(LdapException e) { Console.WriteLine("Error: " + e.ToString()); // Exception is thrown, go for next entry continue; } Console.WriteLine("\n" + nextEntry.DN); } // disconnect with the server lc.Disconnect(); } catch( LdapException e ) { Console.WriteLine( "Error: " + e.ToString() ); } catch( Exception e ) { Console.WriteLine( "Error: " + e.ToString() ); } Environment.Exit(0); }
private void PopulateGroupsForUserWithQuery(XDoc doc, string username, LdapConnection conn) { doc.Start("groups"); string searchFilter = string.Format(Dream.PhpUtil.ConvertToFormatString(_config.GroupMembershipQuery), username); //Build interesting attribute list List<string> attrs = new List<string>(); attrs.AddRange(new string[] { "whenCreated", "name", "sAMAccountName", "cn" }); LdapSearchConstraints cons = new LdapSearchConstraints(new LdapConstraints(_timeLimit, true, null, 0)); cons.BatchSize = 0; LdapSearchResults results = conn.Search(_config.LdapSearchBase, LdapConnection.SCOPE_SUB, searchFilter, attrs.ToArray(), false, cons); while (results.hasMore()) { LdapEntry nextEntry = null; try { nextEntry = results.next(); } catch (LdapException x) { HandleLdapException(x); } if (nextEntry == null) throw new ArgumentNullException("nextEntry"); //Create xml from search entry doc.Start("group").Attr("name", GetNameFromDn(nextEntry.DN)).Start("ldap-dn").Value(nextEntry.DN).End().End(); } doc.End(); //groups }
private LdapSearchResults LookupLdapUser(bool retrieveGroupMembership, string username, out LdapConnection conn) { conn = Bind(); username = EscapeLdapString(username); //search filter is built based on passed userQuery with username substitution string searchFilter = this.BuildUserSearchQuery(username); //Build interesting attribute list List<string> attrs = new List<string>(); attrs.AddRange(new string[] { "sAMAccountName", "uid", "cn", "userAccountControl", "whenCreated", "name", "givenname", "sn", "telephonenumber", "mail", "description" }); if (retrieveGroupMembership) { attrs.Add(_config.GroupMembersAttribute); } if (!string.IsNullOrEmpty(_config.UserNameAttribute) && !attrs.Contains(_config.UserNameAttribute)) { attrs.Add(_config.UserNameAttribute); } //add more attributes to lookup if using a displayname-pattern string[] patternAttributes = RetrieveAttributesFromPattern(_config.DisplayNamePattern); if (patternAttributes != null) { foreach (string patternAttribute in patternAttributes) { if (!attrs.Contains(patternAttribute)) attrs.Add(patternAttribute); } } LdapSearchConstraints cons = new LdapSearchConstraints(new LdapConstraints(_timeLimit, true, null, 0)); cons.BatchSize = 0; LdapSearchResults results = conn.Search(_config.LdapSearchBase, LdapConnection.SCOPE_SUB, searchFilter, attrs.ToArray(), false, cons); return results; }
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 void Main(System.String[] args) { /* Check if we have the correct number of command line arguments */ if (args.Length != 4) { System.Console.Error.WriteLine("Usage: mono VLVControl <host name> <login dn>" + " <password> <container>"); System.Console.Error.WriteLine("Example: mono VLVControl Acme.com \"cn=admin,o=Acme\" secret" + " \"ou=Sales,o=Acme\""); System.Environment.Exit(1); } /* Parse the command line arguments */ System.String LdapHost = args[0]; System.String loginDN = args[1]; System.String password = args[2]; System.String searchBase = args[3]; int LdapPort = LdapConnection.DEFAULT_PORT; int LdapVersion = LdapConnection.Ldap_V3; LdapConnection conn = new LdapConnection(); try { // connect to the server conn.Connect(LdapHost, LdapPort); // bind to the server conn.Bind(LdapVersion, loginDN, password); System.Console.Out.WriteLine("Succesfully logged in to server: " + LdapHost); /* Set default filter - Change this line if you need a different set * of search restrictions. Read the "NDS and Ldap Integration Guide" * for information on support by Novell eDirectory of this * functionaliry. */ System.String MY_FILTER = "cn=*"; /* We are requesting that the givenname and cn fields for each * object be returned */ System.String[] attrs = new System.String[2]; attrs[0] = "givenname"; attrs[1] = "cn"; // We will be sending two controls to the server LdapControl[] requestControls = new LdapControl[2]; /* Create the sort key to be used by the sort control * Results should be sorted based on the cn attribute. * See the "NDS and Ldap Integration Guide" for information on * Novell eDirectory support of this functionaliry. */ LdapSortKey[] keys = new LdapSortKey[1]; keys[0] = new LdapSortKey("cn"); // Create the sort control requestControls[0] = new LdapSortControl(keys, true); /* Create the VLV Control. * These two fields in the VLV Control identify the before and * after count of entries to be returned */ int beforeCount = 0; int afterCount = 2; /* The VLV control request can specify the index * using one of the two methods described below: * * TYPED INDEX: Here we request all objects that have cn greater * than or equal to the letter "a" */ requestControls[1] = new LdapVirtualListControl("a", beforeCount, afterCount); /* The following code needs to be enabled to specify the index * directly * int offset = 0; - offset of the index * int contentCount = 3; - our estimate of the search result size * requestControls[1] = new LdapVirtualListControl(offset, * beforeCount, afterCount, contentCount); */ // Set the controls to be sent as part of search request LdapSearchConstraints cons = conn.SearchConstraints; cons.setControls(requestControls); conn.Constraints = cons; // Send the search request - Synchronous Search is being used here System.Console.Out.WriteLine("Calling Asynchronous Search..."); LdapSearchResults res = conn.Search(searchBase, LdapConnection.SCOPE_SUB, MY_FILTER, attrs, false, (LdapSearchConstraints) null); // Loop through the results and print them out while (res.hasMore()) { /* Get next returned entry. Note that we should expect a Ldap- *Exception object as well just in case something goes wrong */ LdapEntry nextEntry=null; try { nextEntry = res.next(); } catch (LdapException e) { if (e is LdapReferralException) continue; else { System.Console.Out.WriteLine("Search stopped with exception " + e.ToString()); break; } } /* Print out the returned Entries distinguished name. */ System.Console.Out.WriteLine(); System.Console.Out.WriteLine(nextEntry.DN); /* Get the list of attributes for the current entry */ LdapAttributeSet findAttrs = nextEntry.getAttributeSet(); /* Convert attribute list to Enumeration */ System.Collections.IEnumerator enumAttrs = findAttrs.GetEnumerator(); System.Console.Out.WriteLine("Attributes: "); /* Loop through all attributes in the enumeration */ while (enumAttrs.MoveNext()) { LdapAttribute anAttr = (LdapAttribute) enumAttrs.Current; /* Print out the attribute name */ System.String attrName = anAttr.Name; System.Console.Out.WriteLine("" + attrName); // Loop through all values for this attribute and print them System.Collections.IEnumerator enumVals = anAttr.StringValues; while (enumVals.MoveNext()) { System.String aVal = (System.String) enumVals.Current; System.Console.Out.WriteLine("" + aVal); } } } // Server should send back a control irrespective of the // status of the search request LdapControl[] controls = res.ResponseControls; if (controls == null) { System.Console.Out.WriteLine("No controls returned"); } else { // We are likely to have multiple controls returned for (int i = 0; i < controls.Length; i++) { /* Is this the Sort Response Control. */ if (controls[i] is LdapSortResponse) { System.Console.Out.WriteLine("Received Ldap Sort Control from " + "Server"); /* We could have an error code and maybe a string * identifying erring attribute in the response control. */ System.String bad = ((LdapSortResponse) controls[i]).FailedAttribute; int result = ((LdapSortResponse) controls[i]).ResultCode; // Print out error code (0 if no error) and any // returned attribute System.Console.Out.WriteLine("Error code: " + result); if ((System.Object) bad != null) System.Console.Out.WriteLine("Offending " + "attribute: " + bad); else System.Console.Out.WriteLine("No offending " + "attribute " + "returned"); } /* Is this a VLV Response Control */ if (controls[i] is LdapVirtualListResponse) { System.Console.Out.WriteLine("Received VLV Response Control from " + "Server..."); /* Get all returned fields */ int firstPosition = ((LdapVirtualListResponse) controls[i]).FirstPosition; int ContentCount = ((LdapVirtualListResponse) controls[i]).ContentCount; int resultCode = ((LdapVirtualListResponse) controls[i]).ResultCode; System.String context = ((LdapVirtualListResponse) controls[i]).Context; /* Print out the returned fields. Typically you would * have used these fields to reissue another VLV request * or to display the list on a GUI */ System.Console.Out.WriteLine("Result Code => " + resultCode); System.Console.Out.WriteLine("First Position => " + firstPosition); System.Console.Out.WriteLine("Content Count => " + ContentCount); if ((System.Object) context != null) System.Console.Out.WriteLine("Context String => " + context); else System.Console.Out.WriteLine("No Context String in returned" + " control"); } } } /* We are done - disconnect */ if (conn.Connected) conn.Disconnect(); } catch (LdapException e) { System.Console.Out.WriteLine(e.ToString()); } catch (System.IO.IOException e) { System.Console.Out.WriteLine("Error: " + e.ToString()); } catch(Exception e) { System.Console.WriteLine("Error: " + e.Message); } }
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( String[] args ) { if (args.Length != 4) { Console.WriteLine("Usage: mono ListGroups <host name> <login dn>" + " <password> <group dn>\n"); Console.WriteLine("Example: mono ListGroups Acme.com" + " \"cn=admin,o=Acme\" secret " + " cn=salesGroup,ou=sales,o=acme\n"); Environment.Exit(0); } int ldapPort = LdapConnection.DEFAULT_PORT; int searchScope = LdapConnection.SCOPE_BASE; int ldapVersion = LdapConnection.Ldap_V3; int i; IEnumerator objClass = null; IEnumerator queryURL = null; IEnumerator identity = null; IEnumerator excludedMember = null; IEnumerator member = null; bool isGroup=false, isDynamicGroup=false; String[] attrs = new String[] { "objectClass", "memberQueryURL", "dgIdentity", "excludedMember", "member"}; /* Since reading members of a dynamic group could potentially involve * a significant directory search, we use a timeout. Setting * time out to 10 seconds */ LdapSearchConstraints cons = new LdapSearchConstraints(); cons.TimeLimit = 10000 ; String ldapHost = args[0]; String loginDN = args[1]; String password = args[2]; String groupDN = args[3]; LdapConnection lc = new LdapConnection(); try { // connect to the server lc.Connect( ldapHost, ldapPort ); // bind to the server lc.Bind( ldapVersion, loginDN, password ); Console.WriteLine("\n\tReading object :" + groupDN); LdapSearchResults searchResults = lc.Search( groupDN, // object to read searchScope, // scope - read single object null, // search filter attrs, // return only required attributes false, // return attrs and values cons ); // time out value // Examine the attributes that were returned and extract the data LdapEntry nextEntry = null; try { nextEntry = searchResults.next(); } catch(LdapException e) { Console.WriteLine("Error: " + e.ToString()); Environment.Exit(1); } LdapAttributeSet attributeSet = nextEntry.getAttributeSet(); IEnumerator allAttributes = attributeSet.GetEnumerator(); while(allAttributes.MoveNext()) { LdapAttribute attribute = (LdapAttribute)allAttributes.Current; String attributeName = attribute.Name; // Save objectclass values if (attributeName.ToUpper().Equals( "objectClass".ToUpper() ) ) { objClass = attribute.StringValues; } // Save the memberQueryURL attribute if present else if (attributeName.ToUpper().Equals( "memberQueryURL".ToUpper() )) { queryURL = attribute.StringValues; } // Save the dgIdentity attribute if present else if (attributeName.ToUpper().Equals( "dgIdentity".ToUpper() ) ) { identity = attribute.StringValues; } // Save the excludedMember attribute if present else if (attributeName.ToUpper().Equals( "excludedMember".ToUpper() )) { excludedMember = attribute.StringValues; } /* Save the member attribute. This may also show up * as uniqueMember */ else if ( attributeName.ToUpper().Equals ( "member".ToUpper() ) || attributeName.ToUpper().Equals ( "uniqueMember".ToUpper() ) ) { member = attribute.StringValues; } } /* Verify that this is a group object (i.e. objectClass contains * the value "group", "groupOfNames", or "groupOfUniqueNames"). * Also determine if this is a dynamic group object * (i.e. objectClass contains the value "dynamicGroup" or * "dynamicGroupAux"). */ while(objClass.MoveNext()) { String objectName = (String) objClass.Current; if ( objectName.ToUpper().Equals( "group".ToUpper() ) || objectName.ToUpper().Equals( "groupOfNames".ToUpper() ) || objectName.ToUpper().Equals( "groupOfUniqueNames".ToUpper()) ) isGroup = true; else if ( objectName.ToUpper().Equals( "dynamicGroup".ToUpper() ) || objectName.ToUpper().Equals( "dynamicGroupAux".ToUpper() ) ) isGroup = isDynamicGroup = true; } if (!isGroup) { Console.WriteLine("\tThis object is NOT a group object." + "Exiting.\n"); Environment.Exit(0); } /* If this is a dynamic group, display its memberQueryURL, identity * and excluded member list. */ if ( isDynamicGroup ) { if ( (queryURL != null)&& (queryURL.MoveNext()) ) { Console.WriteLine("\tMember Query URL:"); while (queryURL.MoveNext()) Console.WriteLine("\t\t" + queryURL.Current); } if ( (identity != null) && (identity.MoveNext()) ) { Console.WriteLine("\tIdentity for search:" + identity.Current); } if ( (excludedMember != null) && (excludedMember.MoveNext()) ) { Console.WriteLine("\tExcluded member list:"); while (excludedMember.MoveNext()) Console.WriteLine("\t\t" + excludedMember.Current); } } // Print the goup's member list if( member != null && member.MoveNext() ) { Console.WriteLine("\n\tMember list:"); while ( member.MoveNext() ) Console.WriteLine("\t\t" + member.Current); } // disconnect with the server lc.Disconnect(); } catch( LdapException e ) { Console.WriteLine( "Error: " + e.ToString() ); Environment.Exit(1); } catch( Exception e ) { Console.WriteLine( "Error: " + e.ToString() ); } Environment.Exit(0); }
public static void Main( String[] args ) { if (args.Length != 5) { Console.WriteLine("Usage: mono ClientSideSort <host name> "+ "<login dn> <password> <search base>\n" + " <search filter>"); Console.WriteLine("Example: mono ClientSideSort Acme.com" + " \"cn=admin,o=Acme\"" + " secret \"ou=sales,o=Acme\"\n" + " \"(objectclass=*)\""); Environment.Exit(0); } int ldapPort = LdapConnection.DEFAULT_PORT; int searchScope = LdapConnection.SCOPE_ONE; int ldapVersion = LdapConnection.Ldap_V3; String ldapHost = args[0]; String loginDN = args[1]; String password = args[2]; String searchBase = args[3]; String searchFilter = args[4]; LdapConnection conn = new LdapConnection(); try { // connect to the server conn.Connect( ldapHost, ldapPort ); // bind to the server conn.Bind( ldapVersion, loginDN, password); LdapSearchResults searchResults = conn.Search( searchBase, searchScope, searchFilter, new String[] {"cn", "uid", "sn"}, //attributes false); // return attrs and values /* sortedResults will sort the entries according to the natural * ordering of LDAPEntry (by distiguished name). */ ArrayList sortedResults = new ArrayList(); while ( searchResults.hasMore()) { try { sortedResults.Add( searchResults.next() ); } catch(LdapException e) { Console.WriteLine("Error: " + e.ToString()); // Exception is thrown, go for next entry continue; } } // print the sorted results Console.WriteLine( "\n"+ "****************************\n"+ "Search results sorted by DN:\n"+ "****************************"); sortedResults.Sort(); IEnumerator i = sortedResults.GetEnumerator(0,sortedResults.Count-1); while (i.MoveNext()) { PrintEntry( (LdapEntry)(i.Current) ); } /* resort the results an an array using a specific comparator */ String[] namesToSortBy = { "sn", "uid", "cn" }; bool[] sortAscending = { true, false, true }; LdapCompareAttrNames myComparator = new LdapCompareAttrNames( namesToSortBy, sortAscending ); Object[] sortedSpecial = sortedResults.ToArray(); Array.Sort(sortedSpecial, myComparator); // print the re-sorted results Console.WriteLine( "\n" + "*****************************************************\n" + "Search results sorted by sn, uid(Descending), and cn:\n" + "*****************************************************"); for(int j=0; j< sortedSpecial.Length; j++) { PrintEntry( (LdapEntry) sortedSpecial[j] ); } // disconnect with the server conn.Disconnect(); } catch( LdapException e ) { Console.WriteLine( "Error: " + e.ToString() ); } catch( Exception e ) { Console.WriteLine( "Error: " + e.ToString() ); } Environment.Exit(0); }
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() ); } }
public LdapConnectionResult Test(string username, string password) { // Creating an LdapConnection instance var ldapConn = new LdapConnection(); var tempDomainName = new StringBuilder(100); if (!string.IsNullOrEmpty(_settings.DomainName)) { tempDomainName.Append(_settings.DomainName); tempDomainName.Append('\\'); } tempDomainName.Append(username); try { //Connect function will create a socket connection to the server ldapConn.Connect(_settings.Address, _settings.PortNumber); //Bind function will Bind the user object Credentials to the Server ldapConn.Bind(tempDomainName.ToString(), password); } catch (Exception e) { return(new LdapConnectionResult(false, e.Message, "Login")); } // Searches in the Marketing container and return all child entries just below this //container i.e. Single level search var claims = new List <ClaimViewModel>(); try { var cons = ldapConn.SearchConstraints; cons.ReferralFollowing = true; ldapConn.Constraints = cons; var attributes = _settings.Attributes?.Trim() == "" ? null : _settings.Attributes?.Split(",").Select(s => s.Trim()); var lsc = ldapConn.Search(_settings.DistinguishedName, (int)Enum.Parse <SearchScope>(_settings.SearchScope), $"(sAMAccountName={username})", attributes?.ToArray(), false, (LdapSearchConstraints)null); while (lsc.HasMore()) { LdapEntry nextEntry = null; try { nextEntry = lsc.Next(); } catch (LdapException e) { ldapConn.Disconnect(); return(new LdapConnectionResult(false, e.Message, "Search Error")); } var attributeSet = nextEntry.GetAttributeSet(); System.Collections.IEnumerator ienum = attributeSet.GetEnumerator(); while (ienum.MoveNext()) { var attribute = (LdapAttribute)ienum.Current; var attributeName = attribute.Name; var attributeVal = attribute.StringValue; claims.Add(new ClaimViewModel(attributeName, attributeVal)); } } } catch (Exception e) { ldapConn.Disconnect(); return(new LdapConnectionResult(false, e.Message, "Search Error")); } ldapConn.Disconnect(); return(new LdapConnectionResult(true, claims.OrderBy(b => b.Type).ToList())); }
/* * Ldap URL search */ /// <summary> Synchronously perfoms the search specified by the Ldap URL, using /// the specified search constraints (such as the maximum number of /// entries to find or the maximum time to wait for search results). /// /// When this method is called, a new connection is created /// automatically, using the host and port specified in the URL. After /// all search results have been received from the server, the method /// closes the connection (in other words, it disconnects from the Ldap /// server). /// /// As part of the search constraints, a choice can be made as to whether /// to have the results delivered all at once or in smaller batches. If /// the results are to be delivered in smaller batches, each iteration /// blocks only until the next batch of results is returned. /// /// /// </summary> /// <param name="toGet"> Ldap URL specifying the entry to read. /// /// </param> /// <param name="cons"> The constraints specific to the search. /// /// </param> /// <exception> LdapException A general exception which includes an error /// message and an Ldap error code. /// </exception> public static LdapSearchResults Search(LdapUrl toGet, LdapSearchConstraints cons) { LdapConnection lconn = new LdapConnection(); lconn.Connect(toGet.Host, toGet.Port); if (cons == null) { // This is a clone, so we already have our own copy cons = lconn.SearchConstraints; } else { // get our own copy of user's constraints because we modify it cons = (LdapSearchConstraints) cons.Clone(); } cons.BatchSize = 0; // Must wait until all results arrive LdapSearchResults toReturn = lconn.Search(toGet.getDN(), toGet.Scope, toGet.Filter, toGet.AttributeArray, false, cons); lconn.Disconnect(); return toReturn; }