Ejemplo n.º 1
0
        public static Task <bool> ModifyAsync(string oldUsername, string username, string password, string nombre, string apellido, string email)
        {
            CancellationTokenSource cts = new CancellationTokenSource();
            CancellationToken       cancellationToken = cts.Token;

            LdapConnection conn = null;


            return(Task.Factory.StartNew(() => {
                conn = new LdapConnection();
                conn.Connect(Host, Port);

                if (!string.IsNullOrEmpty(username))
                {
                    try
                    {
                        conn.Bind(dn, pa);
                    }
                    catch (Exception e)
                    {
                        conn.Disconnect();
                        return false;
                    }

                    string searchBase = filter;

                    int searchScope = LdapConnection.ScopeSub;
                    string searchFilter = "uid=" + username.Trim();
                    LdapSearchQueue queue = conn.Search(searchBase,
                                                        searchScope,
                                                        searchFilter,
                                                        null,
                                                        false,
                                                        (LdapSearchQueue)null,
                                                        (LdapSearchConstraints)null);

                    LdapMessage message;
                    while ((message = queue.GetResponse()) != null)
                    {
                        try
                        {
                            string msg = message.ToString();

                            LdapEntry entry = ((LdapSearchResult)message).Entry;

                            LdapAttributeSet attributeSet = entry.GetAttributeSet();
                            System.Collections.IEnumerator ienum = attributeSet.GetEnumerator();

                            LdapAttribute cn = attributeSet.GetAttribute("cn");
                            string idUser = cn.StringValue;

                            try
                            {
                                conn.Delete("cn=" + idUser + "," + filter);


                                LdapAttributeSet ldapAttributeSet = new LdapAttributeSet();
                                ldapAttributeSet.Add(new LdapAttribute("cn", nombre + " " + apellido));
                                ldapAttributeSet.Add(new LdapAttribute("sn", nombre));
                                ldapAttributeSet.Add(new LdapAttribute("homeDirectory", "/home/users/" + username));
                                ldapAttributeSet.Add(new LdapAttribute("objectClass", new string[] { "inetOrgPerson", "posixAccount", "top" }));
                                ldapAttributeSet.Add(new LdapAttribute("uid", username));
                                ldapAttributeSet.Add(new LdapAttribute("givenName", nombre));
                                ldapAttributeSet.Add(new LdapAttribute("uidNumber", "1000"));
                                ldapAttributeSet.Add(new LdapAttribute("gidNumber", "500"));
                                ldapAttributeSet.Add(new LdapAttribute("mail", email));
                                ldapAttributeSet.Add(new LdapAttribute("userPassword", password));

                                LdapEntry ldapEntry = new LdapEntry("cn=" + nombre + " " + apellido + "," + filter, ldapAttributeSet);

                                conn.Add(ldapEntry);
                            }
                            catch (Exception e)
                            {
                                conn.Disconnect();
                                return false;
                            }

                            conn.Disconnect();
                            return true;
                        }
                        catch (Exception e)
                        {
                            conn.Disconnect();
                            return false;
                        }
                    }
                }

                return false;
            }, cancellationToken));
        }
Ejemplo n.º 2
0
        /// <summary>
        /// For this entry, get all the ldap attributes such as Names, group property and home server
        /// </summary>
        /// <param name="conn">ldap connection</param>
        /// <param name="entry">entry for this user/member</param>
        /// <param name="group">group</param>
        /// <param name="groupList">list of groups</param>
        private void ProcessUserEntry(LdapConnection conn, LdapEntry entry, string group, string groupList)
        {
            log.Debug("ProcessUserEntry(" + entry.DN + ")");

            string commonName        = String.Empty;
            string firstName         = null;
            string lastName          = null;
            string fullName          = null;
            string distinguishedName = String.Empty;
            string ldapGuid          = null;
            bool   Group             = false;
            string groupmembers      = "";
            string groupmembership   = "";
            string iFolderHomeServer = "";


            char[]        dnDelimiters  = { ',', '=' };
            LdapAttribute timeStampAttr = null;

            bool   attrError       = false;
            string FullNameDisplay = "";

            store = Store.GetStore();
            Domain domain = store.GetDomain(store.DefaultDomain);

            if (domain != null)
            {
                FullNameDisplay = domain.UsersFullNameDisplay;
            }

            try
            {
                // get the last update time
                timeStampAttr = entry.getAttribute("modifytimestamp");

                ldapGuid          = GetLdapGuid(entry);
                distinguishedName = entry.DN;

                // retrieve from configuration the directory attribute configured
                // for naming in Simias.
                LdapAttribute cAttr =
                    entry.getAttribute(ldapSettings.NamingAttribute);
                if (cAttr != null && cAttr.StringValue.Length != 0)
                {
                    commonName = cAttr.StringValue;
                }
                else
                if (ldapSettings.NamingAttribute.ToLower() == LdapSettings.DefaultNamingAttribute.ToLower())
                {
                    // If the naming attribute is default (cn) then we want to continue
                    // to work the way we previously did so we don't break any existing installs.
                    //
                    // If the distinguishing attribute did not exist,
                    // then make the Simias username the first component
                    // of the ldap DN.
                    string[] components = entry.DN.Split(dnDelimiters);
                    commonName = components[1];
                }

                LdapAttribute givenAttr = entry.getAttribute("givenName");
                if (givenAttr != null && givenAttr.StringValue.Length != 0)
                {
                    firstName = givenAttr.StringValue as string;
                }

                LdapAttribute sirAttr = entry.getAttribute("sn");
                if (sirAttr != null && sirAttr.StringValue.Length != 0)
                {
                    lastName = sirAttr.StringValue as string;
                }

                if (firstName != null && lastName != null)
                {
                    if (FullNameDisplay == "FirstNameLastName")
                    {
                        fullName = firstName + " " + lastName;
                    }
                    else
                    {
                        fullName = lastName + " " + firstName;
                    }
                }
                else
                {
                    fullName = commonName;
                }


                LdapAttribute objectAttr = entry.getAttribute("objectclass");
                String[]      values     = objectAttr.StringValueArray;
                if (IsGroup(values) == true)
                {
                    Group = true;
                }

                LdapAttribute iFolderHomeAttr = entry.getAttribute("iFolderHomeServer");
                if (iFolderHomeAttr != null && iFolderHomeAttr.StringValue.Length != 0)
                {
                    iFolderHomeServer = iFolderHomeAttr.StringValue as string;
                }

                if (Group == true)
                {
                    if (isGropuAlreadyprocessed(groupList, distinguishedName) == true)
                    {
                        return;
                    }
                    LdapAttributeSet attributeSet        = entry.getAttributeSet();
                    System.Collections.IEnumerator ienum = attributeSet.GetEnumerator();
                    while (ienum.MoveNext())
                    {
                        LdapAttribute attribute                 = (LdapAttribute)ienum.Current;
                        string        attributeName             = attribute.Name;
                        System.Collections.IEnumerator enumVals = attribute.StringValues;
                        if (attributeName.ToLower() == "member" ||
                            attributeName.ToLower() == "uniquemember")
                        {
                            while (enumVals.MoveNext())
                            {
                                if (isGropuAlreadyprocessed(groupList, (System.String)enumVals.Current) == false)
                                {
                                    groupmembers += (System.String)enumVals.Current;
                                    groupmembers += ";";
                                }
                            }
                        }
                    }
                    groupList += distinguishedName;
                    groupList += ";";
                    ProcessSearchGroup(conn, groupmembers, distinguishedName, groupList);
                }
                if (group != null && group != String.Empty)
                {
                    groupmembership  = group;
                    groupmembership += ";";
                }
            }
            catch (Exception gEx)
            {
                log.Error(gEx.Message);
                log.Error(gEx.StackTrace);

                state.ReportError(gEx.Message);
                attrError = true;
            }

            // No exception were generated gathering member info
            // so call the sync engine to process this member
            if (attrError == false)
            {
                if (timeStampAttr != null && timeStampAttr.StringValue.Length != 0)
                {
                    Property ts = new Property("LdapTimeStamp", timeStampAttr.StringValue);
                    ts.LocalProperty = true;
                    Property[] propertyList = { ts };

                    state.ProcessMember(
                        null,
                        commonName,
                        firstName,
                        lastName,
                        fullName,
                        distinguishedName,
                        propertyList,
                        Group,
                        groupmembers,
                        groupmembership,
                        iFolderHomeServer);
                }
                else
                {
                    state.ProcessMember(
                        null,
                        commonName,
                        firstName,
                        lastName,
                        fullName,
                        distinguishedName,
                        null,
                        Group,
                        groupmembers,
                        groupmembership,
                        iFolderHomeServer);
                }
            }
        }
        public static void Run(string[] args)
        {
            if (args.Length != 6)
            {
                Usage();
                return;
            }

            string ldapHost     = args[0];
            int    ldapPort     = Convert.ToInt32(args[1]);
            String loginDN      = args[2];
            String password     = args[3];
            String searchBase   = args[4];
            String searchFilter = args[5];

            try
            {
                using (LdapConnection conn = new LdapConnection())
                {
                    Console.WriteLine("Connecting to:" + ldapHost);
                    conn.Connect(ldapHost, ldapPort);
                    conn.Bind(loginDN, password);
                    LdapSearchResults lsc = conn.Search(searchBase, LdapConnection.SCOPE_SUB, searchFilter, null, false);

                    while (lsc.hasMore())
                    {
                        LdapEntry nextEntry = null;

                        try
                        {
                            nextEntry = lsc.next();
                        }
                        catch (LdapException ex)
                        {
                            Printer.Error(ex.ToString());
                            // Exception is thrown, go for next entry
                            continue;
                        }

                        Console.WriteLine("--------------------------------------------------------------------------------");
                        Console.WriteLine(nextEntry.DN);
                        Console.WriteLine("--------------------------------------------------------------------------------");

                        LdapAttributeSet attributeSet = nextEntry.getAttributeSet();

                        IEnumerator ienum = attributeSet.GetEnumerator();

                        while (ienum.MoveNext())
                        {
                            LdapAttribute attribute     = (LdapAttribute)ienum.Current;
                            string        attributeName = attribute.Name;
                            string        attributeVal  = attribute.StringValue;

                            if (!Base64.isLDIFSafe(attributeVal))
                            {
                                byte[] tbyte = SupportClass.ToByteArray(attributeVal);
                                attributeVal = Base64.encode(SupportClass.ToSByteArray(tbyte));
                            }

                            Printer.PrintAttribute(attributeName, attributeVal);
                        }
                    }
                }
            }
            catch (LdapException ex)
            {
                Printer.Error(ex.ToString());
                return;
            }
            catch (Exception ex)
            {
                Printer.Error(ex.ToString());
                return;
            }
        }
Ejemplo n.º 4
0
        private void CommitEntry()
        {
            PropertyCollection properties = GetProperties(false);

            if (!Nflag)
            {
                System.Collections.ArrayList modList = new System.Collections.ArrayList();
                foreach (string attribute in properties.PropertyNames)
                {
                    LdapAttribute attr = null;
                    if (properties [attribute].Mbit)
                    {
                        switch (properties [attribute].Count)
                        {
                        case 0:
                            attr = new LdapAttribute(attribute, new string [0]);
                            modList.Add(new LdapModification(LdapModification.DELETE, attr));
                            break;

                        case 1:
                            string val = (string)properties [attribute].Value;
                            attr = new LdapAttribute(attribute, val);
                            modList.Add(new LdapModification(LdapModification.REPLACE, attr));
                            break;

                        default:
                            object [] vals     = (object [])properties [attribute].Value;
                            string [] aStrVals = new string [properties [attribute].Count];
                            Array.Copy(vals, 0, aStrVals, 0, properties [attribute].Count);
                            attr = new LdapAttribute(attribute, aStrVals);
                            modList.Add(new LdapModification(LdapModification.REPLACE, attr));
                            break;
                        }
                        properties [attribute].Mbit = false;
                    }
                }
                if (modList.Count > 0)
                {
                    LdapModification[] mods = new LdapModification[modList.Count];
                    Type mtype = typeof(LdapModification);
                    mods = (LdapModification[])modList.ToArray(mtype);
                    ModEntry(mods);
                }
            }
            else
            {
                LdapAttributeSet attributeSet = new LdapAttributeSet();
                foreach (string attribute in properties.PropertyNames)
                {
                    if (properties [attribute].Count == 1)
                    {
                        string val = (string)properties [attribute].Value;
                        attributeSet.Add(new LdapAttribute(attribute, val));
                    }
                    else
                    {
                        object[] vals     = (object [])properties [attribute].Value;
                        string[] aStrVals = new string [properties [attribute].Count];
                        Array.Copy(vals, 0, aStrVals, 0, properties [attribute].Count);
                        attributeSet.Add(new LdapAttribute(attribute, aStrVals));
                    }
                }
                LdapEntry newEntry = new LdapEntry(Fdn, attributeSet);
                conn.Add(newEntry);
                Nflag = false;
            }
        }
    public 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());
        }
    }
Ejemplo n.º 6
0
        public void Run(LdapEntry lhs, LdapEntry rhs)
        {
            Log.Debug("Starting LdapEntryAnalyzer");

            if (lhs.CompareTo(rhs) != 0)
            {
                Log.Debug("Entry DNs don't match\nlhs: {0}\nrhs: {1}", lhs.DN, rhs.DN);
                return;
            }

            LdapAttributeSet las = lhs.getAttributeSet();

            foreach (LdapAttribute la in las)
            {
                LdapAttribute rla = rhs.getAttribute(la.Name);
                if (rla == null)
                {
                    Log.Debug("Delete attribute {0} from {1}", la.Name, lhs.DN);
                    LdapAttribute    a = new LdapAttribute(la.Name);
                    LdapModification m = new LdapModification(LdapModification.DELETE, a);
                    mods.Add(m);
                }
                else
                {
                    if (rla.StringValueArray.Length > 1)
                    {
                        Log.Debug("Replacing attribute {0} with multiple values", la.Name);
                        LdapAttribute    a = new LdapAttribute(la.Name, rla.StringValueArray);
                        LdapModification m = new LdapModification(LdapModification.REPLACE, a);
                        mods.Add(m);
                    }
                    else if (la.StringValue != rla.StringValue)
                    {
                        LdapAttribute    newattr;
                        LdapModification lm;

                        if (rla.StringValue == "" || rla.StringValue == null)
                        {
                            Log.Debug("Delete attribute {0} from {1}", la.Name, lhs.DN);
                            newattr = new LdapAttribute(la.Name);
                            lm      = new LdapModification(LdapModification.DELETE, newattr);
                        }
                        else
                        {
                            Log.Debug("Replace attribute {0} value from {1} to {2} ", la.Name, la.StringValue, rla.StringValue);
                            newattr = new LdapAttribute(la.Name, rla.StringValue);
                            lm      = new LdapModification(LdapModification.REPLACE, newattr);
                        }

                        mods.Add(lm);
                    }
                }
            }

            LdapAttributeSet rlas = rhs.getAttributeSet();

            foreach (LdapAttribute la in rlas)
            {
                LdapAttribute lla = lhs.getAttribute(la.Name);
                if (lla == null && la.StringValue != string.Empty)
                {
                    Log.Debug("Add attribute {0} value [{1}] to {2}", la.Name, la.StringValue, lhs.DN);
                    LdapAttribute    a = new LdapAttribute(la.Name, la.StringValue);
                    LdapModification m = new LdapModification(LdapModification.ADD, a);
                    mods.Add(m);
                }
            }

            Log.Debug("End LdapEntryAnalyzer");
        }
Ejemplo n.º 7
0
        private int ldap_check(int serveruse)
        {
            try
            {
                if (serveruse == 1)
                {
                    Statusbar_Message("Retrieving username input");
                }
                if (Username.Text.Equals("") == true)
                {
                    Error_Handler("Input Error: Username field has been left blank.");
                    Statusbar_Message("Operation failed");
                    return(0);
                }
                if (serveruse == 1)
                {
                    Statusbar_Message("Retrieving password input");
                }
                string userPasswd = Password.Text;

                if (Password.Text.Equals("") == true)
                {
                    Error_Handler("Input Error: Password field has been left blank.");
                    Statusbar_Message("Operation failed");
                    return(0);
                }

                if (Context.SelectedIndex < 0)
                {
                    Error_Handler("Invalid Context selected from the list.");
                    Statusbar_Message("Operation failed");
                    return(0);
                }

                string   tdn    = "";
                string[] tempdn = Context.Items[Context.SelectedIndex].ToString().Split('.');
                System.Collections.IEnumerator runner = tempdn.GetEnumerator();
                while (runner.MoveNext())
                {
                    if (runner.Current.Equals("uct") == false)
                    {
                        tdn = tdn + "OU=" + runner.Current + ",";
                    }
                    else
                    {
                        tdn = tdn + "O=" + runner.Current + ",";
                    }
                }
                tdn = tdn.Remove(tdn.Length - 1, 1);
                string userDN = "CN=" + Username.Text.ToUpper() + "," + tdn;
                if (serveruse == 1)
                {
                    Statusbar_Message("Setting DN string as " + userDN);
                }



                string ldapHost;
                int    ldapPort;
                int    ldapVersion = LdapConnection.Ldap_V3;
                if (serveruse == 1)
                {
                    ldapHost = "rep1.uct.ac.za";
                    ldapPort = LdapConnection.DEFAULT_PORT;
                }
                else
                {
                    ldapHost = "rep2.uct.ac.za";
                    ldapPort = LdapConnection.DEFAULT_PORT;
                }
                Statusbar_Message("Setting LDAP server as " + ldapHost + ":" + ldapPort);

                Statusbar_Message("Attempting to bind " + Username.Text + " to " + ldapHost + ":" + ldapPort);
                // Creating an LdapConnection instance
                LdapConnection ldapConn = new LdapConnection();
                try
                {
                    //Connect function will create a socket
                    //ldapConn.SecureSocketLayer = true;
                    ldapConn.Connect(ldapHost, ldapPort);
                    //Bind function will Bind the user
                    //ldapConn.startTLS();
                    ldapConn.Bind(ldapVersion, userDN, userPasswd);
                    //ldapConn.stopTLS();
                }
                catch (System.Exception except)
                {
                    Error_Handler(except);
                    if (serveruse == 1)
                    {
                        Statusbar_Message("Contacting Secondary LDAP server");
                        ldap_check(2);
                        return(0);
                    }
                    else
                    {
                        Statusbar_Message("Operation failed");
                        return(0);
                    }
                }


                //LdapAttribute attr = new LdapAttribute("userPassword", userPasswd);
                //bool correct = ldapConn.Compare(userDN, attr);
                //label1_Message("Password Verify: " + correct);


                Statusbar_Message("Retrieving User Account Attributes");
                // Searches in the Marketing container and return all child entries just below this
                //container i.e Single level search
                LdapSearchQueue queue = ldapConn.Search(tdn, LdapConnection.SCOPE_SUB,
                                                        //"objectClass=*"
                                                        "CN=" + Username.Text.ToUpper(),
                                                        null,
                                                        false,
                                                        (LdapSearchQueue)null,
                                                        (LdapSearchConstraints)null);

                LdapMessage message;
                while ((message = queue.getResponse()) != null)

                {
                    if (message is LdapSearchResult)
                    {
                        LdapEntry entry = ((LdapSearchResult)message).Entry;
                        label1_Message("------------------------------------------------\n ENTRY:\n------------------------------------------------");
                        label1_Message(" " + entry.DN);
                        label1_Message("------------------------------------------------\n ATTRIBUTES:\n------------------------------------------------");
                        LdapAttributeSet attributeSet = entry.getAttributeSet();

                        System.Collections.IEnumerator ienum = attributeSet.GetEnumerator();
                        while (ienum.MoveNext())
                        {
                            LdapAttribute attribute     = (LdapAttribute)ienum.Current;
                            string        attributeName = attribute.Name;
                            //if (attributeName.Equals("groupMembership") == true)
                            {
                                System.Collections.IEnumerator ienum2 = attribute.StringValues;

                                while (ienum2.MoveNext())
                                {
                                    //string gr =(string)ienum.Current;
                                    //label1.Text = label1.Text + " \n " +  attributeName + " value:" + gr;
                                    label1_Message(" Attribute: " + attributeName + "\n Value: " + ienum2.Current.ToString() + "");
                                }
                            }
                        }
                    }
                }

                Statusbar_Message("Disconnecting from LDAP server");

                ldapConn.Disconnect();
                Statusbar_Message("Operation successfully completed");
                return(1);
            }
            catch (System.Exception except)
            {
                Error_Handler(except);
                Statusbar_Message("Operation failed");
            }
            return(0);
        }
        private async Task <bool> FindUser(string userName, LdapAuthenticationModeModel ldapAuthenticationMode, string password, bool testLogin, bool syncLdapAttributes)
        {
            try
            {
                var adminDistinguishedName = $"cn={ldapAuthenticationMode.Account},{ldapAuthenticationMode.BaseDn}";

                // Search for user in directory
                var searchBase   = $"{ldapAuthenticationMode.BaseDn}";
                var searchFilter = $"(cn = {userName})";

                try
                {
                    logger.Info($"Attempting to connect to LDAP connection. Hostname '{ldapAuthenticationMode.HostName}', Port '{ldapAuthenticationMode.Port}'");
                    ldapConnectionClient.Connect(ldapAuthenticationMode.HostName, ldapAuthenticationMode.Port);
                    logger.Info($"Attempting to bind with DN '{adminDistinguishedName}'");
                    ldapConnectionClient.Bind(adminDistinguishedName, ldapAuthenticationMode.Password);
                }
                catch (Exception ex)
                {
                    // User not authenticated
                    logger.Error(ex, "LDAP admin account user not authenticated.");
                    return(false);
                }

                LdapSearchResults lsc = ldapConnectionClient.Search(searchBase, LdapConnection.SCOPE_SUB, searchFilter, null, false);

                while (lsc.hasMore())
                {
                    LdapEntry ldapEntry;

                    try
                    {
                        ldapEntry = lsc.next();
                    }
                    catch (LdapException ex)
                    {
                        logger.Warn("Warning on LDAP search: " + ex.LdapErrorMessage);
                        continue;
                    }

                    // User found, try to log in
                    if (testLogin)
                    {
                        try
                        {
                            logger.Info($"Attempting to connect to LDAP connection. Hostname '{ldapAuthenticationMode.HostName}', Port '{ldapAuthenticationMode.Port}'");
                            ldapTestConnectionClient.Connect(ldapAuthenticationMode.HostName, ldapAuthenticationMode.Port);
                            logger.Info($"Attempting to bind with DN '{ldapEntry.DN}'");
                            ldapTestConnectionClient.Bind(ldapEntry.DN, password);
                        }
                        catch (Exception ex)
                        {
                            // User not authenticated
                            logger.Error(ex, "LDAP user not authenticated.");
                            return(false);
                        }
                    }

                    // Login successful. Sync attributes
                    if (syncLdapAttributes)
                    {
                        LdapAttributeSet attributeSet        = ldapEntry.getAttributeSet();
                        System.Collections.IEnumerator ienum = attributeSet.GetEnumerator();
                        var attributeValues = new Dictionary <string, string>();

                        while (ienum.MoveNext())
                        {
                            var attribute = (LdapAttribute)ienum.Current;
                            attributeValues.Add(attribute.Name, attribute.StringValue);
                        }

                        await SyncLdapAttributeToUserField(userName, ldapAuthenticationMode.LdapAttributes, attributeValues);
                    }

                    return(true);
                }

                // If we reached this point, we were not able authenticate the user
                return(false);
            }
            catch (Exception ex)
            {
                logger.Error(ex, "General error during LDAP authentication process.");
                return(false);
            }
        }
Ejemplo n.º 9
0
        public void AddUser(LdapUser user, string password)
        {
            var dn = $"CN={user.FirstName} {user.LastName},{_ldapSettings.ContainerName}";

            var attributeSet = new LdapAttributeSet
            {
                new LdapAttribute("instanceType", "4"),
                new LdapAttribute("objectCategory", $"CN=Person,CN=Schema,CN=Configuration,{_ldapSettings.DomainDistinguishedName}"),
                new LdapAttribute("objectClass", new[] { "top", "person", "organizationalPerson", "user" }),
                new LdapAttribute("name", user.UserName),
                new LdapAttribute("cn", $"{user.FirstName} {user.LastName}"),
                new LdapAttribute("sAMAccountName", user.UserName),
                new LdapAttribute("userPrincipalName", user.UserName),
                new LdapAttribute("unicodePwd", Convert.ToBase64String(Encoding.Unicode.GetBytes($"\"{user.Password}\""))),
                new LdapAttribute("userAccountControl", user.MustChangePasswordOnNextLogon ? "544" : "512"),
                new LdapAttribute("givenName", user.FirstName),
                new LdapAttribute("sn", user.LastName),
                new LdapAttribute("mail", user.EmailAddress)
            };

            if (user.DisplayName != null)
            {
                attributeSet.Add(new LdapAttribute("displayName", user.DisplayName));
            }

            if (user.Description != null)
            {
                attributeSet.Add(new LdapAttribute("description", user.Description));
            }
            if (user.Phone != null)
            {
                attributeSet.Add(new LdapAttribute("telephoneNumber", user.Phone));
            }
            if (user.Address?.Street != null)
            {
                attributeSet.Add(new LdapAttribute("streetAddress", user.Address.Street));
            }
            if (user.Address?.City != null)
            {
                attributeSet.Add(new LdapAttribute("l", user.Address.City));
            }
            if (user.Address?.PostalCode != null)
            {
                attributeSet.Add(new LdapAttribute("postalCode", user.Address.PostalCode));
            }
            if (user.Address?.StateName != null)
            {
                attributeSet.Add(new LdapAttribute("st", user.Address.StateName));
            }
            if (user.Address?.CountryName != null)
            {
                attributeSet.Add(new LdapAttribute("co", user.Address.CountryName));
            }
            if (user.Address?.CountryCode != null)
            {
                attributeSet.Add(new LdapAttribute("c", user.Address.CountryCode));
            }

            var newEntry = new Novell.Directory.Ldap.LdapEntry(dn, attributeSet);

            using (var ldapConnection = GetConnection())
            {
                ldapConnection.Add(newEntry);
            }
        }
Ejemplo n.º 10
0
 private Identity.Models.LdapEntry CreateEntryFromAttributes(string distinguishedName, LdapAttributeSet attributeSet)
 {
     return(new Identity.Models.LdapEntry
     {
         ObjectSid = attributeSet.getAttribute("objectSid")?.StringValue,
         ObjectGuid = attributeSet.getAttribute("objectGUID")?.StringValue,
         ObjectCategory = attributeSet.getAttribute("objectCategory")?.StringValue,
         ObjectClass = attributeSet.getAttribute("objectClass")?.StringValue,
         CommonName = attributeSet.getAttribute("cn")?.StringValue,
         Name = attributeSet.getAttribute("name")?.StringValue,
         DistinguishedName = attributeSet.getAttribute("distinguishedName")?.StringValue ?? distinguishedName,
         SamAccountName = attributeSet.getAttribute("sAMAccountName")?.StringValue,
         SamAccountType = int.Parse(attributeSet.getAttribute("sAMAccountType")?.StringValue ?? "0"),
     });
 }
Ejemplo n.º 11
0
    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);
    }
Ejemplo n.º 12
0
        /// <summary>
        /// Retrieves group information from ldap
        /// </summary>
        /// <param name="retrieveGroupMembers">true to return users in each group. This may hurt performance</param>
        /// <param name="optionalGroupName">Group to lookup by name. Null for all groups</param>
        /// <returns></returns>
        public XDoc GetGroupInfo(bool retrieveGroupMembers, string optionalGroupName)
        {
            LdapConnection conn      = null;
            XDoc           resultXml = null;

            try {
                //Confirm a query bind has been established
                conn = Bind();

                string searchFilter;

                //Build the searchfilter based on if a group name is given.
                if (!string.IsNullOrEmpty(optionalGroupName))
                {
                    optionalGroupName = EscapeLdapString(optionalGroupName);

                    //Looking up group by name
                    searchFilter = string.Format(PhpUtil.ConvertToFormatString(_config.GroupQuery), optionalGroupName);
                }
                else
                {
                    //Looking up all groups
                    searchFilter = _config.GroupQueryAll;
                }

                //Build interesting attribute list
                List <string> attrs = new List <string>();
                attrs.AddRange(new string[] { "whenCreated", "name", "sAMAccountName", "cn" });
                if (retrieveGroupMembers)
                {
                    attrs.Add("member");
                }

                if (!string.IsNullOrEmpty(_config.GroupNameAttribute) && !attrs.Contains(_config.GroupNameAttribute))
                {
                    attrs.Add(_config.GroupNameAttribute);
                }

                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);

                //Create outer groups collection if multiple groups are being looked up or none provided
                if (string.IsNullOrEmpty(optionalGroupName))
                {
                    resultXml = new XDoc("groups");
                }

                while (results.hasMore())
                {
                    LdapEntry nextEntry = null;
                    try {
                        nextEntry = results.next();
                    } catch (LdapException x) {
                        HandleLdapException(x);
                        continue;
                    }

                    //Create xml from search entry
                    if (resultXml == null)
                    {
                        resultXml = new XDoc("group");
                    }
                    else
                    {
                        resultXml.Start("group");
                    }

                    string name = string.Empty;

                    //If a groupnameattribute is configured, use that. Otherwise try the common ones.
                    if (!string.IsNullOrEmpty(_config.GroupNameAttribute))
                    {
                        name = GetAttributeSafe(nextEntry, _config.GroupNameAttribute);
                    }
                    else
                    {
                        name = GetAttributeSafe(nextEntry, "sAMAccountName"); //MS Active Directory
                        if (string.IsNullOrEmpty(name))
                        {
                            name = GetAttributeSafe(nextEntry, "uid"); //OpenLDAP
                        }
                        if (string.IsNullOrEmpty(name))
                        {
                            name = GetAttributeSafe(nextEntry, "name"); //OpenLDAP
                        }
                        if (string.IsNullOrEmpty(name))
                        {
                            name = GetAttributeSafe(nextEntry, "cn"); //Novell eDirectory
                        }
                    }

                    resultXml.Attr("name", name);
                    resultXml.Start("ldap-dn").Value(nextEntry.DN).End();
                    resultXml.Start("date.created").Value(ldapStringToDate(GetAttributeSafe(nextEntry, "whenCreated"))).End();

                    //Retrieve and write group membership to xml
                    LdapAttributeSet memberAttrSet = nextEntry.getAttributeSet();
                    LdapAttribute    memberAttr    = memberAttrSet.getAttribute("member");

                    // TODO MaxM: This currently does not differentiate between user and group
                    // members.

                    if (memberAttr != null)
                    {
                        foreach (string member in memberAttr.StringValueArray)
                        {
                            resultXml.Start("member");
                            resultXml.Attr("name", GetNameFromDn(member));
                            resultXml.Start("ldap-dn").Value(member).End();
                            resultXml.End();
                        }
                    }
                    if (string.IsNullOrEmpty(optionalGroupName))
                    {
                        resultXml.End();
                    }
                }
            } finally {
                UnBind(conn);
            }

            return(resultXml);
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Retrieve information about one or more users
        /// </summary>
        /// <param name="retrieveGroupMembership">retrieving list of groups for each user will take longer</param>
        /// <param name="username">Username to lookup</param>
        /// <returns></returns>
        public XDoc GetUserInfo(bool retrieveGroupMembership, string username)
        {
            XDoc           resultXml = null;
            LdapConnection conn      = null;

            try {
                LdapSearchResults results = LookupLdapUser(retrieveGroupMembership, username, out conn);

                if (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
                    resultXml = new XDoc("user");

                    string name = string.Empty;

                    //If a usernameattribute is configured, use that. Otherwise try the common ones.
                    if (!string.IsNullOrEmpty(_config.UserNameAttribute))
                    {
                        name = GetAttributeSafe(nextEntry, _config.UserNameAttribute);
                    }
                    else
                    {
                        name = GetAttributeSafe(nextEntry, "sAMAccountName"); //MS Active Directory
                        if (string.IsNullOrEmpty(name))
                        {
                            name = GetAttributeSafe(nextEntry, "uid"); //OpenLDAP
                        }
                        if (string.IsNullOrEmpty(name))
                        {
                            name = GetAttributeSafe(nextEntry, "name"); //OpenLDAP
                        }
                        if (string.IsNullOrEmpty(name))
                        {
                            name = GetAttributeSafe(nextEntry, "cn"); //Novell eDirectory
                        }
                    }

                    string displayName = BuildDisplayNameFromPattern(_config.DisplayNamePattern, nextEntry);

                    resultXml.Attr("name", name);
                    if (!string.IsNullOrEmpty(displayName))
                    {
                        resultXml.Attr("displayname", displayName);
                    }

                    resultXml.Start("ldap-dn").Value(nextEntry.DN).End();
                    resultXml.Start("date.created").Value(ldapStringToDate(GetAttributeSafe(nextEntry, "whenCreated"))).End();
                    resultXml.Start("firstname").Value(GetAttributeSafe(nextEntry, "givenname")).End();
                    resultXml.Start("lastname").Value(GetAttributeSafe(nextEntry, "sn")).End();
                    resultXml.Start("phonenumber").Value(GetAttributeSafe(nextEntry, "telephonenumber")).End();
                    resultXml.Start("email").Value(GetAttributeSafe(nextEntry, "mail")).End();
                    resultXml.Start("description").Value(GetAttributeSafe(nextEntry, "description")).End();

                    //Retrieve group memberships

                    if (string.IsNullOrEmpty(_config.GroupMembershipQuery))
                    {
                        LdapAttributeSet memberAttrSet = nextEntry.getAttributeSet();

                        LdapAttribute memberAttr = null;
                        if (memberAttrSet != null)
                        {
                            memberAttr = memberAttrSet.getAttribute(_config.GroupMembersAttribute);
                        }

                        if (memberAttr != null)
                        {
                            resultXml.Start("groups");
                            foreach (string member in memberAttr.StringValueArray)
                            {
                                resultXml.Start("group");
                                resultXml.Attr("name", GetNameFromDn(member));
                                resultXml.Start("ldap-dn").Value(member).End();
                                resultXml.End();
                            }
                            resultXml.End();
                        }
                    }
                    else
                    {
                        //Perform custom query to determine groups of a user
                        PopulateGroupsForUserWithQuery(resultXml, username, conn);
                    }
                }
            } finally {
                UnBind(conn);
            }

            return(resultXml);
        }
Ejemplo n.º 14
0
        public static Task <bool> LoginAsync(string username, string password)
        {
            CancellationTokenSource cts = new CancellationTokenSource();
            CancellationToken       cancellationToken = cts.Token;

            LdapConnection conn = null;


            return(Task.Factory.StartNew(() => {
                conn = new LdapConnection();
                conn.Connect(Host, Port);


                if (!string.IsNullOrEmpty(username))
                {
                    try
                    {
                        conn.Bind(dn, pa);
                    }
                    catch (Exception e)
                    {
                        conn.Disconnect();
                        return false;
                    }

                    string searchBase = filter;

                    int searchScope = LdapConnection.ScopeSub;
                    string searchFilter = "uid=" + username.Trim();
                    LdapSearchQueue queue = conn.Search(searchBase,
                                                        searchScope,
                                                        searchFilter,
                                                        null,
                                                        false,
                                                        (LdapSearchQueue)null,
                                                        (LdapSearchConstraints)null);

                    LdapMessage message;
                    while ((message = queue.GetResponse()) != null)
                    {
                        try
                        {
                            string msg = message.ToString();

                            LdapEntry entry = ((LdapSearchResult)message).Entry;

                            LdapAttributeSet attributeSet = entry.GetAttributeSet();
                            System.Collections.IEnumerator ienum = attributeSet.GetEnumerator();

                            LdapAttribute cn = attributeSet.GetAttribute("cn");
                            string idUser = cn.StringValue;

                            try
                            {
                                conn.Bind("cn=" + idUser + "," + filter, password);
                            }
                            catch (Exception e)
                            {
                                conn.Disconnect();
                                return false;
                            }

                            conn.Disconnect();
                            return true;
                        }
                        catch (Exception e)
                        {
                            conn.Disconnect();
                            return false;
                        }
                    }
                }

                return false;
            }, cancellationToken));
        }
Ejemplo n.º 15
0
        public Tuple <LDAPLoginResponseContract, string> Requester(
            string host,
            string baseConnector,
            string usernameSuffix,
            string userName,
            string password)
        {
            var    result     = new LDAPLoginResponseContract();
            string memberOf   = string.Empty;
            var    searchAttr = new string[]
            {
                mSAMAccountNameKey,
                mDisplayNameKey,
                mDisplayThaiNameKey,
                mRoleEnKey,
                mBranchThKey,
                mRoleThKey,
                mSexKey,
                mMemberOfKey,
            };

            try
            {
                using (var connection = new LdapConnection {
                    SecureSocketLayer = false
                })
                {
                    connection.Connect(host, LdapConnection.DEFAULT_PORT);
                    connection.Bind(userName + usernameSuffix, password);

                    if (connection.Bound)
                    {
                        var lsc = connection.Search(
                            baseConnector,
                            LdapConnection.SCOPE_SUB,
                            $"(&(objectClass=person)(sAMAccountName={userName}))",
                            searchAttr,
                            false
                            );
                        while (lsc.hasMore())
                        {
                            LdapEntry nextEntry = null;
                            try
                            {
                                nextEntry = lsc.next();
                            }
                            catch
                            {
                                continue;
                            }

                            LdapAttributeSet attributeSet        = nextEntry.getAttributeSet();
                            System.Collections.IEnumerator ienum = attributeSet.GetEnumerator();
                            while (ienum.MoveNext())
                            {
                                LdapAttribute attribute     = (LdapAttribute)ienum.Current;
                                string        attributeName = attribute.Name;
                                string        attributeVal  = attribute.StringValue;
                                switch (attributeName)
                                {
                                case mSAMAccountNameKey:
                                {
                                    result.userId = attributeVal.Substring(attributeVal.IndexOf(':') + 1).Trim();
                                    break;
                                }

                                case mDisplayNameKey:
                                {
                                    result.fullName = attributeVal.Substring(attributeVal.IndexOf(':') + 1).Trim();
                                    break;
                                }

                                case mDisplayThaiNameKey:
                                {
                                    result.fullNameTh =
                                        attributeVal.Substring(attributeVal.IndexOf(':') + 1).Trim();
                                    break;
                                }

                                case mRoleEnKey:
                                {
                                    string[] roleEnList = attributeVal.Split('|');
                                    string   roleEn     = roleEnList[0].Substring(roleEnList[0].IndexOf(':') + 1).Trim();
                                    result.roleEn = roleEn;
                                    break;
                                }

                                case mBranchThKey:
                                {
                                    string[] branch = attributeVal.Split('|');
                                    result.branchTh   = branch[0].Trim();
                                    result.branchCode = branch[1].Trim();
                                    break;
                                }

                                case mRoleThKey:
                                {
                                    string[] role = attributeVal.Split('|');
                                    result.roleTh   = role[0].Trim();
                                    result.roleCode = role[1].Trim();
                                    break;
                                }

                                case mSexKey:
                                {
                                    result.sex = attributeVal.Substring(attributeVal.IndexOf(':') + 1).Trim();
                                    break;
                                }

                                case mMemberOfKey:
                                {
                                    result.channel   = "";   //TODO implement role
                                    memberOf        += (" MEMBEROF " + string.Join(" , ", attribute.StringValueArray));
                                    result.authority = ConfigRoleByMemberOf(attribute.StringValueArray);
                                    break;
                                }

                                default:
                                    break;
                                }
                            }
                        }

                        connection.Disconnect();
                    }
                }

                if (string.IsNullOrEmpty(result.authority))
                {
                    return(new Tuple <LDAPLoginResponseContract, string>(null, memberOf));
                }

                return(new Tuple <LDAPLoginResponseContract, string>(result, memberOf));
            }
            catch (Exception e)
            {
                return(new Tuple <LDAPLoginResponseContract, string>(null, memberOf + " " + e.ToString()));
            }
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Create a New User in the LDAP Tree
        /// </summary>
        /// <param name="dn">The New User DN</param>
        /// <param name="password">The New User Password</param>
        /// <returns>true, if the user was created. false, if the user already exists.</returns>
        public bool CreateUser(string dn, string password)
        {
            // KLUDGE: The search method is currently failing with the LDAP libraries.

            //LdapSearchResults results = connection.Search(proxyDN,
            //	LdapConnection.SCOPE_BASE, "(objectclass=*)", null, false);

            bool created = true;

            //if (!results.hasMore())
            try
            {
                // find
                connection.Read(dn);

                created = false;
            }
            catch
            {
                LdapAttributeSet attributeSet = new LdapAttributeSet();
                switch (ldapType)
                {
                case LdapDirectoryType.ActiveDirectory:
                {
                    Regex    cnRegex         = null;
                    int      AccEnable       = (int)ADS_USER_FLAGS.NORMAL_ACCOUNT | (int)ADS_USER_FLAGS.DONT_EXPIRE_PASSWD;                  // Flags set to 66048
                    string   quotedPassword  = "******"" + password + "\"";
                    char []  unicodePassword = quotedPassword.ToCharArray();
                    sbyte [] userPassword    = new sbyte[unicodePassword.Length * 2];

                    for (int i = 0; i < unicodePassword.Length; i++)
                    {
                        userPassword[i * 2 + 1] = (sbyte)(unicodePassword[i] >> 8);
                        userPassword[i * 2 + 0] = (sbyte)(unicodePassword[i] & 0xff);
                    }

                    if (dn.ToLower().StartsWith("cn="))
                    {
                        cnRegex = new Regex(@"^cn=(.*?),.*$", RegexOptions.IgnoreCase | RegexOptions.Compiled);
                    }
                    else if (dn.ToLower().StartsWith("uid="))
                    {
                        cnRegex = new Regex(@"^uid=(.*?),.*$", RegexOptions.IgnoreCase | RegexOptions.Compiled);
                    }
                    string cn = cnRegex.Replace(dn, "$1");

                    // create user attributes
                    attributeSet.Add(new LdapAttribute("objectClass", "user"));
                    attributeSet.Add(new LdapAttribute("objectClass", "InetOrgPerson"));
                    attributeSet.Add(new LdapAttribute("cn", cn));
                    attributeSet.Add(new LdapAttribute("SamAccountName", cn));
                    attributeSet.Add(new LdapAttribute("sn", cn));
                    attributeSet.Add(new LdapAttribute("userAccountControl", AccEnable.ToString()));
                    attributeSet.Add(new LdapAttribute("UnicodePwd", userPassword));
                    break;
                }

                case LdapDirectoryType.eDirectory:
                {
                    // parse the cn
                    Regex cnRegex = null;
                    if (dn.ToLower().StartsWith("cn="))
                    {
                        cnRegex = new Regex(@"^cn=(.*?),.*$", RegexOptions.IgnoreCase | RegexOptions.Compiled);
                    }
                    else if (dn.ToLower().StartsWith("uid="))
                    {
                        cnRegex = new Regex(@"^uid=(.*?),.*$", RegexOptions.IgnoreCase | RegexOptions.Compiled);
                    }
                    string cn = cnRegex.Replace(dn, "$1");

                    // create user attributes
                    attributeSet.Add(new LdapAttribute("objectClass", "inetOrgPerson"));
                    attributeSet.Add(new LdapAttribute("cn", cn));
                    attributeSet.Add(new LdapAttribute("sn", cn));
                    attributeSet.Add(new LdapAttribute("userPassword", password));
                    break;
                }

                case LdapDirectoryType.OpenLDAP:
                {
                    Regex  uidRegex = new Regex(@"^(.*?)=(.*?),.*$", RegexOptions.IgnoreCase | RegexOptions.Compiled);
                    string uid      = uidRegex.Replace(dn, "$2");

                    // I think we can get away with just creating an inetOrgPerson ...
                    // we don't need a posixAccount ... hmm, maybe a shadowAccount
                    // so that the password can expire?
                    attributeSet.Add(new LdapAttribute("objectClass", "inetOrgPerson"));                            //new string[]{"inetOrgPerson", "posixAccount", "shadowAccount"}));
                    attributeSet.Add(new LdapAttribute("uid", uid));
                    attributeSet.Add(new LdapAttribute("cn", uid));
                    attributeSet.Add(new LdapAttribute("sn", uid));
                    attributeSet.Add(new LdapAttribute("givenName", uid));
                    attributeSet.Add(new LdapAttribute("displayName", uid));
                    // TODO: Need to encrypt the password first.
                    attributeSet.Add(new LdapAttribute("userPassword", password));
                    break;
                }
                }

                // add user entry
                Console.Write("Creating proxy {0}", dn);
                try
                {
                    LdapEntry entry = new LdapEntry(dn, attributeSet);
                    connection.Add(entry);
                }
                catch (Exception ex)
                {
                    if (ex.Message.IndexOf("Constraint Violation") != -1)
                    {
                        throw new Exception("Constraint Violation: password too short or Q not active");
                    }
                    if (ex.ToString().IndexOf("-16000") != -1)
                    {
                        throw new Exception("Constraint Violation: password is too long");
                    }
                    // This is applicable for both admin and proxy user.
                    created = false;
                }
            }

            // result
            return(created);
        }
Ejemplo n.º 17
0
        private void DoSearch()
        {
            InitBlock();
            String[] attrs = new String[PropertiesToLoad.Count];
            PropertiesToLoad.CopyTo(attrs, 0);

            LdapSearchConstraints cons = _conn.SearchConstraints;

            if (SizeLimit > 0)
            {
                cons.MaxResults = SizeLimit;
            }
            if (ServerTimeLimit != DefaultTimeSpan)
            {
                cons.ServerTimeLimit = (int)ServerTimeLimit.TotalSeconds;
            }

            int connScope = LdapConnection.SCOPE_SUB;

            switch (_SearchScope)
            {
            case SearchScope.Base:
                connScope = LdapConnection.SCOPE_BASE;
                break;

            case SearchScope.OneLevel:
                connScope = LdapConnection.SCOPE_ONE;
                break;

            case SearchScope.Subtree:
                connScope = LdapConnection.SCOPE_SUB;
                break;

            default:
                connScope = LdapConnection.SCOPE_SUB;
                break;
            }
            LdapSearchResults lsc = _conn.Search(SearchRoot.Fdn,
                                                 connScope,
                                                 Filter,
                                                 attrs,
                                                 PropertyNamesOnly, cons);

            while (lsc.hasMore())
            {
                LdapEntry nextEntry = null;
                try
                {
                    nextEntry = lsc.next();
                }
                catch (LdapException e)
                {
                    switch (e.ResultCode)
                    {
                    // in case of this return codes exception should not be thrown
                    case LdapException.SIZE_LIMIT_EXCEEDED:
                    case LdapException.TIME_LIMIT_EXCEEDED:
                    case LdapException.REFERRAL:
                        continue;

                    default:
                        throw e;
                    }
                }
                DirectoryEntry     de    = new DirectoryEntry(_conn);
                PropertyCollection pcoll = new PropertyCollection();
//				de.SetProperties();
                de.Path = DirectoryEntry.GetLdapUrlString(_Host, _Port, nextEntry.DN);
                LdapAttributeSet attributeSet        = nextEntry.getAttributeSet();
                System.Collections.IEnumerator ienum = attributeSet.GetEnumerator();
                if (ienum != null)
                {
                    while (ienum.MoveNext())
                    {
                        LdapAttribute attribute     = (LdapAttribute)ienum.Current;
                        string        attributeName = attribute.Name;
                        pcoll[attributeName].AddRange(attribute.StringValueArray);
//						de.Properties[attributeName].AddRange(attribute.StringValueArray);
//						de.Properties[attributeName].Mbit=false;
                    }
                }
                if (!pcoll.Contains("ADsPath"))
                {
                    pcoll["ADsPath"].Add(de.Path);
                }
//				_SrchColl.Add(new SearchResult(de,PropertiesToLoad));
                _SrchColl.Add(new SearchResult(de, pcoll));
            }
            return;
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Queries to find the type of directory
        /// </summary>
        /// <returns>The LDAP directory type.</returns>
        public LdapDirectoryType QueryDirectoryType()
        {
            Console.WriteLine("get directory type");

            LdapAttribute     attr       = null;
            LdapEntry         entry      = null;
            bool              eDirectory = false;
            LdapSearchResults lsc        = connection.Search("",
                                                             LdapConnection.SCOPE_BASE,
                                                             "objectClass=*",
                                                             null,
                                                             false);

            while (lsc.hasMore())
            {
                entry = null;
                try
                {
                    entry = lsc.next();
                }
                catch (LdapException e)
                {
                    Console.WriteLine("Error: " + e.LdapErrorMessage);
                    // Exception is thrown, go for next entry
                    continue;
                }
                Console.WriteLine("\n" + entry.DN);
                LdapAttributeSet attributeSet        = entry.getAttributeSet();
                System.Collections.IEnumerator ienum = attributeSet.GetEnumerator();

                while (ienum.MoveNext())
                {
                    attr = (LdapAttribute)ienum.Current;
                    string attributeName = attr.Name;
                    string attributeVal  = attr.StringValue;
                    Console.WriteLine(attributeName + ": value :" + attributeVal);

                    //eDirectory specific attributes
                    //If any of the following attribute is found, conclude this as eDirectory
                    if (                                                         /*String.Equals(attributeName, "vendorVersion")==true ||	*/
                        String.Equals(attributeVal, "Novell, Inc.") == true ||
                        String.Equals(attributeVal, "NetIQ Corporation") == true /* ||
                                                                                  * String.Equals(attributeName, "dsaName")==true ||*/

                        /*String.Equals(attributeName, "directoryTreeName")==true*/)
                    {
                        eDirectory = true;
                        Console.WriteLine("Type : Novell eDirectory");
                        break;
                    }
                }
            }

            if (eDirectory == true)
            {
                ldapType = LdapDirectoryType.eDirectory;
            }
            else
            {
                // Decide is this a Active Directory or not. If not AD then the assumption is OpenLDAP
                entry = connection.Read("");
                attr  = entry.getAttribute("defaultNamingContext");
                if (attr != null)
                {
                    ldapType = LdapDirectoryType.ActiveDirectory;
                }
                else
                {
                    ldapType = LdapDirectoryType.OpenLDAP;
                }
            }

            return(ldapType);
        }
Ejemplo n.º 19
0
        public static void Test()
        {
            string ldapHost = TestSettings.ldapHost; // args[0];
            int    ldapPort = TestSettings.ldapPort; // System.Convert.ToInt32(args[1]);
            string loginDN  = TestSettings.loginDN;  // args[2];
            string password = TestSettings.password; // args[3];


            string searchBase = "DC=cor,DC=local"; // args[4];

            searchBase = null;
            searchBase = "DC=rootDSE";
            searchBase = "DC=cor,DC=local";
            searchBase = " ";
            // searchBase = "CN=Configuration,DC=cor,DC=local";
            /// searchBase = "CN=,DC=cor,DC=local";
            // searchBase = "rootDSE";

            string searchFilter = "(objectclass=*)";

            searchFilter = "(objectClass=*)";

            try
            {
                LdapConnection conn = new LdapConnection();
                Console.WriteLine("Connecting to:" + ldapHost);
                conn.Connect(ldapHost, ldapPort);



                conn.Bind(loginDN, password);

                //dsServiceName
                //CN = NTDS Settings,CN = COR - AD02,CN = Servers,CN = COR - ERLEN,CN = Sites,CN = Configuration,DC = cor,DC = local

                //serverName
                //CN = COR - AD02, CN = Servers, CN = COR - ERLEN, CN = Sites, CN = Configuration, DC = cor, DC = local

                //configurationNamingContext
                //CN = Configuration, DC = cor, DC = local

                //dnsHostName
                //cor - ad02.cor.local

                string defaultNamingContext       = GetDefaultNamingContext(conn);
                string configurationNamingContext = GetConfigurationNamingContext(conn);
                string dnsHostName = GetDnsHostName(conn);

                System.Console.WriteLine(defaultNamingContext);
                System.Console.WriteLine(configurationNamingContext);
                System.Console.WriteLine(dnsHostName);

                GetRootDSE(conn);



                string foo = conn.GetSchemaDN();
                System.Console.WriteLine(foo);


                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));
                        }

                        if (string.Equals(attributeName, "defaultNamingContext", StringComparison.InvariantCultureIgnoreCase))
                        {
                            System.Console.WriteLine("yahoo");
                        }

                        Console.WriteLine(attributeName + "value:" + attributeVal);
                    }
                }
                conn.Disconnect();
                System.Console.WriteLine("disconnected");
            }
            catch (LdapException e)
            {
                Console.WriteLine("Error:" + e.LdapErrorMessage);
                return;
            }
            catch (Exception e)
            {
                Console.WriteLine("Error:" + e.Message);
                return;
            }
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Extends the Active directory AD iFolderschema
        /// </summary>
        /// <returns>True on successful schema Extension and false on Failure. </returns>
        public bool ExtendADiFolderschema()
        {
            LdapAttribute attr  = null;
            LdapEntry     entry = null;
            string        retschemaNamingContext = String.Empty;

            string[]          searchAttributes = { "schemaNamingContext" };
            LdapSearchResults lsc = connection.Search("",
                                                      LdapConnection.SCOPE_BASE,
                                                      "objectClass=*",
                                                      searchAttributes,
                                                      false);

            while (lsc.hasMore())
            {
                entry = null;
                try
                {
                    entry = lsc.next();
                }
                catch (LdapException e)
                {
                    Console.WriteLine("Error: " + e.LdapErrorMessage);
                    continue;
                }
                LdapAttributeSet attributeSet        = entry.getAttributeSet();
                System.Collections.IEnumerator ienum = attributeSet.GetEnumerator();

                while (ienum.MoveNext())
                {
                    attr = (LdapAttribute)ienum.Current;
                    string attributeName = attr.Name;
                    Console.WriteLine(attributeName + ": value :" + attr.StringValue);

                    if (String.Equals(attributeName, searchAttributes[0]) == true)
                    {
                        retschemaNamingContext = attr.StringValue;
                        break;
                    }
                }
            }
            try
            {
                LdapAttributeSet newattr_attributeSet = new LdapAttributeSet();
                newattr_attributeSet.Add(new LdapAttribute("adminDisplayName", "iFolderHomeServer"));
                newattr_attributeSet.Add(new LdapAttribute("attributeID", "2.16.840.1.113719.1.288.1.42"));
                newattr_attributeSet.Add(new LdapAttribute("cn", "iFolderHomeServer"));
                newattr_attributeSet.Add(new LdapAttribute("attributeSyntax", "2.5.5.12"));
                newattr_attributeSet.Add(new LdapAttribute("adminDescription", "iFolder 3.x iFolderHomeServer Attribute, stores DNS Name or IP address of Users/Groups iFolder server."));
                newattr_attributeSet.Add(new LdapAttribute("isMemberOfPartialAttributeSet", "FALSE"));
                newattr_attributeSet.Add(new LdapAttribute("isSingleValued", "TRUE"));
                newattr_attributeSet.Add(new LdapAttribute("showInAdvancedViewOnly", "FALSE"));
                newattr_attributeSet.Add(new LdapAttribute("lDAPDisplayName", "iFolderHomeServer"));
                newattr_attributeSet.Add(new LdapAttribute("distinguishedName", "CN=iFolderHomeServer," + retschemaNamingContext));
                newattr_attributeSet.Add(new LdapAttribute("objectCategory", "CN=Attribute-Schema," + retschemaNamingContext));
                newattr_attributeSet.Add(new LdapAttribute("objectClass", "attributeSchema"));
                newattr_attributeSet.Add(new LdapAttribute("oMSyntax", "64"));
                newattr_attributeSet.Add(new LdapAttribute("name", "iFolderHomeServer"));
                newattr_attributeSet.Add(new LdapAttribute("searchFlags", "0"));

                Console.WriteLine("\nExtending Active Directory Schema for {0}", "CN=iFolderHomeServer," + retschemaNamingContext);
                LdapEntry newattr_entry = new LdapEntry("CN=iFolderHomeServer," + retschemaNamingContext, newattr_attributeSet);
                connection.Add(newattr_entry);


                LdapAttribute    newattr_modattribute = new LdapAttribute("schemaUpdateNow", "1");
                LdapModification newattr_modification = new LdapModification(LdapModification.REPLACE, newattr_modattribute);
                connection.Modify("", newattr_modification);

                Console.WriteLine("\n Updating {0}", "CN=user," + retschemaNamingContext);
                LdapAttribute    newclass_modattribute = new LdapAttribute("mayContain", "iFolderHomeServer");
                LdapModification newclass_modification = new LdapModification(LdapModification.ADD, newclass_modattribute);
                connection.Modify("cn=user," + retschemaNamingContext, newclass_modification);

                newclass_modattribute = new LdapAttribute("schemaUpdateNow", "1");
                newclass_modification = new LdapModification(LdapModification.REPLACE, newclass_modattribute);
                connection.Modify("", newclass_modification);
                Console.WriteLine("Completed.\n");
            }
            catch (LdapException e)
            {
                if (e.ResultCode == LdapException.ENTRY_ALREADY_EXISTS)
                {
                    Console.WriteLine("\n Active Directory iFolder Schema is already Extended.");
                    return(true);
                }
                else
                {
                    Console.WriteLine("\n Unable to extend Active Directory iFolder Schema. {0}::{1}", e.ResultCode.ToString(), e.Message);
                    return(false);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("\n Unable to extend Active Directory iFolder Schema. Ex.Message {0}", e.Message);
                return(false);
            }
            Console.WriteLine("\nActive Directory iFolder Schema Extended.");
            return(true);
        }
Ejemplo n.º 21
0
            public static DomainObject ConvertLDAPProperty(LdapEntry result)
            {
                DomainObject     obj          = new DomainObject();
                LdapAttributeSet attributeSet = result.getAttributeSet();

                System.Collections.IEnumerator ienum = attributeSet.GetEnumerator();
                while (ienum.MoveNext())
                {
                    LdapAttribute attr = (LdapAttribute)ienum.Current;
                    switch (attr.Name.ToLower())
                    {
                    case "objectsid":
                        //Will need to convert this to a string
                        obj.objectsid = attr.StringValue;
                        break;

                    case "sidhistory":
                        obj.sidhistory = attr.StringValueArray;
                        break;

                    case "grouptype":
                        obj.grouptype = (GroupTypeEnum)Enum.Parse(typeof(GroupTypeEnum), attr.StringValue);
                        break;

                    case "samaccounttype":
                        obj.samaccounttype = (SamAccountTypeEnum)Enum.Parse(typeof(SamAccountTypeEnum), attr.StringValue);
                        break;

                    case "objectguid":
                        //Will need to conver this to a string
                        obj.objectguid = attr.StringValue;
                        break;

                    case "useraccountcontrol":
                        //convertme
                        break;

                    case "ntsecuritydescriptor":
                        //convertme
                        break;

                    case "accountexpires":
                        if (long.Parse(attr.StringValue) >= DateTime.MaxValue.Ticks)
                        {
                            obj.accountexpires = DateTime.MaxValue;
                        }
                        try
                        {
                            obj.accountexpires = DateTime.FromFileTime(long.Parse(attr.StringValue));
                        }
                        catch (ArgumentOutOfRangeException)
                        {
                            obj.accountexpires = DateTime.MaxValue;
                        }
                        break;

                    case "lastlogon":
                        DateTime dateTime = DateTime.MinValue;
                        //Not sure if this syntax is right.
                        if (attr.StringValues.GetType().Name == "System.MarshalByRefObject")
                        {
                            var comobj = (MarshalByRefObject)attr.StringValues;
                            int high   = (int)comobj.GetType().InvokeMember("HighPart", System.Reflection.BindingFlags.GetProperty, null, comobj, null);
                            int low    = (int)comobj.GetType().InvokeMember("LowPart", System.Reflection.BindingFlags.GetProperty, null, comobj, null);
                            dateTime = DateTime.FromFileTime(int.Parse("0x" + high + "" + low, System.Globalization.NumberStyles.HexNumber));
                        }
                        else
                        {
                            dateTime = DateTime.FromFileTime(long.Parse(attr.StringValue));
                        }
                        obj.lastlogon = dateTime;
                        break;

                    case "pwdlastset":
                        if (attr.StringValues.GetType().Name == "System.MarshalByRefObject")
                        {
                            var comobj = (MarshalByRefObject)attr.StringValues;
                            int high   = (int)comobj.GetType().InvokeMember("HighPart", System.Reflection.BindingFlags.GetProperty, null, comobj, null);
                            int low    = (int)comobj.GetType().InvokeMember("LowPart", System.Reflection.BindingFlags.GetProperty, null, comobj, null);
                            dateTime = DateTime.FromFileTime(int.Parse("0x" + high + "" + low, System.Globalization.NumberStyles.HexNumber));
                        }
                        else
                        {
                            dateTime = DateTime.FromFileTime(long.Parse(attr.StringValue));
                        }
                        obj.pwdlastset = dateTime;
                        break;

                    case "lastlogoff":
                        if (attr.StringValues.GetType().Name == "System.MarshalByRefObject")
                        {
                            var comobj = (MarshalByRefObject)attr.StringValues;
                            int high   = (int)comobj.GetType().InvokeMember("HighPart", System.Reflection.BindingFlags.GetProperty, null, comobj, null);
                            int low    = (int)comobj.GetType().InvokeMember("LowPart", System.Reflection.BindingFlags.GetProperty, null, comobj, null);
                            dateTime = DateTime.FromFileTime(int.Parse("0x" + high + "" + low, System.Globalization.NumberStyles.HexNumber));
                        }
                        else
                        {
                            dateTime = DateTime.FromFileTime(long.Parse(attr.StringValue));
                        }
                        obj.lastlogoff = dateTime;
                        break;

                    case "badpasswordtime":
                        if (attr.StringValues.GetType().Name == "System.MarshalByRefObject")
                        {
                            var comobj = (MarshalByRefObject)attr.StringValues;
                            int high   = (int)comobj.GetType().InvokeMember("HighPart", System.Reflection.BindingFlags.GetProperty, null, comobj, null);
                            int low    = (int)comobj.GetType().InvokeMember("LowPart", System.Reflection.BindingFlags.GetProperty, null, comobj, null);
                            dateTime = DateTime.FromFileTime(int.Parse("0x" + high + "" + low, System.Globalization.NumberStyles.HexNumber));
                        }
                        else
                        {
                            dateTime = DateTime.FromFileTime(long.Parse(attr.StringValue));
                        }
                        obj.badpasswordtime = dateTime;
                        break;

                    default:
                    {
                        string property = "0";
                        if (attr.StringValue.GetType().Name == "System.MarshalByRefObject")
                        {
                            var comobj = (MarshalByRefObject)attr.StringValues;
                            int high   = (int)comobj.GetType().InvokeMember("HighPart", System.Reflection.BindingFlags.GetProperty, null, comobj, null);
                            int low    = (int)comobj.GetType().InvokeMember("LowPart", System.Reflection.BindingFlags.GetProperty, null, comobj, null);
                            property = int.Parse("0x" + high + "" + low, System.Globalization.NumberStyles.HexNumber).ToString();
                        }
                        else if (attr.StringValueArray.Length == 1)
                        {
                            property = attr.StringValueArray[0];
                        }
                        else
                        {
                            List <string> propertyList = new List <string>();
                            foreach (object prop in attr.StringValueArray)
                            {
                                propertyList.Add(prop.ToString());
                            }
                            property = String.Join(", ", propertyList.ToArray());
                        }
                        string attribName = attr.Name.ToLower();
                        if (attribName == "samaccountname")
                        {
                            obj.samaccountname = property;
                        }
                        else if (attribName == "distinguishedname")
                        {
                            obj.distinguishedname = property;
                        }
                        else if (attribName == "cn")
                        {
                            obj.cn = property;
                        }
                        else if (attribName == "admincount")
                        {
                            obj.admincount = property;
                        }
                        else if (attribName == "serviceprincipalname")
                        {
                            obj.serviceprincipalname = property;
                        }
                        else if (attribName == "name")
                        {
                            obj.name = property;
                        }
                        else if (attribName == "description")
                        {
                            obj.description = property;
                        }
                        else if (attribName == "memberof")
                        {
                            obj.memberof = property;
                        }
                        else if (attribName == "logoncount")
                        {
                            obj.logoncount = property;
                        }
                        else if (attribName == "badpwdcount")
                        {
                            obj.badpwdcount = property;
                        }
                        else if (attribName == "whencreated")
                        {
                            obj.whencreated = property;
                        }
                        else if (attribName == "whenchanged")
                        {
                            obj.whenchanged = property;
                        }
                        else if (attribName == "codepage")
                        {
                            obj.codepage = property;
                        }
                        else if (attribName == "objectcategory")
                        {
                            obj.objectcategory = property;
                        }
                        else if (attribName == "usnchanged")
                        {
                            obj.usnchanged = property;
                        }
                        else if (attribName == "instancetype")
                        {
                            obj.instancetype = property;
                        }
                        else if (attribName == "objectclass")
                        {
                            obj.objectclass = property;
                        }
                        else if (attribName == "iscriticalsystemobject")
                        {
                            obj.iscriticalsystemobject = property;
                        }
                        else if (attribName == "usncreated")
                        {
                            obj.usncreated = property;
                        }
                        else if (attribName == "dscorepropagationdata")
                        {
                            obj.dscorepropagationdata = property;
                        }
                        else if (attribName == "adspath")
                        {
                            obj.adspath = property;
                        }
                        else if (attribName == "countrycode")
                        {
                            obj.countrycode = property;
                        }
                        else if (attribName == "primarygroupid")
                        {
                            obj.primarygroupid = property;
                        }
                        else if (attribName == "msds_supportedencryptiontypes")
                        {
                            obj.msds_supportedencryptiontypes = property;
                        }
                        else if (attribName == "showinadvancedviewonly")
                        {
                            obj.showinadvancedviewonly = property;
                        }
                    }
                    break;
                    }
                }
                return(obj);
            }
Ejemplo n.º 22
0
        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;
            }
        }
Ejemplo n.º 23
0
    // 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);
    }
Ejemplo n.º 24
0
      /// <summary>
      /// Create a New User in the LDAP Tree
      /// </summary>
      /// <param name="dn">The New User DN</param>
      /// <param name="password">The New User Password</param>
      /// <param name="sn">New User sn</param>
      /// <param name="ldapHomeServer">New User ldapHomeServer</param>
      /// <returns>true, if the user was created. false, if the user already exists.</returns>
      public bool CreateUser(string dn, string password, string sn, string ldapHomeServer)
      {
          bool created = true;

          try
          {
              connection.Read(dn);
              created = false;
          }
          catch
          {
              UserAdd.DisplayStrings("");
              UserAdd.DisplayStrings("Attempting to create user, with the following ldif");
              UserAdd.DisplayStrings("");
              UserAdd.DisplayStrings("--------------------------------------------------");
              LdapAttributeSet attributeSet = new LdapAttributeSet();
              switch (ldapType)
              {
              case LdapDirectoryType.ActiveDirectory:
              {
                  Regex    cnRegex         = null;
                  int      AccEnable       = (int)ADS_USER_FLAGS.NORMAL_ACCOUNT | (int)ADS_USER_FLAGS.DONT_EXPIRE_PASSWD;                    // Flags set to 66048
                  string   quotedPassword  = "******"" + password + "\"";
                  char []  unicodePassword = quotedPassword.ToCharArray();
                  sbyte [] userPassword    = new sbyte[unicodePassword.Length * 2];

                  for (int i = 0; i < unicodePassword.Length; i++)
                  {
                      userPassword[i * 2 + 1] = (sbyte)(unicodePassword[i] >> 8);
                      userPassword[i * 2 + 0] = (sbyte)(unicodePassword[i] & 0xff);
                  }

                  if (dn.ToLower().StartsWith("cn="))
                  {
                      cnRegex = new Regex(@"^cn=(.*?),.*$", RegexOptions.IgnoreCase | RegexOptions.Compiled);
                  }
                  else if (dn.ToLower().StartsWith("uid="))
                  {
                      cnRegex = new Regex(@"^uid=(.*?),.*$", RegexOptions.IgnoreCase | RegexOptions.Compiled);
                  }
                  string cn = cnRegex.Replace(dn, "$1");

                  // create user attributes
                  UserAdd.DisplayStrings(String.Format("{0}: {1}", "dn", dn));
                  attributeSet.Add(new LdapAttribute("objectClass", "user"));
                  UserAdd.DisplayStrings(String.Format("{0}: {1}", "objectClass", "user"));
                  attributeSet.Add(new LdapAttribute("objectClass", "InetOrgPerson"));
                  UserAdd.DisplayStrings(String.Format("{0}: {1}", "objectClass", "InetOrgPerson"));
                  attributeSet.Add(new LdapAttribute("cn", cn));
                  UserAdd.DisplayStrings(String.Format("{0}: {1}", "cn", cn));
                  attributeSet.Add(new LdapAttribute("SamAccountName", cn));
                  UserAdd.DisplayStrings(String.Format("{0}: {1}", "SamAccountName", cn));
                  attributeSet.Add(new LdapAttribute("sn", sn));
                  UserAdd.DisplayStrings(String.Format("{0}: {1}", "sn", sn));
                  attributeSet.Add(new LdapAttribute("userAccountControl", AccEnable.ToString()));
                  UserAdd.DisplayStrings(String.Format("{0}: {1}", "userAccountControl", AccEnable.ToString()));
                  attributeSet.Add(new LdapAttribute("UnicodePwd", userPassword));
                  UserAdd.DisplayStrings(String.Format("{0}: {1}", "UnicodePwd", "xxxxxxx"));

                  LdapEntry entry = new LdapEntry(dn, attributeSet);
                  connection.Add(entry);
                  if (ldapHomeServer != null)
                  {
                      if (UpdateUserObject(dn, "iFolderHomeServer", ldapHomeServer, false) == false)
                      {
                          UpdateUserObject(dn, "iFolderHomeServer", ldapHomeServer, true);
                      }
                  }
                  break;
              }

              case LdapDirectoryType.eDirectory:
              {
                  // parse the cn
                  Regex cnRegex = null;
                  if (dn.ToLower().StartsWith("cn="))
                  {
                      cnRegex = new Regex(@"^cn=(.*?),.*$", RegexOptions.IgnoreCase | RegexOptions.Compiled);
                  }
                  else if (dn.ToLower().StartsWith("uid="))
                  {
                      cnRegex = new Regex(@"^uid=(.*?),.*$", RegexOptions.IgnoreCase | RegexOptions.Compiled);
                  }
                  string cn = cnRegex.Replace(dn, "$1");

                  // create user attributes
                  UserAdd.DisplayStrings(String.Format("{0}: {1}", "Dn", dn));
                  attributeSet.Add(new LdapAttribute("objectClass", "inetOrgPerson"));
                  UserAdd.DisplayStrings(String.Format("{0}: {1}", "objectClass", "inetOrgPerson"));
                  attributeSet.Add(new LdapAttribute("objectclass", "iFolderUserProvision"));
                  UserAdd.DisplayStrings(String.Format("{0}: {1}", "objectclass", "iFolderUserProvision"));
                  attributeSet.Add(new LdapAttribute("cn", cn));
                  UserAdd.DisplayStrings(String.Format("{0}: {1}", "cn", cn));
                  attributeSet.Add(new LdapAttribute("sn", sn));
                  UserAdd.DisplayStrings(String.Format("{0}: {1}", "sn", sn));
                  attributeSet.Add(new LdapAttribute("userPassword", password));
                  UserAdd.DisplayStrings(String.Format("{0}: {1}", "userPassword", "xxxxxxxx"));

                  LdapEntry entry = new LdapEntry(dn, attributeSet);
                  connection.Add(entry);
                  UpdateUserObject(dn, "objectclass", "iFolderUserProvision", false);
                  if (ldapHomeServer != null)
                  {
                      if (UpdateUserObject(dn, "iFolderHomeServer", ldapHomeServer, false) == false)
                      {
                          UpdateUserObject(dn, "iFolderHomeServer", ldapHomeServer, true);
                      }
                  }
                  break;
              }

              case LdapDirectoryType.OpenLDAP:
              {
                  Regex  uidRegex = new Regex(@"^(.*?)=(.*?),.*$", RegexOptions.IgnoreCase | RegexOptions.Compiled);
                  string uid      = uidRegex.Replace(dn, "$2");

                  // I think we can get away with just creating an inetOrgPerson ...
                  // we don't need a posixAccount ... hmm, maybe a shadowAccount
                  // so that the password can expire?
                  attributeSet.Add(new LdapAttribute("objectClass", "inetOrgPerson"));                              //new string[]{"inetOrgPerson", "posixAccount", "shadowAccount"}));
                  UserAdd.DisplayStrings(String.Format("{0}: {1}", "Dn", dn));
                  attributeSet.Add(new LdapAttribute("uid", uid));
                  UserAdd.DisplayStrings(String.Format("{0}: {1}", "uid", uid));
                  attributeSet.Add(new LdapAttribute("cn", uid));
                  UserAdd.DisplayStrings(String.Format("{0}: {1}", "cn", uid));
                  attributeSet.Add(new LdapAttribute("sn", sn));
                  UserAdd.DisplayStrings(String.Format("{0}: {1}", "sn", sn));
                  attributeSet.Add(new LdapAttribute("givenName", uid));
                  UserAdd.DisplayStrings(String.Format("{0}: {1}", "givenName", uid));
                  attributeSet.Add(new LdapAttribute("displayName", uid));
                  UserAdd.DisplayStrings(String.Format("{0}: {1}", "displayName", uid));
                  attributeSet.Add(new LdapAttribute("objectclass", "iFolderUserProvision"));
                  // TODO: Need to encrypt the password first.
                  attributeSet.Add(new LdapAttribute("userPassword", password));
                  UserAdd.DisplayStrings(String.Format("{0}: {1}", "userPassword", "xxxxxxx"));

                  LdapEntry entry = new LdapEntry(dn, attributeSet);
                  connection.Add(entry);
                  UpdateUserObject(dn, "objectclass", "iFolderUserProvision", false);
                  if (ldapHomeServer != null)
                  {
                      if (UpdateUserObject(dn, "iFolderHomeServer", ldapHomeServer, false) == false)
                      {
                          UpdateUserObject(dn, "iFolderHomeServer", ldapHomeServer, true);
                      }
                  }
                  break;
              }
              }

              UserAdd.DisplayStrings("");
              UserAdd.DisplayStrings("--------------------------------------------------");
          }

          // result
          return(created);
      }
Ejemplo n.º 25
0
        public bool SearchUser(Models.Environment enviro, ref User user)
        {
            bool rval = false;

            try
            {
                string server = "", bindPwd = "";
                switch (enviro)
                {
                case Models.Environment.QA:
                    server  = GetStringValue("S_ldap_ED_server_QA");
                    bindPwd = GetStringValue("S_ldap_ED_bindPwd_QA");
                    break;

                case Models.Environment.Dev:
                    server  = GetStringValue("S_ldap_ED_server_Dev");
                    bindPwd = GetStringValue("S_ldap_ED_bindPwd_Dev");
                    break;

                default:     // Prod
                    server  = GetStringValue("S_ldap_ED_server");
                    bindPwd = GetStringValue("S_ldap_ED_bindPwd");
                    break;
                }
                ILdapConnection ldapConn = new LdapConnection()
                {
                    SecureSocketLayer = GetBoolValue("S_ldap_ED_isSSL")
                };
                ldapConn.Connect(server, GetIntValue("S_ldap_ED_port"));
                ldapConn.Bind(GetStringValue("S_ldap_ED_bindName"), bindPwd);

                string            userSearch = String.Format(GetStringValue("S_ldap_ED_userNameFrmt"), user.login_id);
                string            baseSearch = ""; // "ou=People,o=eaton.com";
                LdapSearchResults search     = ldapConn.Search(baseSearch, LdapConnection.SCOPE_SUB, userSearch, null, false);
                if (search != null)                // && search.Count > 0)
                {
                    LdapEntry le = search.First <LdapEntry>();
                    if (le != null)
                    {
                        string           name = le.DN;
                        LdapAttributeSet set  = le.getAttributeSet();
                        if (set != null)
                        {
                            IEnumerator ienum = set.GetEnumerator();
                            while (ienum.MoveNext())
                            {
                                LdapAttribute attribute     = (LdapAttribute)ienum.Current;
                                string        attributeName = attribute.Name;
                                string        attributeVal  = attribute.StringValue;

                                if (String.Compare(attributeName, GetStringValue("S_ED_FirstName"), true) == 0)
                                {
                                    user.first_name = attributeVal;
                                }
                                else if (String.Compare(attributeName, GetStringValue("S_ED_LastName"), true) == 0)
                                {
                                    user.last_name = attributeVal;
                                }
                                else if (String.Compare(attributeName, GetStringValue("S_ED_Email"), true) == 0)
                                {
                                    user.email = attributeVal;
                                }
                                else
                                {
                                    user.attributes.Add(attributeName, attributeVal);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Trace.WriteLine("Exception in SearchUser(), details: " + ex.ToString());
                throw ex;
            }
            return(rval);
        }
Ejemplo n.º 26
0
      /// <summary>
      /// Queries to find the type of directory
      /// </summary>
      /// <returns>The LDAP directory type.</returns>
      public LdapDirectoryType QueryDirectoryType()
      {
          LdapAttribute     attr       = null;
          LdapEntry         entry      = null;
          bool              eDirectory = false;
          LdapSearchResults lsc        = connection.Search("",
                                                           LdapConnection.SCOPE_BASE,
                                                           "objectClass=*",
                                                           null,
                                                           false);

          UserAdd.DisplayStrings(String.Format(""));
          UserAdd.DisplayStrings(String.Format("============="));
          while (lsc.hasMore())
          {
              entry = null;
              try
              {
                  entry = lsc.next();
              }
              catch (LdapException e)
              {
                  Console.WriteLine("Error: " + e.LdapErrorMessage);
                  continue;
              }
              UserAdd.DisplayStrings(String.Format("Entry DN: {0} ", entry.DN));
              LdapAttributeSet attributeSet        = entry.getAttributeSet();
              System.Collections.IEnumerator ienum = attributeSet.GetEnumerator();

              while (ienum.MoveNext())
              {
                  attr = (LdapAttribute)ienum.Current;
                  string attributeName = attr.Name;
                  string attributeVal  = attr.StringValue;
                  UserAdd.DisplayStrings(String.Format("{0}: {1}", attributeName, attributeVal));

                  if (String.Equals(attributeVal, "Novell, Inc.") == true)
                  {
                      eDirectory = true;
                      UserAdd.DisplayStrings(String.Format("Directory Type: {0} ", "Novell eDirectory"));
                      break;
                  }
              }
          }

          if (eDirectory == true)
          {
              ldapType = LdapDirectoryType.eDirectory;
          }
          else
          {
              entry = connection.Read("");
              attr  = entry.getAttribute("defaultNamingContext");
              if (attr != null)
              {
                  UserAdd.DisplayStrings(String.Format("Directory Type: {0} ", "Active Directory"));
                  ldapType = LdapDirectoryType.ActiveDirectory;
              }
              else
              {
                  UserAdd.DisplayStrings(String.Format("Directory Type: {0} ", "OpenLdap Directory"));
                  ldapType = LdapDirectoryType.OpenLDAP;
              }
          }

          UserAdd.DisplayStrings(String.Format("============="));
          UserAdd.DisplayStrings(String.Format(""));
          return(ldapType);
      }
Ejemplo n.º 27
0
        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;
            }
        }
Ejemplo n.º 28
0
 public LdapOrganization(LdapAttributeSet attributeSet)
     : base(attributeSet)
 {
     OrganizationUnit = attributeSet.getAttribute("ou")?.StringValue;
 }
 private static void AssertSameAs(this LdapAttributeSet expectedAttributeSet, LdapAttributeSet actualAttributeSet)
 {
     AssertSameAs(expectedAttributeSet, actualAttributeSet, new List <string>());
 }
        public static void MainTest(string[] args)
        {
            if (args.Length != 6)
            {
                Console.WriteLine("Usage:   mono GetAttributeSchema <host name> <ldap port>  <login dn>" + " <password> <search base>" + " <search filter>");
                Console.WriteLine("Example: mono GetAttributeSchema 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);
                LdapSchema        dirschema = conn.FetchSchema(conn.GetSchemaDN());
                LdapSearchResults lsc       = conn.Search(searchBase,
                                                          LdapConnection.SCOPE_ONE,
                                                          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\n\n");
                    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;
                        Console.WriteLine(attributeName + ":  " + dirschema.getAttributeSchema(attributeName).ToString());
                    }
                }
                conn.Disconnect();
            }
            catch (LdapException e)
            {
                Console.WriteLine("Error:" + e.LdapErrorMessage);
                return;
            }
            catch (Exception e)
            {
                Console.WriteLine("Error:" + e.Message);
                return;
            }
        }