Ejemplo n.º 1
0
        /// <summary>
        /// Finds ldap entry
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="filter">The ADO query filter</param>
        /// <param name="attributes">Properties to load</param>
        /// <returns></returns>
        private LdapEntry ForLdapEntry(string key, string value, string filter, string[] attributes)
        {
            LdapEntry searchResult = null;

            using (LdapConnection conn = new LdapConnection())
            {
                conn.Connect(_config.Host, _config.LDAPPort);
                conn.Bind(_config.LDAPVersion, _config.UserName, _config.Password);

                //Search
                LdapSearchResults results = conn.Search(_config.Container,        //search base
                                                        LdapConnection.SCOPE_SUB, //scope
                                                        filter,                   //filter
                                                        attributes,               //attributes
                                                        false);                   //types only

                while (results.hasMore())
                {
                    try
                    {
                        searchResult = results.next();
                        break;
                    }
                    catch (LdapException e)
                    {
                        throw e;
                    }
                }
            }
            return(searchResult);
        }
Ejemplo n.º 2
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="filter"></param>
        /// <param name="attributes"></param>
        /// <returns></returns>
        private List <LdapEntry> ForLdapEntries(string key, string value, string filter, string[] attributes)
        {
            List <LdapEntry> searchResults = new List <LdapEntry>();

            using (LdapConnection conn = new LdapConnection())
            {
                conn.Connect(_config.Host, _config.LDAPPort);
                conn.Bind(_config.LDAPVersion, _config.UserName, _config.Password);

                LdapSearchResults results = conn.Search(_config.Container,        //search base
                                                        LdapConnection.SCOPE_SUB, //scope
                                                        filter,                   //filter
                                                        attributes,               //attributes
                                                        false);                   //types only

                while (results.hasMore())
                {
                    LdapEntry nextEntry = null;
                    try
                    {
                        nextEntry = results.next();
                        if (nextEntry != null)
                        {
                            searchResults.Add(nextEntry);
                        }
                    }
                    catch (LdapException)
                    {
                        continue;
                    }
                }
            }
            return(searchResults);
        }
Ejemplo n.º 3
0
        public void Ldap_Search_Should_Return_Correct_Results_Count()
        {
            var loginDN  = "dc=example,dc=com";
            var password = "";

            LdapConnection conn = new LdapConnection();

            conn.Connect(Globals.Host, Globals.DefaultPort);
            conn.Bind(loginDN, password);
            LdapSearchResults lsc = conn.Search(
                "dc=example,dc=com",
                LdapConnection.SCOPE_SUB,
                "objectclass=*",
                null,
                false);

            int resultsCount = lsc.Count;
            int counter      = 0;

            while (lsc.hasMore())
            {
                LdapEntry nextEntry = lsc.next();
                ++counter;
            }

            Assert.Equal(resultsCount, counter);

            conn.Disconnect();
        }
Ejemplo n.º 4
0
        public static bool searchGroupEntry(LdapConnection lc, String searchBase, string searchFilter)
        {
            bool status      = true;
            int  searchScope = LdapConnection.SCOPE_SUB;

            String[] attrList          = new String[] { "distinguishedName" };
            LdapSearchConstraints cons = new LdapSearchConstraints();

            cons.TimeLimit = 10000;
            try
            {
                LdapSearchResults searchResults =
                    lc.Search(searchBase,
                              searchScope,
                              searchFilter,
                              attrList,
                              false,
                              cons);                              // time out value

                LdapEntry nextEntry = null;

                if ((nextEntry = searchResults.next()) == null)
                {
                    status = false;
                }
            }
            catch
            {
                status = false;
            }
            return(status);
        }
Ejemplo n.º 5
0
        public static List <LdapEntry> Children(this LdapEntry entry, LdapConnection connection)
        {
            //string filter = "(&(objectclass=user))";
            List <LdapEntry>  entryList = new List <LdapEntry>();
            LdapSearchResults lsc       = connection.Search(entry.DN, LdapConnection.SCOPE_ONE, "objectClass=*", null, false);

            if (lsc == null)
            {
                return(entryList);
            }

            while (lsc.HasMore())
            {
                LdapEntry nextEntry = null;
                try
                {
                    nextEntry = lsc.Next();

                    if (nextEntry.IsUser() || nextEntry.IsOrganizationalUnit())
                    {
                        entryList.Add(nextEntry);
                    }
                }
                catch (LdapException e)
                {
                    continue;
                }
            }
            return(entryList);
        }
Ejemplo n.º 6
0
 /// <summary>
 /// Loads the values of the specified properties into the property cache.
 /// </summary>
 /// <param name="propertyNames">An array of the specified properties.</param>
 private void LoadProperties(PropertyCollection properties, string[] propertyNames)
 {
     _inPropertiesLoading = true;
     try     {
         LdapSearchResults lsc = conn.Search(Fdn, LdapConnection.SCOPE_BASE, "objectClass=*", propertyNames, false);
         if (lsc.hasMore())
         {
             LdapEntry nextEntry            = lsc.next();
             string [] lowcasePropertyNames = null;
             int       length = 0;
             if (propertyNames != null)
             {
                 length = propertyNames.Length;
                 lowcasePropertyNames = new string [length];
                 for (int i = 0; i < length; i++)
                 {
                     lowcasePropertyNames [i] = propertyNames [i].ToLower();
                 }
             }
             foreach (LdapAttribute attribute in nextEntry.getAttributeSet())
             {
                 string attributeName = attribute.Name;
                 if ((propertyNames == null) || (Array.IndexOf(lowcasePropertyNames, attributeName.ToLower()) != -1))
                 {
                     properties [attributeName].Value = null;
                     properties [attributeName].AddRange(attribute.StringValueArray);
                     properties [attributeName].Mbit = false;
                 }
             }
         }
     }
     finally {
         _inPropertiesLoading = false;
     }
 }
Ejemplo n.º 7
0
        public static void Main(String[] args)
        {
            int  LdapPort      = 10389;
            int  searchScope   = LdapConnection.SCOPE_ONE;
            int  LdapVersion   = LdapConnection.Ldap_V3;;
            bool attributeOnly = true;

            String[]       attrs        = { LdapConnection.NO_ATTRS };
            String         ldapHost     = "192.168.2.130";
            String         loginDN      = "";
            String         password     = "";
            String         searchBase   = "";
            String         searchFilter = "";
            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);
        }
Ejemplo n.º 8
0
        public sbyte[] GetLdapInfo(string num, string attr)
        {
            string filter = string.Format("telephoneNumber={0}", num);

            LdapConnection    conn   = GetConnection();
            LdapSearchResults result = conn.Search("dc=renstech,dc=com", LdapConnection.SCOPE_SUB, filter, null, false);

            while (result.hasMore())
            {
                LdapEntry nextEntry;
                try
                {
                    nextEntry = result.next();
                }
                catch (LdapException)
                {
                    continue;
                }

                LdapAttributeSet attributeSet        = nextEntry.getAttributeSet();
                System.Collections.IEnumerator ienum = attributeSet.GetEnumerator();
                while (ienum.MoveNext())
                {
                    LdapAttribute attribute     = (LdapAttribute)ienum.Current;
                    string        attributeName = attribute.Name;
                    if (attributeName == attr)
                    {
                        return(attribute.ByteValue);
                    }
                    //string attributeVal = attribute.StringValue;
                }
            }
            return(null);
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Searches an entry in the Ldap directory and returns the attribute value
        /// </summary>
        /// <param name="attrName">attribute whose value is required</param>
        /// <returns> value of the attribute stored in Ldap directory</returns>
        private string FindAttrValue(string attrName)
        {
            string aValue = null;

            string[] attrs = { attrName };

            LdapSearchResults lsc = conn.Search(Fdn,
                                                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;
                }
                LdapAttribute attribute = nextEntry.getAttribute(attrName);
                aValue = attribute.StringValue;
                break;
            }
            return(aValue);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Find user by name
        /// </summary>
        /// <param name="userName">User name</param>
        /// <returns>LdapEntry object</returns>
        /// <see cref="https://www.novell.com/documentation/developer/ldapcsharp/?page=/documentation/developer/ldapcsharp/cnet/data/bow8dju.html"/>
        public async Task <LdapEntry> FindAsync(string userName)
        {
            Func <LdapConnection, LdapEntry> action = (ldapConn) =>
            {
                // Set search filter
                var searchFilter = $"(cn={userName})";

                // Get search result
                LdapSearchResults searchResults = ldapConn.Search(
                    this.ldapServer.SearchBase,
                    scope: LdapConnection.SCOPE_SUB,
                    filter: searchFilter,                                // Search filter
                    attrs: new string[] { "cn", "displayName", "mail" }, // The attributes to retrieve
                    typesOnly: false);

                // Note in Novell.Directory.Ldap.NETStandard >=3.0.1, LdapSearchResults implement IEnumerable...
                // return searchResults.AsEnumerable().FirstOrDefault();
                while (searchResults.hasMore())
                {
                    var entry = searchResults.next();
                    return(entry);
                }

                return(default(LdapEntry));
            };

            return(await this.ldapActionAsync(action));
        }
Ejemplo n.º 11
0
        private List <LdapUser> GetUsers()
        {
            List <LdapUser> users = new List <LdapUser>();

            //Abrimos Socket contra el server
            LdapConnection ldapConn = new LdapConnection();

            ldapConn.Connect("192.168.123.159", 389);

            //Definimos un filtro Ldap utilizado mas tarde, en este caso solo queremos los objetos tipo usuario
            string filter = "(ObjectClass=inetOrgPerson)";



            //Hacemos la busqueda
            LdapSearchResults query = ldapConn.Search("dc=examen,dc=ies", LdapConnection.SCOPE_SUB, filter, null, false);



            foreach (var element in query)
            {
                LdapUser user = new LdapUser();



                user.DN      = element.DN;
                user.Name    = element.getAttribute("givenName").ToString();
                user.Surname = element.getAttribute("sn").ToString();
                users.Add(user);
            }

            return(users);
        }
Ejemplo n.º 12
0
        public IEnumerator GetEnumerator()
        {
            m_oValues = new ArrayList();
            string[]          attrs = { "objectClass" };
            LdapSearchResults lsc   = Conn.Search(Basedn,
                                                  LdapConnection.SCOPE_ONE,
                                                  "objectClass=*",
                                                  attrs,
                                                  false);

            LdapUrl Burl = new LdapUrl(_Bpath);
            string  host = Burl.Host;
            int     port = Burl.Port;

            while (lsc.hasMore())
            {
                LdapEntry nextEntry = null;
                try                                     {
                    nextEntry = lsc.next();
                }
                catch (LdapException e)          {
                    // Exception is thrown, go for next entry
                    continue;
                }
                DirectoryEntry dEntry = new DirectoryEntry(Conn);
                string         eFdn   = nextEntry.DN;
                LdapUrl        curl   = new LdapUrl(host, port, eFdn);
                dEntry.Path = curl.ToString();
                m_oValues.Add((DirectoryEntry)dEntry);
            }
            return(m_oValues.GetEnumerator());
        }
Ejemplo n.º 13
0
        ADInfo Search(LdapConnection ldapConn)
        {
            LdapSearchConstraints constraints = new LdapSearchConstraints
            {
                TimeLimit = 10000
            };

            LdapSearchResults lsc = ldapConn.Search(
                SearchBase,
                LdapConnection.SCOPE_SUB,
                "SAMAccountName=" + Username.ToLower(),
                null,  // no specified attributes
                false, // return attr and value
                constraints);

            while (lsc.hasMore())
            {
                LdapEntry nextEntry = null;
                try
                {
                    nextEntry = lsc.next();
                    return(new ADInfo(Username, nextEntry));
                }
                catch (LdapException e)
                {
                    Console.WriteLine("Error: " + e.LdapErrorMessage);
                    // Exception is thrown, go for next entry
                    continue;
                }
            }
            return(null);
        }
Ejemplo n.º 14
0
        public void userList()
        {
            string LDAP_server  = "localhost";
            int    ldapPort     = 1920;
            string loginON      = "uid=admin,ou=system";
            string password     = "******";
            string searchBase   = "ou=user,o=Company";
            string searchFilter = "ObjectClass=UserLogin,Password,Name,TelNo,Email";

            try
            {
                LdapConnection conn = new LdapConnection();
                Console.WriteLine("Connecting to " + LDAP_server);
                conn.Connect(LDAP_server, ldapPort);
                conn.Bind(loginON, password);
                string[]          requiredAttri = { "cn", "sn", "uid" };
                LdapSearchResults result        = conn.Search(searchBase,
                                                              LdapConnection.SCOPE_SUB,
                                                              searchFilter,
                                                              requiredAttri,
                                                              false);
                while (result.hasMore())
                {
                    LdapEntry nextEntry = null;
                    try
                    {
                        nextEntry = result.next();
                    }
                    catch (LdapException ex)
                    {
                        Console.WriteLine("LDAPconnection error:" + ex.LdapErrorMessage);
                        continue;
                    }
                    Console.WriteLine("\n" + nextEntry.DN);
                    LdapAttributeSet ldapattri           = nextEntry.getAttributeSet();
                    System.Collections.IEnumerator ienum = ldapattri.GetEnumerator();
                    while (ienum.MoveNext())
                    {
                        LdapAttribute attri     = (LdapAttribute)ienum.Current;
                        string        attriName = attri.Name;
                        string        attriVal  = attri.StringValue;
                        Console.WriteLine("\t" + attriName + "\tValue = \t" + attriVal);
                    }
                }
                conn.Disconnect();
            }
            catch (LdapException ex)
            {
                Console.WriteLine("LDAPconnection error:" + ex.LdapErrorMessage);
                return;
            }
            catch (Exception ex)
            {
                Console.WriteLine("LDAPconnection error:" + ex.Message);
                return;
            }
        }
        private List <LdapEntry> Search(string login, string password, string server, int portNumber, bool startTls,
                                        int scope, string searchFilter = null, string disnguishedName = null, string[] attributes = null)
        {
            if (server.StartsWith("LDAP://"))
            {
                server = server.Substring("LDAP://".Length);
            }
            var entries        = new List <LdapEntry>();
            var ldapConnection = new LdapConnection();

            if (startTls)
            {
                ldapConnection.UserDefinedServerCertValidationDelegate += TlsHandler;
            }
            ldapConnection.Connect(server, portNumber);
            if (startTls)
            {
                // does not call stopTLS because it does not work
                ldapConnection.startTLS();
            }
            ldapConnection.Bind(LdapConnection.Ldap_V3, login, password);
            if (startTls)
            {
                string errorMessage = ServerCertValidate();
                if (!String.IsNullOrEmpty(errorMessage))
                {
                    ldapConnection.Disconnect();
                    throw new Exception(errorMessage);
                }
            }
            if (searchFilter == null)
            {
                ldapConnection.Disconnect();
                return(null);
            }
            LdapSearchResults ldapSearchResults =
                ldapConnection.Search(disnguishedName, scope, searchFilter, attributes, false);

            while (ldapSearchResults.hasMore())
            {
                LdapEntry nextEntry = null;
                try
                {
                    nextEntry = ldapSearchResults.next();
                }
                catch (LdapException)
                {
                    continue;
                }
                if (nextEntry != null)
                {
                    entries.Add(nextEntry);
                }
            }
            ldapConnection.Disconnect();
            return(entries);
        }
Ejemplo n.º 16
0
        public ActionResult <HashSet <object> > GetUsersWithActiveDirectory([FromBody] SampekeyUserAccountRequest value)
        {
            var users = new HashSet <object>();

            try
            {
                using (var connection = new LdapConnection {
                    SecureSocketLayer = false
                })
                {
                    var _domain       = Environment.GetEnvironmentVariable("AD_DDOMAIN");
                    var _domainServer = Environment.GetEnvironmentVariable("AD_DDOMAIN_SSERVER");
                    var _port         = Environment.GetEnvironmentVariable("AD_PORT");

                    connection.Connect(_domainServer, int.Parse(_port));
                    connection.Bind($"{value.UserName}@{_domain}", value.Password);

                    LdapSearchResults searchResults = connection.Search(
                        Environment.GetEnvironmentVariable("BIND_DN"),
                        LdapConnection.SCOPE_SUB,
                        Environment.GetEnvironmentVariable("LDAP_FILTER"),
                        null,
                        false
                        );

                    while (searchResults.hasMore())
                    {
                        LdapEntry nextEntry = null;
                        nextEntry = searchResults.next();
                        nextEntry.getAttributeSet();
                        var attr = nextEntry.getAttribute("mail");
                        if (attr == null)
                        {
                            users.Add(nextEntry.getAttribute("distinguishedName").StringValue);
                        }
                        else
                        {
                            users.Add(new{
                                Email    = nextEntry.getAttribute("mail").StringValue,
                                UserName = nextEntry.getAttribute("sAMAccountName").StringValue
                            });
                        }
                    }
                    return(users);
                }
            }
            catch
            {
                return(users);
            }

            /*
             * HashSet<string> data = account.GetUsersWithActiveDirectory(value);
             * return Ok(data);
             */
        }
Ejemplo n.º 17
0
        static void DoSearch(string ldapHost, int ldapPort, string loginDN, string password, string searchBase, string searchFilter)
        {
            try
            {
                LdapConnection conn = new LdapConnection();
                Console.WriteLine("Connecting to:" + ldapHost);
                conn.Connect(ldapHost, ldapPort);
                conn.Bind(loginDN, password);
                LdapSearchResults lsc = conn.Search(searchBase,
                                                    LdapConnection.SCOPE_SUB,
                                                    searchFilter,
                                                    null,
                                                    false);

                while (lsc.hasMore())
                {
                    LdapEntry nextEntry = null;
                    try
                    {
                        nextEntry = lsc.next();
                    }
                    catch (LdapException e)
                    {
                        Console.WriteLine("Error: " + e.LdapErrorMessage);
                        // Exception is thrown, go for next entry
                        continue;
                    }
                    Console.WriteLine("\n" + nextEntry.DN);
                    LdapAttributeSet attributeSet        = nextEntry.getAttributeSet();
                    System.Collections.IEnumerator ienum = attributeSet.GetEnumerator();
                    while (ienum.MoveNext())
                    {
                        LdapAttribute attribute     = (LdapAttribute)ienum.Current;
                        string        attributeName = attribute.Name;
                        string        attributeVal  = attribute.StringValue;
                        if (!Base64.isLDIFSafe(attributeVal))
                        {
                            byte[] tbyte = SupportClass.ToByteArray(attributeVal);
                            attributeVal = Base64.encode(SupportClass.ToSByteArray(tbyte));
                        }
                        Console.WriteLine(attributeName + "value:" + attributeVal);
                    }
                }
                conn.Disconnect();
            }
            catch (LdapException e)
            {
                Console.WriteLine("Error:" + e.LdapErrorMessage);
                return;
            }
            catch (Exception e)
            {
                Console.WriteLine("Error:" + e.Message);
                return;
            }
        }
Ejemplo n.º 18
0
        /// <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);
        }
Ejemplo n.º 19
0
        public static string Credenciales(string usuario, string contraseña)
        {
            string[] prueba = new string[20];
            string   acceso = "";

            try
            {
                string email = null;
                string rol   = null;
                if (usuario != "u00000000" && usuario != "u12345678")
                {
                    string         ldapHost = "ldap.uca.es";
                    int            ldapPort = 389;
                    string         loginDN  = "CN=" + usuario + ",dc=uca,dc=es";
                    LdapConnection conn     = new LdapConnection();
                    conn.Connect(ldapHost, ldapPort);
                    conn.Bind(loginDN, contraseña);
                    if (conn.Bound)
                    {
                        string searchBase   = "CN=" + usuario + ",dc=uca,dc=es";
                        string searchFilter = "tipodocumento=NIF";

                        LdapSearchResults lsc       = conn.Search(searchBase, LdapConnection.SCOPE_BASE, searchFilter, null, false);
                        LdapEntry         nextEntry = lsc.next();
                        email = nextEntry.getAttribute("mail").StringValue;
                        rol   = nextEntry.getAttribute("ou").StringValue;
                    }
                }
                else
                {
                    email = "*****@*****.**";
                    rol   = "PDI";
                }
                prueba = Insertar(7, usuario, null, null, null, null, null, null, null, null);
                acceso = prueba[0];
                if (acceso == "0")
                {
                    Insertar(10, usuario, email, rol, null, null, null, null, null, null);
                }
                if (acceso == "1")
                {
                    acceso = "2";
                }
                if (acceso == "0")
                {
                    acceso = "1";
                }
            }
            catch (LdapException e)
            {
                Console.WriteLine(e);
            }

            return(acceso);
        }
Ejemplo n.º 20
0
        public List <LdapEntry> ExecuteSearch(string searchBase, string filter = "")
        {
            var results = new List <LdapEntry>();

            var lcm  = LdapConnectionManager.Instance;
            var conn = lcm.GetConnection();
            var sb   = searchBase + config.searchBase;

            LdapControl[] requestControls = new LdapControl[1];

            LdapSortKey[] keys = new LdapSortKey[1];
            keys[0] = new LdapSortKey("cn"); //samaccountname
            // Create the sort control
            requestControls[0] = new LdapSortControl(keys, true);

            // Set the controls to be sent as part of search request
            LdapSearchConstraints cons = conn.SearchConstraints;

            cons.SetControls(requestControls);
            conn.Constraints = cons;

            LdapSearchResults resps = (LdapSearchResults)conn.Search(sb, LdapConnection.ScopeSub, filter, null, false, (LdapSearchConstraints)null);

            //var resps = SendSearch(searchBase, type, filter);

            while (resps.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 = resps.Next();
                    results.Add(nextEntry);
                }
                catch (Exception e)
                {
                    if (e is LdapReferralException)
                    {
                        continue;
                    }
                    else
                    {
                        logger.Error("Search stopped with exception " + e.ToString());
                        break;
                    }
                }

                /* Print out the returned Entries distinguished name.  */
                logger.Debug(nextEntry.Dn);
            }

            return(results);
        }
Ejemplo n.º 21
0
        public AuthenticationResult AuthenticateUser(Credentials userInfo)
        {
            AuthenticationResult result = new AuthenticationResult();

            try
            {
                LdapConnection conn = new LdapConnection();
                conn.Connect(_LDAPConnectionInfo.Host, _LDAPConnectionInfo.Port);
                conn.Bind(userInfo.Username, userInfo.Password);
                string profileName = null;
                try
                {
                    LdapSearchResults lsc = conn.Search(string.Empty, LdapConnection.SCOPE_SUB, "cn = " + userInfo.Username, null, false);
                    while (lsc.hasMore())
                    {
                        LdapEntry nextEntry = null;
                        try
                        {
                            nextEntry = lsc.next();
                        }
                        catch (LdapException)
                        {
                            continue;
                        }

                        LdapAttributeSet attributeSet = nextEntry.getAttributeSet();
                        LdapAttribute    attribute    = attributeSet.Cast <LdapAttribute>().Where(att => att.Name.Trim().ToUpper() == "PROFILE_NAME").SingleOrDefault();
                        if (attribute != null)
                        {
                            profileName = attribute.StringValue;
                        }
                        break;
                    }
                }
                catch { }
                conn.Disconnect();
                result.IsSuccess        = true;
                result.UserProfile      = new UserProfile();
                result.UserProfile.Name = (profileName == null ? userInfo.Username : profileName);
            }
            catch (LdapException ex)
            {
                _logger.LogCritical(EventIds.AuthenticateUser, ex, nameof(LdapException));
                result.ErrorMessage = ex.Message;
                result.IsSuccess    = false;
            }
            catch (Exception ex)
            {
                _logger.LogCritical(EventIds.AuthenticateUser, ex, nameof(Exception));
                result.ErrorMessage  = ex.Message;
                result.IsServerError = true;
                result.IsSuccess     = false;
            }
            return(result);
        }
Ejemplo n.º 22
0
        /// <summary>
        /// The implementation of the interface ICertificateLookups function.
        ///
        /// It takes the subject string and queries the ldap server for a certificate
        /// that satifies the condition in the subject string.
        ///
        /// Also implements a certificate cache, which removes unused certificates after 14 days.
        /// </summary>
        /// <param name="subject">The subject string of an OCES certificate.</param>
        /// <returns>The certificate that satifies the conditions of the subject string.</returns>
        public X509Certificate2 GetCertificate(CertificateSubject subject)
        {
            if (subject == null)
            {
                throw new ArgumentNullException("subject");
            }

            X509Certificate2 certificateToBeReturned;

            if (!certiticateCache.TryGetValue(subject, out certificateToBeReturned))
            {
                LdapConnection ldapConnection = null;
                try
                {
                    ldapConnection = ConnectToServer();
                    LdapSearchResults results = Search(ldapConnection, subject);
                    certificateToBeReturned = GetCertificate(results, subject);
                }
                finally
                {
                    if (ldapConnection != null)
                    {
                        ldapConnection.Disconnect();
                    }
                }

                // Check the certificate
                //   Check for activation date and expire date
                //   Check the certificate chain
                CertificateValidator.ValidateCertificate(certificateToBeReturned);

                // everything is okay, add it to the cache
                this.certiticateCache.Set(subject, certificateToBeReturned);
            }
            else
            {
                // certificate found in cache
                // check it is not expired
                try
                {
                    CertificateValidator.ValidateCertificate(certificateToBeReturned);
                }
                catch
                {
                    // if any error is thrown, move the certificate from the cache
                    this.certiticateCache.Remove(subject);

                    // throw the original error
                    throw;
                }
            }

            return(certificateToBeReturned);
        }
Ejemplo n.º 23
0
        public LdapAuthenticationResult AuthenticateUser(string userName, string password)
        {
            using (var cn = new LdapConnection())
            {
                cn.Connect(_options.Host, 389);
                try
                {
                    cn.Bind($"{_options.Dn}\\" + userName, password);
                }
                catch
                {
                    return(LdapAuthenticationResult.Fail("USERANDPASSWORDDOESNTMATCH",
                                                         "User and password doesn't match"));
                }

                var searchFilter      = string.Format(_options.SearchFilter, userName);
                LdapSearchResults lsc = cn.Search(_options.Base,
                                                  LdapConnection.SCOPE_SUB,
                                                  searchFilter,
                                                  null,
                                                  false);

                var entry = lsc.Next();
                if (entry == null)
                {
                    return(LdapAuthenticationResult.Fail("ENTRYNOTFOUND", "Entry not found"));
                }
                try
                {
                    var sub = entry.getAttribute(_options.SubjectAttr)?.StringValue;
                    if (string.IsNullOrEmpty(sub))
                    {
                        return(LdapAuthenticationResult.Fail("SUBNOTFOUND", "The user has not a subject"));
                    }
                    else
                    {
                        var claims = new List <Claim>();
                        claims.Add(new Claim(JwtClaimTypes.Subject, sub));
                        claims.Add(new Claim("ldap_accountname", userName));
                        claims.Add(new Claim(ClaimTypes.NameIdentifier, sub));
                        var identity = new ClaimsIdentity(claims, "LDAP");
                        identity.AddClaims(claims);
                        var principal = new ClaimsPrincipal(identity);
                        return(LdapAuthenticationResult.Success(principal));
                    }
                }
                catch
                {
                    return(LdapAuthenticationResult.Fail("ERROR", "En error occured"));
                }
            }
        }
Ejemplo n.º 24
0
        private void ExecuteSearch(LdapFilter filter, LdapConnection ldapConnection, Action <LdapSearchResults> middleAction)
        {
            LdapSearchConstraints constraints = ldapConnection.SearchConstraints;

            SetLdapControls(filter, constraints);

            LdapSearchResults searchResults = ldapConnection.Search(
                filter.SearchPath, LdapConnection.SCOPE_SUB,
                filter.SearchCriteria, null, false, constraints);

            middleAction(searchResults);
            TotalResultsCallback(filter, searchResults);
        }
Ejemplo n.º 25
0
        public IActionResult GetUsersLdap()
        {
            //Listas que utilizare para almacenar los usuarios de Ldap y sus respectivos atributos
            List <String> ldapusers = new List <String>();
            List <String> atributos = new List <String>();



            //Abrimos Socket contra el server
            LdapConnection ldapConn = new LdapConnection();

            ldapConn.Connect("192.168.1.102", 389);

            //Definimos un filtro Ldap utilizado mas tarde, en este caso solo queremos los objetos tipo usuario
            string filter = "(ObjectClass=inetOrgPerson)";


            try{
                //Hacemos la busqueda
                LdapSearchResults query = ldapConn.Search("dc=fran,dc=local", LdapConnection.SCOPE_SUB, filter, null, false);


                //Recorremos la colecion de objetos Ldap
                while (query.hasMore())
                {
                    try {
                        //Obtenemos el usuario iterado y obtenemos su DN y los metemos en la lista, hacemos lo mismo con
                        //TODOS sus atributos(Por comodidad he hecho un toString)
                        //En vez de recorrorerlos 1 a 1.

                        LdapEntry nextEntry = query.next();
                        ldapusers.Add(nextEntry.DN);
                        atributos.Add(nextEntry.getAttributeSet().ToString());
                    }catch (LdapException e) {
                        //Si hubiera algun fallo el la obtencion del usuario iterado lo logeo y continuo
                        Console.WriteLine("Error Entry: " + e.LdapErrorMessage);
                    }
                }
            }catch (LdapException e) {
                //Si la busqueda ha fallado lo logueo y lanzo una excepcion para parar la app
                Console.WriteLine("Error Filtro: " + e.LdapErrorMessage);
                throw;
            }

            //Cargo las dos listas en la array dinamica de la vista

            ViewBag.ldapusers = ldapusers;
            ViewBag.atributos = atributos;
            return(View());
        }
Ejemplo n.º 26
0
        private bool checkAccess(string dnPerfil, string user, string password, LdapConnection ldap)
        {
            try
            {
                if (usuarioLdap.autenticado == false)
                {
                    LdapSearchResults search    = ldap.Search(dnPerfil, LdapConnection.SCOPE_SUB, null, null, false);
                    LdapEntry         entry     = search.next();
                    LdapAttributeSet  attribute = entry.getAttributeSet();
                    LdapAttribute     attrib    = attribute.getAttribute("uniquemember");

                    //if (attrib != null)
                    //{
                    //    usuarioLdap.autenticado = Array.Exists(attrib.StringValueArray, element => element.Contains(user.ToLower()));
                    //    if (usuarioLdap.autenticado)
                    //        usuarioLdap.perfil = attribute.getAttribute("cn").StringValue;
                    //    return usuarioLdap.autenticado;
                    //}

                    foreach (string usuario in attrib.StringValueArray)
                    {
                        if (usuario.Substring(3).Split(',').First().Equals(user))
                        {
                            ldap.Bind(usuario, password);

                            LdapSearchResults searchu    = ldap.Search("cn=users,dc=network,dc=ctbc", LdapConnection.SCOPE_SUB, "uid=" + user, null, false);
                            LdapEntry         entryu     = searchu.next();
                            LdapAttributeSet  attributeu = entryu.getAttributeSet();

                            usuarioLdap.CPF             = attributeu.getAttribute("CPF").StringValue;
                            usuarioLdap.nomeAssociado   = attributeu.getAttribute("DISPLAYNAME").StringValue;
                            usuarioLdap.centroResultado = attributeu.getAttribute("DEPARTMENTNUMBER").StringValue;
                            usuarioLdap.email           = attributeu.getAttribute("MAIL").StringValue;
                            usuarioLdap.tipo_usuario    = attributeu.getAttribute("TIPOUSUARIO").StringValue;
                            usuarioLdap.usuario         = attributeu.getAttribute("CN").StringValue.ToLower();

                            usuarioLdap.perfil      = attribute.getAttribute("cn").StringValue;
                            usuarioLdap.autenticado = true;
                            return(true);
                        }
                    }
                }
            }
            catch (LdapException)
            {
                throw new Exception("Usuário ou Senha Incorreta!");
            }

            return(false);
        }
        /// <summary>
        /// Checks whether the entry with the specified Relative distinguised name
        /// exists or not.
        /// </summary>
        /// <param name="rdn"> Relative distinguished name of the entry</param>
        /// <returns>DirectoryEntry object of Entry if entry exists,
        /// Null if entry doesn't exist </returns>
        private DirectoryEntry CheckEntry(string rdn)
        {
            string         Ofdn   = null;
            DirectoryEntry cEntry = null;

            Ofdn = rdn + "," + Basedn;
            string[] attrs = { "objectClass" };
            try
            {
                LdapSearchResults lsc = Conn.Search(Ofdn,
                                                    LdapConnection.SCOPE_BASE,
                                                    "objectClass=*",
                                                    attrs,
                                                    false);
                while (lsc.hasMore())
                {
                    LdapEntry nextEntry = null;
                    try
                    {
                        nextEntry = lsc.next();
                        cEntry    = new DirectoryEntry(Conn);
                        LdapUrl Burl = new LdapUrl(_Bpath);
                        LdapUrl curl = new LdapUrl(Burl.Host, Burl.Port, Ofdn);
                        cEntry.Path = curl.ToString();
                    }
                    catch (LdapException e)
                    {
                        // Exception is thrown, go for next entry
                        throw e;
                    }
                    break;
                }
            }
            catch (LdapException le)
            {
                if (le.ResultCode == LdapException.NO_SUCH_OBJECT)
                {
                    return(null);
                }
                else
                {
                    throw le;
                }
            }
            catch (Exception e)
            {
                throw e;
            }
            return(cEntry);
        }
Ejemplo n.º 28
0
        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);
        }
 private static int?GetTotalCount(LdapSearchResults results)
 {
     if (results.ResponseControls != null)
     {
         var r = (from c in results.ResponseControls
                  let d = c as LdapVirtualListResponse
                          where (d != null)
                          select(LdapVirtualListResponse) c).SingleOrDefault();
         if (r != null)
         {
             return(r.ContentCount);
         }
     }
     return(null);
 }
Ejemplo n.º 30
0
        /// <summary>
        /// Search in AD for non-eRSA accounts created after a given date
        /// Only display selected attributes defined in _essentialProperties
        /// </summary>
        /// <param name="earliest"></param>
        public List <Dictionary <string, string> > Search(DateTime earliest)
        {
            string whenCreated = earliest.ToUniversalTime().ToString("yyyyMMddHHmmss.0Z");

            Console.WriteLine("Local {0} to UTC {1}", earliest, whenCreated);

            string userFilter = HELPER.CreateFilter(whenCreated);

            List <Dictionary <string, string> > results = new List <Dictionary <string, string> >();
            LdapSearchResults lsc = conn.Search(HELPER.SEARCH_BASE,
                                                LdapConnection.SCOPE_SUB,
                                                userFilter,
                                                HELPER.CREATION_PROPERTIES,
                                                false);

            int count = 0;

            while (lsc.hasMore())
            {
                LdapEntry nextEntry = null;
                try
                {
                    nextEntry = lsc.next();
                    count++;
                }
                catch (LdapReferralException) {
                    // Nothing really serious: constraints.ReferralFollowing = true this may not be needed
                    // https://www.novell.com/documentation/developer/ldapcsharp/?page=/documentation/developer/ldapcsharp/cnet/data/b3u4u0n.html
                    // https://technet.microsoft.com/en-us/library/cc978014.aspx
                    continue;
                }
                catch (LdapException e)
                {
                    Console.WriteLine("Move next error: {0}", e.ToString());
                    Console.WriteLine("Error message: " + e.Message);
                    continue;
                }
                Console.WriteLine("\n" + nextEntry.DN);
                try {
                    results.Add(GetProperties(nextEntry.getAttributeSet()));
                } catch (NullReferenceException ex)
                {
                    Console.WriteLine("Not a qualified person account");
                    Console.WriteLine(ex.Message);
                }
            }
            return(results);
        }