Esempio n. 1
2
    // 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;
    }
        // Constructor
        public PSearchEventSource(
            LdapConnection conn,
            string searchBase,
            int scope,
            string filter,
            string[] attrs,
            bool typesOnly,
            LdapSearchConstraints constraints,
            LdapEventType eventchangetype,
            bool changeonly
            )
        {
            // validate the input arguments
              if ((conn == null)
              || (searchBase == null)
              || (filter == null)
              || (attrs == null))
              {
            throw new ArgumentException("Null argument specified");
              }

              mConnection = conn;
              mSearchBase = searchBase;
              mScope = scope;
              mFilter = filter;
              mAttrs = attrs;
              mTypesOnly = typesOnly;
              mEventChangeType = eventchangetype;

              // make things ready for starting a search operation
              if (constraints == null)
              {
            mSearchConstraints = new LdapSearchConstraints();
              }
              else
              {
            mSearchConstraints = constraints;
              }

              //Create the persistent search control
              LdapPersistSearchControl psCtrl =
            new LdapPersistSearchControl((int)eventchangetype,// any change
                     changeonly, //only get changes
                     true, //return entry change controls
                     true); //control is critcal

              // add the persistent search control to the search constraints
              mSearchConstraints.setControls(psCtrl);
        }
Esempio n. 3
0
    public static void doCleanup(LdapConnection conn, System.String userdn, System.String groupdn)
    {
        // since we have modified the user's attributes and failed to
        // modify the group's attribute, we need to delete the modified
        // user's attribute values.

        // modifications for user
        LdapModification[] modUser = new LdapModification[2];

        // Delete the groupdn from the user's attributes
        LdapAttribute membership = new LdapAttribute("groupMembership", groupdn);
        modUser[0] = new LdapModification(LdapModification.DELETE, membership);
        LdapAttribute security = new LdapAttribute("securityEquals", groupdn);
        modUser[1] = new LdapModification(LdapModification.DELETE, security);

        try
        {
            // Modify the user's attributes
            conn.Modify(userdn, modUser);

            System.Console.Out.WriteLine("Deleted the modified user's attribute values.");
        }
        catch (LdapException e)
        {
            System.Console.Out.WriteLine("Could not delete modified user's attributes: " + e.LdapErrorMessage);
        }
        catch(Exception e)
        {
            Console.WriteLine("Error:" + e.Message);
            return;
        }

        return ;
    }
Esempio n. 4
0
        public EdirEventSource(EdirEventSpecifier[] specifier, LdapConnection conn)
        {
            if ((null == specifier) || (null == conn))
            throw new ArgumentException("Null argument specified");

              mRequestOperation = new MonitorEventRequest(specifier);
              mConnection = conn;
        }
    /**
     *
     * Constructs an extended operation object for getting data about any Object
     * and make a call to ld.ExtendedOperation to get the response <br>
     *
     */
    public static ArrayList backup(LdapConnection ld, String objectDN,
        byte[] passwd, String stateInfo)
    {
        int intInfo;
        String strInfo;
        byte[] returnedBuffer; //Actual data blob returned as byte[]
        ArrayList objectBuffer = new ArrayList(4);
        objectBuffer.Insert(0, new Integer32(-1)); //Mark the rc default as failed backup
        try
        {
            LdapExtendedOperation request = new LdapBackupRequest(objectDN,
                    passwd, stateInfo);

            LdapExtendedResponse response = ld.ExtendedOperation(request);

            int result = response.ResultCode;
            objectBuffer.Remove(0);
            objectBuffer.Insert(0, new Integer32(result));

            if ((result == LdapException.SUCCESS) && (response is LdapBackupResponse))
            {
                Console.WriteLine("Backup Info:");

                strInfo = ((LdapBackupResponse) response).getStatusInfo();
                Console.WriteLine("    Status Info: " + strInfo);

                intInfo = ((LdapBackupResponse) response).getBufferLength();
                Console.WriteLine("    Buffer length: " + intInfo);
                objectBuffer.Insert(1, new Integer32(intInfo));

                strInfo = ((LdapBackupResponse) response).getChunkSizesString();
                Console.WriteLine("    Chunk sizes: " + strInfo);
                objectBuffer.Insert(2, strInfo);

                returnedBuffer = ((LdapBackupResponse) response).getReturnedBuffer();
                objectBuffer.Insert(3, returnedBuffer);

                Console.WriteLine("\nInformation backed up successfully\n");

            }
            else
            {
                Console.WriteLine("Could not backup the information.\n");
                throw new LdapException(response.ErrorMessage, response.ResultCode, (String) null);
            }

        }
        catch (LdapException e)
        {
            Console.WriteLine("Error: " + e.ToString());
        }
        catch (System.Exception e)
        {
            Console.WriteLine("Error: " + e.ToString());
        }
        return objectBuffer;
    }
Esempio n. 6
0
    public static void Main(System.String[] args)
    {
        if (args.Length != 5)
        {
            System.Console.Out.WriteLine("Usage:   mono VerifyPassword <host name>" + " <login dn> <password> <object dn>\n" + "         <test password>");
            System.Console.Out.WriteLine("Example: mono VerifyPassword Acme.com " + "\"cn=Admin,o=Acme\" secret\n" + "         \"cn=JSmith,ou=Sales,o=Acme\" testPassword");
            System.Environment.Exit(0);
        }

        int ldapPort = LdapConnection.DEFAULT_PORT;
        int ldapVersion = LdapConnection.Ldap_V3;
        System.String ldapHost = args[0];
        System.String loginDN = args[1];
        System.String password = args[2];
        System.String objectDN = args[3];
        System.String testPassword = args[4];
        LdapConnection conn = new LdapConnection();

        try
        {
            // connect to the server
            conn.Connect(ldapHost, ldapPort);

            // authenticate to the server
            conn.Bind(ldapVersion, loginDN, password);

            LdapAttribute attr = new LdapAttribute("userPassword", testPassword);
            bool correct = conn.Compare(objectDN, attr);

            System.Console.Out.WriteLine(correct?"The password is correct.":"The password is incorrect.\n");

            // disconnect with the server
            conn.Disconnect();
        }
        catch (LdapException e)
        {
            if (e.ResultCode == LdapException.NO_SUCH_OBJECT)
            {
                System.Console.Error.WriteLine("Error: No such entry");
            }
            else if (e.ResultCode == LdapException.NO_SUCH_ATTRIBUTE)
            {
                System.Console.Error.WriteLine("Error: No such attribute");
            }
            else
            {
                System.Console.Error.WriteLine("Error: " + e.ToString());
            }
        }
        catch (System.IO.IOException e)
        {
            System.Console.Out.WriteLine("Error: " + e.ToString());
        }
        System.Environment.Exit(0);
    }
Esempio n. 7
0
    // findACLValues() reads the entry to get it's ACL values
    public static void findACLValues(LdapConnection lc, String entry)
    {
        String[] returnAttrs = { "acl" };
        String attributeName;
        IEnumerator allValues;
        LdapAttribute attribute;
        LdapAttributeSet attributeSet;

        try
        {
            LdapEntry aclList = lc.Read( entry, returnAttrs );

            // printout entryDN's ACL values
            attributeSet = aclList.getAttributeSet();
            IEnumerator allAttributes = attributeSet.GetEnumerator();

            Console.WriteLine("    =========================================");
            Console.WriteLine("    entryDN's ACL values after modification:");
            Console.WriteLine("    =========================================");
            if (allAttributes.MoveNext())
            {
                attribute = (LdapAttribute)allAttributes.Current;
                attributeName = attribute.Name;
                allValues = attribute.StringValues;
                while(allValues.MoveNext())
                {
                    PrintACLValue((String)allValues.Current);
                }
            }
        }
        catch( LdapException e )
        {
            Console.WriteLine( "Error: ModdifyACL, " + e.ToString() );
            Environment.Exit(1);
        }
    }
Esempio n. 8
0
        private bool BindLdap(NetworkCredential creds, ContextOptions contextOptions)
        {
            LdapConnection current = null;
            bool           useSSL  = (ContextOptions.SecureSocketLayer & contextOptions) > 0;

            if (_contextType == ContextType.ApplicationDirectory)
            {
                _directoryIdent = new LdapDirectoryIdentifier(_serverProperties.dnsHostName, useSSL ? _serverProperties.portSSL : _serverProperties.portLDAP);
            }
            else
            {
                _directoryIdent = new LdapDirectoryIdentifier(_serverName, useSSL ? LdapConstants.LDAP_SSL_PORT : LdapConstants.LDAP_PORT);
            }

            bool attemptFastConcurrent = useSSL && _fastConcurrentSupported;
            int  index = Convert.ToInt32(attemptFastConcurrent) * 2 + Convert.ToInt32(useSSL);

            if (!_connCache.Contains(index))
            {
                lock (_cacheLock)
                {
                    if (!_connCache.Contains(index))
                    {
                        current = new LdapConnection(_directoryIdent);
                        // First attempt to turn on SSL
                        current.SessionOptions.SecureSocketLayer = useSSL;

                        if (attemptFastConcurrent)
                        {
                            try
                            {
                                current.SessionOptions.FastConcurrentBind();
                            }
                            catch (PlatformNotSupportedException)
                            {
                                current.Dispose();
                                current = null;
                                _fastConcurrentSupported = false;
                                index   = Convert.ToInt32(useSSL);
                                current = new LdapConnection(_directoryIdent);
                                // We have fallen back to another connection so we need to set SSL again.
                                current.SessionOptions.SecureSocketLayer = useSSL;
                            }
                        }

                        _connCache.Add(index, current);
                    }
                    else
                    {
                        current = (LdapConnection)_connCache[index];
                    }
                }
            }
            else
            {
                current = (LdapConnection)_connCache[index];
            }

            // If we are performing fastConcurrentBind there is no need to prevent multithreadaccess.  FSB is thread safe and multi cred safe
            // FSB also always has the same contextoptions so there is no need to lock the code that is modifying the current connection
            if (attemptFastConcurrent && _fastConcurrentSupported)
            {
                lockedLdapBind(current, creds, contextOptions);
            }
            else
            {
                lock (_cacheLock)
                {
                    lockedLdapBind(current, creds, contextOptions);
                }
            }
            return(true);
        }
Esempio n. 9
0
        static void Main(string[] args)
        {
            // https://www.forumsys.com/tutorials/integration-how-to/ldap/online-ldap-test-server/
            int    ldapPort    = LdapConnection.DEFAULT_PORT;
            int    ldapVersion = LdapConnection.Ldap_V3;
            string ldapHost    = "ldap.forumsys.com";
            var    loginDN     = "cn=read-only-admin,dc=example,dc=com";
            var    password    = "******";

            string searchLdapUser = "******";

            string searchFilter = "(objectclass=*)";
            string searchBase   = $"uid={searchLdapUser}, dc=example, dc=com"; // "ou = scientists, dc = example, dc = com"; //"uid=gauss, dc=example, dc=com";

            LdapSearchConstraints constraints = new LdapSearchConstraints {
            };

            var users = new HashSet <string>();

            try
            {
                using (var cn = new LdapConnection())
                {
                    // connect
                    cn.Connect(ldapHost, ldapPort);
                    cn.Bind(loginDN, password);

                    LdapSearchResults searchResults = cn.Search(
                        searchBase,
                        LdapConnection.SCOPE_SUB,
                        searchFilter,
                        null, // no specified attributes
                        true, // false = return attr and value
                        constraints);


                    while (searchResults.HasMore())
                    {
                        if (searchResults.Count == 1)
                        {
                            Console.WriteLine("true - found");
                        }
                        searchResults.Next();
                    }
                }
            }
            catch (LdapException ldapEx)
            {
                Console.WriteLine(ldapEx.ToString()); // ocassional time outs
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }

            foreach (var u in users)
            {
                Console.WriteLine("Key:" + u);
            }
            Console.ReadKey();
        }
Esempio n. 10
0
 /// <summary>
 /// Disconnect from the LDAP Server
 /// </summary>
 public void Disconnect()
 {
     connection.Disconnect();
     connection = null;
 }
Esempio n. 11
0
    public static void Main(System.String[] args)
    {
        /* Check if we have the correct number of command line arguments */
        if (args.Length != 4)
        {
            System.Console.Error.WriteLine("Usage:   mono VLVControl <host name> <login dn>" + " <password> <container>");
            System.Console.Error.WriteLine("Example: mono VLVControl Acme.com \"cn=admin,o=Acme\" secret" + " \"ou=Sales,o=Acme\"");
            System.Environment.Exit(1);
        }

        /* Parse the command line arguments  */
        System.String LdapHost = args[0];
        System.String loginDN = args[1];
        System.String password = args[2];
        System.String searchBase = args[3];
        int LdapPort = LdapConnection.DEFAULT_PORT;
        int LdapVersion = LdapConnection.Ldap_V3;
        LdapConnection conn = new LdapConnection();

        try
        {
            // connect to the server
            conn.Connect(LdapHost, LdapPort);
            // bind to the server
            conn.Bind(LdapVersion, loginDN, password);
            System.Console.Out.WriteLine("Succesfully logged in to server: " + LdapHost);

            /* Set default filter - Change this line if you need a different set
            * of search restrictions. Read the "NDS and Ldap Integration Guide"
            * for information on support by Novell eDirectory of this
            * functionaliry.
            */
            System.String MY_FILTER = "cn=*";

            /* We are requesting that the givenname and cn fields for each
            * object be returned
            */
            System.String[] attrs = new System.String[2];
            attrs[0] = "givenname";
            attrs[1] = "cn";

            // We will be sending two controls to the server
            LdapControl[] requestControls = new LdapControl[2];

            /* Create the sort key to be used by the sort control
            * Results should be sorted based on the cn attribute.
            * See the "NDS and Ldap Integration Guide" for information on
            * Novell eDirectory support of this functionaliry.
            */
            LdapSortKey[] keys = new LdapSortKey[1];
            keys[0] = new LdapSortKey("cn");

            // Create the sort control
            requestControls[0] = new LdapSortControl(keys, true);

            /* Create the VLV Control.
            * These two fields in the VLV Control identify the before and
            * after count of entries to be returned
            */
            int beforeCount = 0;
            int afterCount = 2;

            /* The VLV control request can specify the index
            * using one of the two methods described below:
            *
            * TYPED INDEX: Here we request all objects that have cn greater
            * than or equal to the letter "a"
            */
            requestControls[1] = new LdapVirtualListControl("a", beforeCount, afterCount);

            /* The following code needs to be enabled to specify the index
            * directly
            *   int offset = 0; - offset of the index
            *   int contentCount = 3; - our estimate of the search result size
            *   requestControls[1] = new LdapVirtualListControl(offset,
            *                          beforeCount, afterCount, contentCount);
            */

            // Set the controls to be sent as part of search request
            LdapSearchConstraints cons = conn.SearchConstraints;
            cons.setControls(requestControls);
            conn.Constraints = cons;

            // Send the search request - Synchronous Search is being used here
            System.Console.Out.WriteLine("Calling Asynchronous Search...");
            LdapSearchResults res = conn.Search(searchBase, LdapConnection.SCOPE_SUB, MY_FILTER, attrs, false, (LdapSearchConstraints) null);

            // Loop through the results and print them out
            while (res.hasMore())
            {

                /* Get next returned entry.  Note that we should expect a Ldap-
                *Exception object as well just in case something goes wrong
                */
                LdapEntry nextEntry=null;
                try
                {
                    nextEntry = res.next();
                }
                catch (LdapException e)
                {
                    if (e is LdapReferralException)
                        continue;
                    else
                    {
                        System.Console.Out.WriteLine("Search stopped with exception " + e.ToString());
                        break;
                    }
                }

                /* Print out the returned Entries distinguished name.  */
                System.Console.Out.WriteLine();
                System.Console.Out.WriteLine(nextEntry.DN);

                /* Get the list of attributes for the current entry */
                LdapAttributeSet findAttrs = nextEntry.getAttributeSet();

                /* Convert attribute list to Enumeration */
                System.Collections.IEnumerator enumAttrs = findAttrs.GetEnumerator();
                System.Console.Out.WriteLine("Attributes: ");

                /* Loop through all attributes in the enumeration */
                while (enumAttrs.MoveNext())
                {

                    LdapAttribute anAttr = (LdapAttribute) enumAttrs.Current;

                    /* Print out the attribute name */
                    System.String attrName = anAttr.Name;
                    System.Console.Out.WriteLine("" + attrName);

                    // Loop through all values for this attribute and print them
                    System.Collections.IEnumerator enumVals = anAttr.StringValues;
                    while (enumVals.MoveNext())
                    {
                        System.String aVal = (System.String) enumVals.Current;
                        System.Console.Out.WriteLine("" + aVal);
                    }
                }
            }

            // Server should send back a control irrespective of the
            // status of the search request
            LdapControl[] controls = res.ResponseControls;
            if (controls == null)
            {
                System.Console.Out.WriteLine("No controls returned");
            }
            else
            {

                // We are likely to have multiple controls returned
                for (int i = 0; i < controls.Length; i++)
                {

                    /* Is this the Sort Response Control. */
                    if (controls[i] is LdapSortResponse)
                    {

                        System.Console.Out.WriteLine("Received Ldap Sort Control from " + "Server");

                        /* We could have an error code and maybe a string
                        * identifying erring attribute in the response control.
                        */
                        System.String bad = ((LdapSortResponse) controls[i]).FailedAttribute;
                        int result = ((LdapSortResponse) controls[i]).ResultCode;

                        // Print out error code (0 if no error) and any
                        // returned attribute
                        System.Console.Out.WriteLine("Error code: " + result);
                        if ((System.Object) bad != null)
                            System.Console.Out.WriteLine("Offending " + "attribute: " + bad);
                        else
                            System.Console.Out.WriteLine("No offending " + "attribute " + "returned");
                    }

                    /* Is this a VLV Response Control */
                    if (controls[i] is LdapVirtualListResponse)
                    {

                        System.Console.Out.WriteLine("Received VLV Response Control from " + "Server...");

                        /* Get all returned fields */
                        int firstPosition = ((LdapVirtualListResponse) controls[i]).FirstPosition;
                        int ContentCount = ((LdapVirtualListResponse) controls[i]).ContentCount;
                        int resultCode = ((LdapVirtualListResponse) controls[i]).ResultCode;
                        System.String context = ((LdapVirtualListResponse) controls[i]).Context;

                        /* Print out the returned fields.  Typically you would
                        * have used these fields to reissue another VLV request
                        * or to display the list on a GUI
                        */
                        System.Console.Out.WriteLine("Result Code    => " + resultCode);
                        System.Console.Out.WriteLine("First Position => " + firstPosition);
                        System.Console.Out.WriteLine("Content Count  => " + ContentCount);
                        if ((System.Object) context != null)
                            System.Console.Out.WriteLine("Context String => " + context);
                        else
                            System.Console.Out.WriteLine("No Context String in returned" + " control");
                    }
                }
            }

            /* We are done - disconnect */
            if (conn.Connected)
                conn.Disconnect();
        }
        catch (LdapException e)
        {
            System.Console.Out.WriteLine(e.ToString());
        }
        catch (System.IO.IOException e)
        {
            System.Console.Out.WriteLine("Error: " + e.ToString());
        }
        catch(Exception e)
        {
            System.Console.WriteLine("Error: " + e.Message);
        }
    }
Esempio n. 12
0
        public void BeginSendRequest_InvalidPartialMode_ThrowsInvalidEnumArgumentException(PartialResultProcessing partialMode)
        {
            var connection = new LdapConnection("server");

            AssertExtensions.Throws <InvalidEnumArgumentException>("partialMode", () => connection.BeginSendRequest(new AddRequest(), partialMode, null, null));
        }
Esempio n. 13
0
        public void Abort_InvalidAsyncResult_ThrowsArgumentNullException()
        {
            var connection = new LdapConnection("server");

            Assert.Throws <ArgumentException>(null, () => connection.Abort(new CustomAsyncResult()));
        }
Esempio n. 14
0
    public static void Main( String[] args )
    {
        if (args.Length != 6)
        {
            Console.Error.WriteLine("Usage:   mono SimplePassword <host Name> "
                + "<port number> <login dn> <password> <user dn>"
                + " <new user password>");
            Console.Error.WriteLine("\n Example: mono SimplePassword Acme.com 389"
                + " \"cn=Admin,o=Acme\" secret\n"
                + "         \"cn=JSmith,ou=sales,o=Acme\" userPWD");
            Environment.Exit(1);
        }

        int    ldapVersion = LdapConnection.Ldap_V3;
        String ldapHost    = args[0];
        int    ldapPort    = int.Parse(args[1]);
        String loginDN     = args[2];
        String password    = args[3];
        String userDN      = args[4];
        String userPWD     = args[5];

        /* Simple Password control.  There is no value  associated with this control,
         * just an OID and criticality. Setting the criticality to TRUE means the
         * server will return an error if it does not recognize or is unable to
         * perform the control.
         */

        LdapControl cont = new LdapControl(simplePassOID,
            true,
            null);
        LdapConstraints lcons = new LdapConstraints();
        lcons.setControls(cont);

        LdapConnection lc  = new LdapConnection();

        try
        {
            // connect to the server
            lc.Connect( ldapHost, ldapPort );
            // bind to the server
            lc.Bind( ldapVersion, loginDN, password );

            //  Modify the 'userpassword' attribute, with the Simple
            // Password control.
            LdapModification[] modifications = new LdapModification[1];
            LdapAttribute sPassword = new LdapAttribute( "userPassword",userPWD);
            modifications[0] =
                new LdapModification( LdapModification.REPLACE, sPassword);

            lc.Modify( userDN, modifications,lcons);

            Console.WriteLine("Your Simple password has been modified.");

            lc.Disconnect();
        }
        catch( LdapException e )
        {
            Console.Error.WriteLine("SimplePassword example failed");
            Console.Error.WriteLine( "Error: " + e.ToString() );
            Environment.Exit(1);
        }
        catch( Exception e )
        {
            Console.WriteLine( "Error: " + e.ToString() );
        }
        Environment.Exit(0);
    }
Esempio n. 15
0
    public static void Main( String[] args )
    {
        if (args.Length != 6)
        {
            Console.Error.WriteLine("Usage:   mono DynamicGroup <host name>"
                + " <port number> <login dn> <password> <container name>"
                + " <queryURL>");
            Console.Error.WriteLine("Example: mono DynamicGroup Acme.com"
                + " 389 \"cn=admin, o=Acme\" secret \"o=Acme\" \n             "
                + " Ldap:///ou=Sales,o=Acme??sub?(title=*Manager*)\n");
            Environment.Exit(1);
        }

        // Set Ldap version to 3 */
        int LdapVersion  = LdapConnection.Ldap_V3;

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

        /* Construct the entry's dn using the container name from the
         * command line and the name of the new dynamic group entry to create.
         */
        String dn = "cn=myDynamicGroup," + containerName;

        LdapConnection lc = new LdapConnection();

        try
        {
            if(ldapPort == LdapConnection.DEFAULT_SSL_PORT)
                lc.SecureSocketLayer = true;
            // connect to the server
            lc.Connect( ldapHost, ldapPort );
            // bind to the server
            lc.Bind( LdapVersion, loginDN, password );

            // Adding dynamic group entry to the tree
            Console.WriteLine( "\tAdding dynamic group entry...");

            /* add a dynamic group entry to the directory tree in the
             * specified container
             */
            addDynamicGroupEntry( lc, loginDN, dn, queryURL);

            /* Reading the member attribute of dynamic group entry and
             * printing the values
             */
            Console.WriteLine("\n\tReading the \"member\" "
                       + " attribute of dynamic group ojbect ...");
            searchDynamicGroupEntry ( lc, dn );

            // Removing the dynamic group entry from the specified container
            Console.WriteLine("\n\tDeleting dynamic group entry...");
            deleteDynamicGroupEntry( lc, dn );

            // disconnect with the server
            lc.Disconnect();
        }
        catch( LdapException e )
        {
            Console.WriteLine( "Error: " + e.ToString() );
        }
        catch( Exception e )
        {
            Console.WriteLine( "Error: " + e.ToString() );
        }
        Environment.Exit(0);
    }
Esempio n. 16
0
    // delete the  dynamic group entry
    public static bool deleteDynamicGroupEntry( LdapConnection lc,
        String deleteDN)
    {
        bool status = true;

        try
        {
            // Deletes the entry from the directory
            lc.Delete( deleteDN );
            Console.WriteLine("\tEntry: " + deleteDN + " was deleted." );
        }
        catch( LdapException e )
        {
            Console.WriteLine( "\t\tFailed to remove dynamic group entry." );
            Console.WriteLine( "Error: " + e.ToString() );
            status = false;
        }
        return status;
    }
Esempio n. 17
0
    // add dynamic group entry
    public static bool addDynamicGroupEntry( LdapConnection lc,
        String loginDN, String entryDN, String queryURL)
    {
        bool status = true;
        LdapAttributeSet  attributeSet = new LdapAttributeSet();

        //The objectclass "dynamicGroup is used to create dynamic group entries
        attributeSet.Add( new LdapAttribute( "objectclass", "dynamicGroup" ));

        /* The memberQueryURL attribute describes the membership of the list
         * using an LdapURL, which is defined in RFC2255
         */
        attributeSet.Add( new LdapAttribute( "memberQueryURL", queryURL ) );

        /* Set the identity to use for the implied search.  loginDN is used
         * as the dgIdentity in this sample.
         */
        attributeSet.Add( new LdapAttribute( "dgIdentity", loginDN ) );

        LdapEntry newEntry = new LdapEntry( entryDN, attributeSet );

        try
        {
            lc.Add( newEntry );
            Console.WriteLine("\tEntry: " + entryDN + " added successfully." );
        }
        catch( LdapException e )
        {
            Console.WriteLine( "\t\tFailed to add dynamic group entry " +
                       entryDN);
            Console.WriteLine( "Error: " + e.ToString() );
            status = false;
        }
        return status;
    }
        public DirectoryEntry Validate(string username, string password)
        {
            var config = Config.Get<Settings>();
            var directory = new LdapDirectoryIdentifier(
                config.Host,
                config.Port,
                fullyQualifiedDnsHostName: true,
                connectionless: false);

            var credential = new NetworkCredential(
                config.Username,
                config.Password);

            var ldapConnection = new LdapConnection(directory, credential)
            {
                AuthType = AuthType.Basic
            };
            try
            {
                ldapConnection.SessionOptions.ProtocolVersion = 3;

                var request = new SearchRequest(
                        config.DistinguishedName,
                        "(&(objectClass=*)(uid=" + username + "))",
                        SearchScope.Subtree,
                        new string[] { "uid", "givenName", "sn", "mail" });

                var result = (SearchResponse)ldapConnection.SendRequest(request);

                if (result.Entries.Count == 0)
                    return null;

                var item = result.Entries[0];
                try
                {
                    ldapConnection.Bind(new NetworkCredential(item.DistinguishedName, password));
                }
                catch (Exception ex)
                {
                    Log.Error("Error authenticating user", ex, this.GetType());
                    return null;
                }

                // make sure to check these attribute names match with your LDAP attributes
                var uid = item.Attributes["uid"];
                var firstName = item.Attributes["givenName"];
                var lastName = item.Attributes["sn"];
                var email = item.Attributes["mail"];

                var entry = new DirectoryEntry
                {
                    Username = uid[0] as string,
                    FirstName = uid.Count > 0 ? firstName[0] as string : null,
                    LastName = lastName.Count > 0 ? lastName[0] as string : null,
                    Email = email.Count > 0 ? email[0] as string : null
                };

                return entry;
            }
            finally
            {
                try
                {
                    ldapConnection.Dispose();
                }
                catch
                {
                }
            }
        }
Esempio n. 19
0
        static void Main(string[] args)
        {
            string        ldapServer      = getLdapServer();
            List <string> authorizedUsers = new List <string>();

            authorizedUsers.Add("zzzttrent");
            authorizedUsers.Add("ttrent");

            Dictionary <string, string> ldapErrors = new Dictionary <string, string>();

            ldapErrors.Add("52e", "Username or Password incorrect");
            ldapErrors.Add("530", "User Account not permitted to logon during this time");
            ldapErrors.Add("531", "User Account not permitted to logon at this computer");
            ldapErrors.Add("532", "User Account password expired");
            ldapErrors.Add("533", "User Account disabled");
            ldapErrors.Add("701", "User Account expired");
            ldapErrors.Add("773", "User Account password must be reset");
            ldapErrors.Add("775", "User Account Locked");

            Console.Write("Enter username: "******"Enter password: "******"";

            ConsoleKeyInfo info = Console.ReadKey(true);

            while (info.Key != ConsoleKey.Enter)
            {
                string asterisks = generateAsterisks();
                if (info.Key != ConsoleKey.Backspace)
                {
                    Console.Write(asterisks);
                    password += info.KeyChar;
                    info      = Console.ReadKey(true);
                }
                else if (info.Key == ConsoleKey.Backspace)
                {
                    int cursorPosition = Console.CursorLeft;
                    if (cursorPosition != 16)
                    {
                        Console.Write("\b\0\b");
                    }

                    if (!string.IsNullOrEmpty(password))
                    {
                        password = password.Substring
                                       (0, password.Length - 1);
                    }
                    info = Console.ReadKey(true);
                }
            }

            if (authorizedUsers.Contains(username))
            {
                try
                {
                    LdapConnection    connection = new LdapConnection(ldapServer);
                    NetworkCredential credential = new NetworkCredential(username, password);
                    connection.Credential = credential;
                    connection.Bind();
                    Console.WriteLine("\nlogged in");
                }
                catch (LdapException lexc)
                {
                    string error        = lexc.ServerErrorMessage;
                    string errorcode    = error.Substring(77, 3);
                    string errorMessage = ldapErrors[errorcode];
                    Console.WriteLine($"\n{errorMessage}");
                }
            }
            else
            {
                Console.WriteLine("Sorry, you are not authorized to log in.");
            }
        }
Esempio n. 20
0
        public void Timeout_SetInvalid_ThrowsArgumentException(long totalSeconds)
        {
            var connection = new LdapConnection("server");

            AssertExtensions.Throws <ArgumentException>("value", () => connection.Timeout = TimeSpan.FromSeconds(totalSeconds));
        }
Esempio n. 21
0
        static LdapConnection CreateConnection(LdapDirectoryIdentifier server)
        {
            LdapConnection connect = new LdapConnection(server);

            return(connect);
        }
Esempio n. 22
0
        public void BeginSendRequest_NotifyCallbackAndNullCallback_ThrowsArgumentException()
        {
            var connection = new LdapConnection("server");

            AssertExtensions.Throws <ArgumentException>("callback", () => connection.BeginSendRequest(new SearchRequest(), PartialResultProcessing.ReturnPartialResultsAndNotifyCallback, null, null));
        }
Esempio n. 23
0
        public static int Main(string[] args)
        {
            try     {
                Version v = Assembly.GetExecutingAssembly().GetName().Version;
                //fill list of arguments
                _arguments = new List <string>();

                foreach (string arg in args)
                {
                    _arguments.Add(arg.Replace("\"", string.Empty));
                }

                // some fancy window title
                Console.Title = string.Format("LDAP2CSV v{0}.{1}.{2}", v.Major, v.Minor, v.Build);

                //want to create a lcv file? exit after job is done
                if (_arguments.Contains("-c"))
                {
                    Crypto.Protect(_arguments[_arguments.IndexOf("-c") + 1]);
                    return(0);
                }

                //messing around with parameters? dont try
                if (_arguments.Contains("-u") && !_arguments.Contains("-p"))
                {
                    throw new ArgumentException("-u and -p parameter must be specified in conjuction");
                }

                // check existance of desirend amount of parameters at least: server:port/rootdn
                if (_arguments.Count < 1)
                {
                    Console.WriteLine(
                        "LDAP2CSV usage:\n" +
                        "\n" +
                        "ldap2csv.exe LDAP://10.0.0.4:389/ou=people,dc=example,dc=de \n -u username -p password -f (&(ou=people)) -a sn,givenName,ou " +
                        "\n -o \"D:\\Path\\To\\Destination.csv -e UTF8 -s ;\"\n" +
                        "\n" +
                        "optional parmeter -a: ldap attributes\n" +
                        "supported attributes are: comma seperated list of attributes\n" +
                        "Hint: If omitted, attribute will be set to wildcard \"*\"\n" +
                        "usage: -a sn,givenName\n" +
                        "\n" +
                        "optional parmeter -f: ldap search filter\n" +
                        "supported attributes are: standard ldap query\n" +
                        "Hint: If omitted, filter is set to \"objectClass=*\"\n" +
                        "usage: -f ou=people\n" +
                        "\n" +
                        "optional parmeter -u: username\n" +
                        "supported attributes are: ldap username\n" +
                        "Hint: refer -c and -C parameter for encrypted credentials\n" +
                        "Hint: Anonymous Login is used if -u, -p and -C are omitted\n" +
                        "usage: -u cn=admin,dc=example,dc=de\n" +
                        "\n" +
                        "optional parmeter -p: plain password\n" +
                        "supported attributes are: ldap userpassword\n" +
                        "Hint: -u parameter is mandatory if -p should be used \n" +
                        "Hint: refer -c and -C parameter for encrypted credentials\n" +
                        "usage: -p password\n" +
                        "\n" +
                        "optional parmeter -e: encoding\n" +
                        "supported attributes are: UTF8, ASCII(=ANSI) and Unicode\n" +
                        "Hint: If omitted, encoding remain system default\n" +
                        "usage: -e UTF8\n" +
                        "\n" +
                        "optional parmeter -s: csv seperator char\n" +
                        "supported attributes: maybe all ASCII characters" +
                        "Hint: If omitted, comma will be used as seperator\n" +
                        "usage: -s ;\n" +
                        "\n" +
                        "optional parmeter -v: ldap protocol version\n" +
                        "supported attributes: 2, 3\n" +
                        "Hint: If omitted, version 3 is assumed\n" +
                        "usage: -v 2\n" +
                        "\n" +
                        "optional parmeter -ssl: use ssl encryption\n" +
                        "supported attributes: none\n" +
                        "Hint: If omitted, basic authentication will be used\n" +
                        "usage: -ssl\n" +
                        "\n" +
                        "optional parmeter -tls: use tls encryption\n" +
                        "supported attributes: none\n" +
                        "Hint: If omitted, basic authentication will be used\n" +
                        "usage: -tls\n" +
                        "\n" +
                        "optional parmeter -k: use kerberos encryption\n" +
                        "supported attributes: none\n" +
                        "Hint: If omitted, basic authentication will be used\n" +
                        "usage: -k\n" +
                        "\n" +
                        "optional parmeter -t: timeout in minutes before a connection\n" +
                        "or a ldap query will raise a timeout exception\n" +
                        "supported attributes: 1 - n\n" +
                        "Hint: If omitted, timeout will be set to 10 minutes\n" +
                        "usage: -t 5\n" +
                        "\n" +
                        "optional parameter -c: encryption of credentials\n" +
                        "this will create an encrypted \"cred.lcv\" in\n" +
                        "the root directory of ldap2csv.exe where the credentials\n" +
                        "will be stored safely. May need elevated privileges \"Run As Administrator\"\n" +
                        "supported attributes: \"username|password\"\n" +
                        "Hint: Be aware to use the | character (pipe) to seperate user and password.\n" +
                        "Hint: Be aware to set the attribute in quotes.\n" +
                        "Hint: To use the created credential file see \"-C\" parameter.\n" +
                        "usage: ldap2csv.exe -c \"username|password\"\n" +
                        "\n" +
                        "optional paremeter -C: use encrypted credential file\n" +
                        "this will tell ldap2csv.exe to search for the \"cred.lcv\" file\n" +
                        "created with the -c parameter above.\n" +
                        "supported attributes: none\n" +
                        "usage: ldap2csv.exe LDAP://10.0.0.4:389/ou=people,dc=example,dc=de -C -f (&(ou=people))\n" +
                        "-a sn,givenName,ou -o D:\\Path\\To\\Destination.csv\\\n" +
                        "\nImportant: cred.lcv file is bound to the environment where it was created and could not be transferred between different machines"
                        );

                    Console.Write(
                        "\n" +
                        "Press any key to exit . . . "
                        );

                    Console.ReadKey(true);

                    return(0);
                }

                else
                {
                    try     {
                        //extract server and dn from ldap path attribute
                        string dn = _arguments[0].ToUpper().Replace("LDAP://", string.Empty)
                                    .Replace("LDAPS://", string.Empty)
                                    .Remove(0, _arguments[0].ToUpper()
                                            .Replace("LDAP://", string.Empty).Replace("LDAPS://", string.Empty)
                                            .IndexOf('/') + 1)
                                    .ToLower();

                        string server = _arguments[0].ToUpper().Replace("LDAP://", string.Empty)
                                        .Replace("LDAPS://", string.Empty)
                                        .Remove(_arguments[0].ToUpper()
                                                .Replace("LDAP://", string.Empty).Replace("LDAPS://", string.Empty)
                                                .IndexOf('/'), dn.Length + 1)
                                        .ToLower();

                        LdapDirectoryIdentifier ldapDir = new LdapDirectoryIdentifier(server);

                        //prepare output directory if -o parameter was supplied
                        if (_arguments.Contains("-o"))
                        {
                            // the argument right after the "-o" argument should be an existing directory as this will be used for the output file. create if not exists
                            if (!Directory.GetParent(_arguments[_arguments.IndexOf("-o") + 1]).Exists)
                            {
                                Directory.CreateDirectory(Directory.GetParent(_arguments[_arguments.IndexOf("-o") + 1]).ToString());
                            }

                            // try to remove previous csv file if it exists
                            if (File.Exists(_arguments[_arguments.IndexOf("-o") + 1]))
                            {
                                try     {
                                    File.Delete(_arguments[_arguments.IndexOf("-o") + 1]);
                                }
                                catch (Exception ex) {
                                    LogWriter.CreateLogEntry(string.Format("ERROR:{0} {1}", ex.Message, (ex.InnerException != null) ? ex.InnerException.Message : string.Empty));
                                }
                            }
                        }

                        using (LdapConnection ldapConnection = CreateConnection(ldapDir))
                        {
                            //use ssl?
                            ldapConnection.SessionOptions.SecureSocketLayer = _arguments.Contains("-ssl") ? true : false;

                            //use tls?
                            if (_arguments.Contains("-tls") && !_arguments.Contains("-ssl"))
                            {
                                ldapConnection.SessionOptions.StartTransportLayerSecurity(null);
                            }

                            //protocol version specified? use version 3 if not
                            ldapConnection.SessionOptions.ProtocolVersion = _arguments.Contains("-v") ? int.Parse(_arguments[_arguments.IndexOf("-v") + 1]) : 3;

                            //do not chase referral
                            ldapConnection.SessionOptions.ReferralChasing = ReferralChasingOptions.None;

                            //You may need to try different types of Authentication depending on the setup
                            ldapConnection.AuthType = (_arguments.Contains("-u") || _arguments.Contains("-C")) ? AuthType.Basic : AuthType.Anonymous;

                            //use kerberos?
                            if (_arguments.Contains("-k"))
                            {
                                ldapConnection.AuthType = AuthType.Kerberos;
                                ldapConnection.SessionOptions.Sealing = true;
                                ldapConnection.SessionOptions.Signing = true;
                            }

                            //set or get timeout setting
                            ldapConnection.Timeout = new TimeSpan(0, _arguments.Contains("-t") ? int.Parse(_arguments[_arguments.IndexOf("-t") + 1]) : 10, 0);

                            //use credentials from encrypted credential file?
                            if (_arguments.Contains("-C"))
                            {
                                try{
                                    //split back to user|pwd
                                    string[] credentials = Crypto.Unprotect().Split('|');

                                    NetworkCredential cred =
                                        new NetworkCredential(credentials[0], credentials[1]);

                                    //ldap connect
                                    ldapConnection.Bind(cred);
                                }
                                catch (Exception e) {
                                    LogWriter.CreateLogEntry(string.Format("ERROR:{0} {1}", e.Message, (e.InnerException != null) ? e.InnerException.Message : string.Empty));
                                    ldapConnection.Dispose();
                                    return(1);
                                }
                            }

                            //use plain authentication?
                            else if (_arguments.Contains("-u") && _arguments.Contains("-p"))
                            {
                                NetworkCredential cred =
                                    new NetworkCredential(_arguments[_arguments.IndexOf("-u") + 1], _arguments[_arguments.IndexOf("-p") + 1]);

                                ldapConnection.Bind(cred);
                            }

                            //or try anonymously?
                            else
                            {
                                NetworkCredential cred =
                                    new NetworkCredential();
                                cred.Password = null;
                                cred.UserName = null;

                                ldapConnection.Bind(cred);
                            }

                            AsyncSearcher searcher = CreateSearcher(ldapConnection);

                            //this call is asynch, so we need to keep this main
                            //thread alive in order to see anything
                            //we can use the same searcher for multiple requests - we just have to track which one
                            //is which, so we can interpret the results later in our events.
                            attr = _arguments.Contains("-a") ? _arguments[_arguments.IndexOf("-a") + 1].Split(new char[] { ',', ';' }) : new string[] { "*" };

                            _guid = searcher.BeginPagedSearch(
                                //set searchbase
                                string.IsNullOrWhiteSpace(dn) ? "*" : dn,
                                //set filter
                                _arguments.Contains("-f") ? _arguments[_arguments.IndexOf("-f") + 1] : "(objectClass=*)",
                                //set attributes
                                attr,
                                150);

                            //we will use a reset event to signal when we are done (using Sleep() on
                            //current thread would work too...)
                            _resetEvent.WaitOne();                             //wait for signal;
                        }
                    }
                    catch (Exception e)     {
                        LogWriter.CreateLogEntry(string.Format("ERROR:{0} {1}", e.Message, (e.InnerException != null) ? e.InnerException.Message : string.Empty));
                        return(1);
                    }
                }
                return(0);
            }

            catch (Exception e)     {
                LogWriter.CreateLogEntry(string.Format("ERROR:{0} {1}", e.Message, (e.InnerException != null) ? e.InnerException.Message : string.Empty));
                return(1);
            }
        }
    public static void Main(System.String[] args)
    {
        if (args.Length != 6)
        {
            System.Console.Error.WriteLine("Usage:   mono GetEffectivePrivileges " + "<host Name> <port number> <login dn> " + "\n         <password> <object dn> <trustee dn>");
            System.Console.Error.WriteLine("Example: mono GetEffectivePrivileges Acme.com 389 " + "\"cn=Admin,o=Acme\" secret\n         " + "\"cn=james,o=Acme\" " + "\"cn=admin,o=Acme\"");
            System.Environment.Exit(1);
        }

        int LdapVersion = LdapConnection.Ldap_V3;
        System.String LdapHost = args[0];
        int LdapPort = System.Int32.Parse(args[1]);
        System.String loginDN = args[2];
        System.String password = args[3];
        System.String objectDN = args[4];
        System.String trusteeDN = args[5];
        int iRight = 0;
        System.String sRight = null;
        LdapConnection ld = new LdapConnection();

        try
        {
            // connect to the server
            ld.Connect(LdapHost, LdapPort);
            // bind to the server
            ld.Bind(LdapVersion, loginDN, password);
            System.Console.Out.WriteLine("\nLogin succeeded");

            // user can choose from:
            //   1. object rights(represented as [Entry Rights]);
            //   2. attribute rights(represented as [All Attributes Rights];
            //   3. a single attribute name like 'acl'
            //String rightName = "[Entry Rights]"
            //String rightName = "[All Attributes Rights]";
            System.String rightName = "acl";

            LdapExtendedOperation request = new GetEffectivePrivilegesRequest(objectDN, trusteeDN, rightName);

            LdapExtendedResponse response = ld.ExtendedOperation(request);

            if (response.ResultCode == LdapException.SUCCESS && (response is GetEffectivePrivilegesResponse))
            {
                iRight = ((GetEffectivePrivilegesResponse) response).Privileges;

                if (rightName.ToUpper().Equals("[Entry Rights]".ToUpper()))
                    sRight = "object rights";
                else if (rightName.ToUpper().Equals("[All Attributes Rights]".ToUpper()))
                    sRight = "attribute rights";
                else
                    sRight = rightName;

                System.Console.Out.WriteLine("\"" + trusteeDN + "\" has the following" + " rights on \"" + objectDN + "\"s '" + sRight + "':");
                PrintRights(rightName, iRight);
                System.Console.Out.WriteLine("\nGet Effective Privileges succeeded");
            }
            else
            {
                System.Console.Out.WriteLine("Get Effective Privileges Failed");
                throw new LdapException(response.ErrorMessage, response.ResultCode, (System.String) null);
            }

            /* Done, so disconnect */
            if (ld.Connected)
                ld.Disconnect();
        }
        catch (LdapException e)
        {
            System.Console.Out.WriteLine("Error: " + e.LdapErrorMessage);
        }
    }
Esempio n. 25
0
 public AsyncSearcher(LdapConnection connection)
 {
     this._connect = connection;
 }
Esempio n. 26
0
    public static void Main(String[] args)
    {
        if (args.Length != 3)
        {
            Console.WriteLine(
                "Usage:   mono EdirEventSample <host name> <login dn>"
                + " <password> ");
            Console.WriteLine(
                "Example: mono EdirEventSample Acme.com \"cn=admin,o=Acme\""
                + " secret ");
            Environment.Exit(0);
        }

        int ldapPort = LdapConnection.DEFAULT_PORT;
        int ldapVersion = LdapConnection.Ldap_V3;
        String ldapHost = args[0];
        String loginDN = args[1];
        String password = args[2];

        LdapResponseQueue queue = null;

        LdapConnection lc = new LdapConnection();

        try
        {
            // connect to the server
            lc.Connect(ldapHost, ldapPort);

            // authenticate to the server
            lc.Bind(ldapVersion, loginDN, password);

            //Create an Array of EdirEventSpecifier
            EdirEventSpecifier[] specifier = new EdirEventSpecifier[1];

            //Register for all Add Value events.
            specifier[0] =
                new EdirEventSpecifier(EdirEventType.EVT_CREATE_ENTRY,
                //Generate an Value Event of Type Add Value
                EdirEventResultType.EVT_STATUS_ALL
                //Generate Event for all status
                );

            //Create an MonitorEventRequest using the specifiers.
            MonitorEventRequest requestoperation =
                new MonitorEventRequest(specifier);

            //Send the request to server and get the response queue.
            queue = lc.ExtendedOperation(requestoperation, null, null);

        }

        catch (LdapException e)
        {
            Console.WriteLine("Error: " + e.ToString());
            try
            {
                lc.Disconnect();
            }
            catch (LdapException e2)
            {
                Console.WriteLine("Error: " + e2.ToString());
            }
            Environment.Exit(1);
        }

        catch (Exception e)
        {
            Console.WriteLine("Error: " + e.ToString());
        }

        Console.WriteLine("Monitoring the events for {0} minutes..", TIME_OUT_IN_MINUTES );
        Console.WriteLine();

        //Set the timeout value
        timeOut= DateTime.Now.AddMinutes(TIME_OUT_IN_MINUTES);

        try
        {
            //Monitor till the timeout happens
            while (DateTime.Now.CompareTo(timeOut) < 0)
            {
                if (!checkForAChange(queue))
                    break;
                System.Threading.Thread.Sleep(10);
            }
        }

        catch (System.IO.IOException e)
        {
            Console.WriteLine(e.Message);
        }

        catch (System.Threading.ThreadInterruptedException e)
        {
            Console.WriteLine(e.Message);
        }

        //disconnect from the server before exiting
        try
        {
            lc.Abandon(queue); //abandon the search
            lc.Disconnect();
        }

        catch (LdapException e)
        {
            Console.WriteLine();
            Console.WriteLine("Error: " + e.ToString());
        }

        Environment.Exit(0);
    }
Esempio n. 27
0
        public LdapConnection GetLdapConnection(string domainName = null)
        {
            Domain targetDomain;

            try
            {
                targetDomain = GetDomain(domainName);
            }
            catch
            {
                Verbose($"Unable to contact domain {domainName}");
                return(null);
            }

            if (targetDomain == null)
            {
                Verbose($"Unable to contact domain {domainName}");
                return(null);
            }

            string domainController;

            if (_options.DomainController != null)
            {
                domainController = _options.DomainController;
            }
            else
            {
                if (!_domainDcCache.TryGetValue(targetDomain.Name, out domainController))
                {
                    domainController = GetUsableDomainController(targetDomain);
                }
            }

            if (domainController == null)
            {
                return(null);
            }

            if (_ldapConnectionCache.TryGetValue(domainController, out var conn))
            {
                return(conn);
            }

            var port = _options.LdapPort == 0 ? (_options.SecureLdap ? 636 : 389) : _options.LdapPort;

            var identifier =
                new LdapDirectoryIdentifier(domainController, port, false, false);

            var connection = new LdapConnection(identifier)
            {
                Timeout = new TimeSpan(0, 0, 5, 0)
            };

            if (_options.LdapPass != null && _options.LdapUser != null)
            {
                Verbose("Adding Network Credential to connection");
                var cred = new NetworkCredential(_options.LdapUser, _options.LdapPass, targetDomain.Name);
                connection.Credential = cred;
            }

            //Add LdapSessionOptions
            var lso = connection.SessionOptions;

            if (!_options.DisableKerbSigning)
            {
                lso.Signing = true;
                lso.Sealing = true;
            }

            if (_options.SecureLdap)
            {
                lso.ProtocolVersion   = 3;
                lso.SecureSocketLayer = true;
                if (_options.IgnoreLdapCert)
                {
                    connection.SessionOptions.VerifyServerCertificate = (con, cer) => true;
                }
            }

            lso.ReferralChasing = ReferralChasingOptions.None;
            _ldapConnectionCache.TryAdd(domainController, connection);
            return(connection);
        }
    /**
     *
     * Constructs an extended operation object for restoring data of retreived
     * Object and make a call to ld.extendedOperation to get the response <br>
     *
     */
    public static void restore(LdapConnection ld, String objectDN, 
        byte[] passwd, ArrayList objectBuffer)
    {
        try
        {
            if(((Integer32)objectBuffer[0]).intValue != 0)
            {
                Console.WriteLine("Note: The test program did not proceed " +
                        "with restore since backup was not proper");
                Environment.Exit(0);
            }

            LdapExtendedOperation request = new LdapRestoreRequest(
                    objectDN, passwd,
                    (((Integer32)objectBuffer[1]).intValue),
                    (string)objectBuffer[2],
                    (byte[])objectBuffer[3]);

            LdapExtendedResponse response = ld.ExtendedOperation(request);

            if ( response.ResultCode == LdapException.SUCCESS )
                Console.WriteLine("Object restored successfully\n");
            else
            {
                Console.WriteLine("Restore Request Failed");
                throw new LdapException( response.ErrorMessage,
                                         response.ResultCode,
                                         (string)null);
            }

        }
        catch (LdapException e)
        {
            Console.WriteLine("Error: " + e.ToString());
        }
        catch (System.Exception e)
        {
            Console.WriteLine("Error: " + e.ToString());
        }
    }
Esempio n. 29
0
        public static void GetAppliedGPOs(LdapConnection connection, string rootDn, string name, bool isPC = false)
        {
            //if it is a computer account or a user account
            string nFilter = isPC ? @"(&(sAMAccountType=805306369)(name=" + name + "))" : @"(&(sAMAccountType=805306368)(name=" + name + "))";

            string[] nAttrs = { "distingushiedName" };

            //get the account distingushied name
            string Dn = GetSingleValue(connection, nFilter, SearchScope.Subtree, nAttrs, rootDn);

            if (!string.IsNullOrEmpty(Dn))
            {
                Console.WriteLine("  * DN: {0}\n", Dn);

                //If Last OU/Domain blocks inheritance
                bool isBlocking = false;

                string dn = "CN=" + name + ",";

                string ou = Dn.Replace(dn, "");

                //OU will not be affected by the block rule on itself
                int blockCounter = 0;


                while (ou.Contains(","))
                {
                    using (var entry = new DirectoryEntry("LDAP://" + ou))
                    {
                        isBlocking = Outputs.PrintGplink(entry, ou, isBlocking, blockCounter);

                        if (isBlocking)
                        {
                            blockCounter += 1;
                        }
                    }

                    if (ou.Contains(","))
                    {
                        ou = ou.Substring(ou.IndexOf(",") + 1);
                    }
                    else
                    {
                        break;
                    }
                }


                //get GPO applied on the site
                if (isPC)
                {
                    try
                    {
                        string site = ActiveDirectorySite.GetComputerSite().Name;

                        string siteDn = "CN=" + site + ",CN=Sites,CN=Configuration," + rootDn;

                        using (var entry = new DirectoryEntry("LDAP://" + siteDn))
                        {
                            Outputs.PrintGplink(entry, siteDn, isBlocking, blockCounter);
                        }
                    }
                    catch { }
                }
            }
        }
Esempio n. 30
0
 static public void LoadRazorAssemblies()
 {
     if (!_loadDone)
     {
         try
         {
             //Force the load of the assemblies
             if (dummy == null)
             {
                 dummy = new HtmlString("");
             }
             if (dummy2 == null)
             {
                 dummy2 = new DataTable();
                 dummy2.AsEnumerable();
             }
             if (dummy3 == null)
             {
                 dummy3 = new OleDbConnection();
             }
             if (dummy4 == null)
             {
                 dummy4 = new LdapConnection("");
             }
             if (dummy5 == null)
             {
                 dummy5 = new SyndicationFeed();
             }
             if (dummy6 == null)
             {
                 dummy6 = new XDocument();
             }
             if (dummy8 == null)
             {
                 dummy8 = new PrincipalContext(ContextType.Machine);
             }
             if (dummy10 == null)
             {
                 dummy10 = JObject.Parse("{}");
             }
             if (dummy11 == null)
             {
                 dummy11 = new FastZip();
             }
             if (dummy12 == null)
             {
                 dummy12 = new OdbcConnection();
             }
             if (dummy13 == null)
             {
                 dummy13 = new SqlConnection();
             }
             if (dummy14 == null)
             {
                 dummy14 = new SftpClient("", "a", "");
             }
             if (dummy15 == null)
             {
                 dummy15 = WebRequest.Create("ftp://dummy.com");
             }
             if (dummy16 == null)
             {
                 dummy16 = new HttpClient();
             }
         }
         catch (Exception ex)
         {
             Console.WriteLine(ex.Message);
         }
         _loadDone = true;
     }
 }
Esempio n. 31
0
        public static void GetResponse(LdapConnection conn,
                                       string filter,
                                       SearchScope scope,
                                       string[] attrsToReturn,
                                       string dn,
                                       string printOption = null,
                                       string spnName     = null)
        //Dictionary<string, string> myNames = null)
        {
            var request = new SearchRequest(dn, filter, scope, attrsToReturn);

            // the size of each page
            var pageReqControl = new PageResultRequestControl(500);

            // turn off referral chasing so that data
            // from other partitions is not returned

            //var searchControl = new SearchOptionsControl(SearchOption.DomainScope);
            //Unhandled Exception: System.ComponentModel.InvalidEnumArgumentException:
            //The value of argument 'value' (0) is invalid for Enum type 'SearchOption'.
            var searchControl = new SearchOptionsControl();

            request.Controls.Add(pageReqControl);
            request.Controls.Add(searchControl);


            SearchResponse            response;
            PageResultResponseControl pageResControl;

            // loop through each page
            while (true)
            {
                try
                {
                    response = (SearchResponse)conn.SendRequest(request);

                    if (response.Controls.Length != 1 || !(response.Controls[0] is PageResultResponseControl))
                    {
                        Console.WriteLine("The server does not support this advanced search operation");
                        return;
                    }
                    pageResControl = (PageResultResponseControl)response.Controls[0];

                    //Console.WriteLine("\nThis page contains {0} response entries:\n", response.Entries.Count);

                    switch (printOption)
                    {
                    //if there's only one attribute needs to be returned
                    //and this attribute is a single-valued attribute
                    case "single":
                        Outputs.PrintSingle(response, attrsToReturn[0]);
                        break;

                    //if there's only one attribute needs to be returned
                    //and this attribute is a multi-valued attribute
                    case "multi":
                        Outputs.PrintMulti(response, attrsToReturn[0]);
                        break;

                    ////Use specified name paris
                    //case "mynames":
                    //Outputs.PrintMyName(response, myNames);
                    //break;

                    case "gpo":
                        Outputs.PrintGPO(response);
                        break;

                    case "ou":
                        GetOU(response);
                        break;

                    case "spn":
                        Outputs.PrintSPNs(response, spnName);
                        break;

                    case "domain":
                        Outputs.PrintDomainAttrs(response);
                        break;

                    //case "attrname":
                    //Outputs.PrintAttrName(response);
                    //break;

                    //default: print all attributesToReturned
                    default:
                        Outputs.PrintAll(response);
                        break;
                    }


                    if (pageResControl.Cookie.Length == 0)
                    {
                        break;
                    }

                    pageReqControl.Cookie = pageResControl.Cookie;
                }
                catch (Exception e)
                {
                    Console.WriteLine("Unexpected error:  {0}", e.Message);
                    break;
                }
            }
        }
Esempio n. 32
0
        internal void ReadServerConfig(string serverName, ref ServerProperties properties)
        {
            string[]       proplist       = new string[] { "msDS-PortSSL", "msDS-PortLDAP", "domainControllerFunctionality", "dnsHostName", "supportedCapabilities" };
            LdapConnection ldapConnection = null;

            try
            {
                bool useSSL = (_options & ContextOptions.SecureSocketLayer) > 0;

                if (useSSL && _contextType == ContextType.Domain)
                {
                    LdapDirectoryIdentifier directoryid = new LdapDirectoryIdentifier(serverName, LdapConstants.LDAP_SSL_PORT);
                    ldapConnection = new LdapConnection(directoryid);
                }
                else
                {
                    ldapConnection = new LdapConnection(serverName);
                }

                ldapConnection.AutoBind = false;
                // If SSL was enabled on the initial connection then turn it on for the search.
                // This is requried bc the appended port number will be SSL and we don't know what port LDAP is running on.
                ldapConnection.SessionOptions.SecureSocketLayer = useSSL;

                string         baseDN           = null; // specify base as null for RootDSE search
                string         ldapSearchFilter = "(objectClass=*)";
                SearchResponse searchResponse   = null;

                SearchRequest searchRequest = new SearchRequest(baseDN, ldapSearchFilter, System.DirectoryServices.Protocols
                                                                .SearchScope.Base, proplist);

                try
                {
                    searchResponse = (SearchResponse)ldapConnection.SendRequest(searchRequest);
                }
                catch (LdapException ex)
                {
                    throw new PrincipalServerDownException(SR.ServerDown, ex);
                }

                // Fill in the struct with the casted properties from the serach results.
                // there will always be only 1 item on the rootDSE so all entry indexes are 0
                properties.dnsHostName         = (string)searchResponse.Entries[0].Attributes["dnsHostName"][0];
                properties.SupportCapabilities = new string[searchResponse.Entries[0].Attributes["supportedCapabilities"].Count];
                for (int i = 0; i < searchResponse.Entries[0].Attributes["supportedCapabilities"].Count; i++)
                {
                    properties.SupportCapabilities[i] = (string)searchResponse.Entries[0].Attributes["supportedCapabilities"][i];
                }

                foreach (string capability in properties.SupportCapabilities)
                {
                    if (CapabilityMap.LDAP_CAP_ACTIVE_DIRECTORY_ADAM_OID == capability)
                    {
                        properties.contextType = ContextType.ApplicationDirectory;
                    }
                    else if (CapabilityMap.LDAP_CAP_ACTIVE_DIRECTORY_OID == capability)
                    {
                        properties.contextType = ContextType.Domain;
                    }
                }

                // If we can't determine the OS vesion so we must fall back to lowest level of functionality
                if (searchResponse.Entries[0].Attributes.Contains("domainControllerFunctionality"))
                {
                    properties.OsVersion = (DomainControllerMode)Convert.ToInt32(searchResponse.Entries[0].Attributes["domainControllerFunctionality"][0], CultureInfo.InvariantCulture);
                }
                else
                {
                    properties.OsVersion = DomainControllerMode.Win2k;
                }

                if (properties.contextType == ContextType.ApplicationDirectory)
                {
                    if (searchResponse.Entries[0].Attributes.Contains("msDS-PortSSL"))
                    {
                        properties.portSSL = Convert.ToInt32(searchResponse.Entries[0].Attributes["msDS-PortSSL"][0]);
                    }
                    if (searchResponse.Entries[0].Attributes.Contains("msDS-PortLDAP"))
                    {
                        properties.portLDAP = Convert.ToInt32(searchResponse.Entries[0].Attributes["msDS-PortLDAP"][0]);
                    }
                }

                GlobalDebug.WriteLineIf(GlobalDebug.Info, "ReadServerConfig", "OsVersion : " + properties.OsVersion.ToString());
                GlobalDebug.WriteLineIf(GlobalDebug.Info, "ReadServerConfig", "dnsHostName : " + properties.dnsHostName);
                GlobalDebug.WriteLineIf(GlobalDebug.Info, "ReadServerConfig", "contextType : " + properties.contextType.ToString());
                GlobalDebug.WriteLineIf(GlobalDebug.Info, "ReadServerConfig", "portSSL : " + properties.portSSL.ToString(CultureInfo.InvariantCulture));
                GlobalDebug.WriteLineIf(GlobalDebug.Info, "ReadServerConfig", "portLDAP :" + properties.portLDAP.ToString(CultureInfo.InvariantCulture));
            }
            finally
            {
                if (ldapConnection != null)
                {
                    ldapConnection.Dispose();
                }
            }
        }
Esempio n. 33
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;
            }
        }
Esempio n. 34
0
        public async Task <IActionResult> Post([FromBody] ChangePasswordModel model)
        {
            // Validate the request
            if (model == null)
            {
                return(BadRequest(ApiResult.InvalidRequest()));
            }

            var result = new ApiResult();

            // Validate the model
            if (ModelState.IsValid == false)
            {
                result.AddModelStateErrors(ModelState);

                return(BadRequest(result));
            }

            // Validate the Captcha
            try
            {
                if (await ValidateRecaptcha(model.Recaptcha) == false)
                {
                    result.Errors.Add(new ApiErrorItem {
                        ErrorType = ApiErrorType.GeneralFailure, ErrorCode = ApiErrorCode.InvalidCaptcha
                    });
                }
            }
            catch (Exception ex)
            {
                result.Errors.Add(new ApiErrorItem {
                    ErrorType = ApiErrorType.GeneralFailure, ErrorCode = ApiErrorCode.Generic, Message = ex.Message
                });
            }

            if (result.HasErrors)
            {
                return(BadRequest(result));
            }

            // perform the password change
            try
            {
#if SWAN
                var distinguishedName = await GetDN(model.Username);

                if (string.IsNullOrEmpty(distinguishedName))
                {
                    result.Errors.Add(new ApiErrorItem()
                    {
                        ErrorType = ApiErrorType.GeneralFailure, ErrorCode = ApiErrorCode.InvalidCredentials, Message = "Invalid Username or Password"
                    });

                    return(BadRequest(result));
                }

                var cn = new LdapConnection();

                await cn.Connect(_options.PasswordChangeOptions.LdapHostname, _options.PasswordChangeOptions.LdapPort);

                await cn.Bind(_options.PasswordChangeOptions.LdapUsername, _options.PasswordChangeOptions.LdapPassword);

                var modList   = new ArrayList();
                var attribute = new LdapAttribute("userPassword", model.NewPassword);
                modList.Add(new LdapModification(LdapModificationOp.Replace, attribute));
                var mods = (LdapModification[])modList.ToArray(typeof(LdapModification));
                await cn.Modify(distinguishedName, mods);

                cn.Disconnect();
#else
                using (var principalContext = AcquirePrincipalContext())
                {
                    var userPrincipal = AcquireUserPricipal(principalContext, model.Username);

                    // Check if the user principal exists
                    if (userPrincipal == null)
                    {
                        result.Errors.Add(new ApiErrorItem {
                            ErrorType = ApiErrorType.GeneralFailure, ErrorCode = ApiErrorCode.UserNotFound, Message = "Invalid Username or Password"
                        });

                        return(BadRequest(result));
                    }

                    // Check if password change is allowed
                    if (userPrincipal.UserCannotChangePassword)
                    {
                        throw new Exception(_options.ClientSettings.Alerts.ErrorPasswordChangeNotAllowed);
                    }

                    // Validate user credentials
                    if (principalContext.ValidateCredentials(model.Username, model.CurrentPassword) == false)
                    {
                        // Your new authenticate code snippet
                        IntPtr token = IntPtr.Zero;
                        try
                        {
                            var    parts  = userPrincipal.UserPrincipalName.Split(new [] { '@' }, StringSplitOptions.RemoveEmptyEntries);
                            string domain = parts.Length > 1 ? parts[1] : null;

                            if (domain == null)
                            {
                                throw new Exception(_options.ClientSettings.Alerts.ErrorInvalidCredentials);
                            }

                            if (!PasswordChangeFallBack.LogonUser(model.Username, domain, model.CurrentPassword, PasswordChangeFallBack.LogonTypes.Network, PasswordChangeFallBack.LogonProviders.Default, out token))
                            {
                                int errorCode = System.Runtime.InteropServices.Marshal.GetLastWin32Error();
                                switch (errorCode)
                                {
                                case PasswordChangeFallBack.ERROR_PASSWORD_MUST_CHANGE:
                                case PasswordChangeFallBack.ERROR_PASSWORD_EXPIRED:
                                    // Both of these means that the password CAN change and that we got the correct password
                                    break;

                                default:
                                    throw new Exception(_options.ClientSettings.Alerts.ErrorInvalidCredentials);
                                }
                            }
                        }
                        finally
                        {
                            PasswordChangeFallBack.CloseHandle(token);
                        }
                    }

                    // Verify user is not a member of an excluded group
                    if (_options.ClientSettings.CheckRestrictedAdGroups)
                    {
                        foreach (Principal userPrincipalAuthGroup in userPrincipal.GetAuthorizationGroups())
                        {
                            if (_options.ClientSettings.RestrictedADGroups.Contains(userPrincipalAuthGroup.Name))
                            {
                                throw new Exception(_options.ClientSettings.Alerts.ErrorPasswordChangeNotAllowed);
                            }
                        }
                    }

                    // Change the password via 2 different methods. Try SetPassword if ChangePassword fails.
                    try
                    {
                        // Try by regular ChangePassword method
                        userPrincipal.ChangePassword(model.CurrentPassword, model.NewPassword);
                    }
                    catch (Exception ex2)
                    {
                        // If the previous attempt failed, use the SetPassword method.
                        if (_options.PasswordChangeOptions.UseAutomaticContext == false)
                        {
                            userPrincipal.SetPassword(model.NewPassword);
                        }
                        else
                        {
                            throw ex2;
                        }
                    }

                    userPrincipal.Save();
                }
#endif
            }
            catch (Exception ex)
            {
                result.Errors.Add(new ApiErrorItem {
                    ErrorType = ApiErrorType.GeneralFailure, ErrorCode = ApiErrorCode.Generic, Message = ex.Message
                });

                return(BadRequest(result));
            }

            if (result.HasErrors)
            {
                Response.StatusCode = (int)HttpStatusCode.BadRequest;
            }

            return(Json(result));
        }
Esempio n. 35
0
        /// <summary>
        /// Gets the login status for the specified user.
        /// </summary>
        /// <param name="connection">Ldap connection to use to get the status.</param>
        /// <param name="status">User information.</param>
        private void GetUserStatus(bool proxyUser, LdapConnection connection, Simias.Authentication.Status status)
        {
            if (connection != null)
            {
                // Get the search attributes for login status.
                string[] searchAttributes =
                {
                    "loginDisabled",
                    "loginExpirationTime",
                    "loginGraceLimit",
                    "loginGraceRemaining",
                    "passwordAllowChange",
                    "passwordRequired",
                    "passwordExpirationTime"
                };
                LdapEntry ldapEntry = connection.Read(status.DistinguishedUserName, searchAttributes);
                if (ldapEntry != null)
                {
                    // If the account has been disabled or the account has expired
                    // the bind will fail and we'll come through on the proxy user
                    // connection so there is no reason for the extra checking on
                    // a successful bind in the context of the actual user.
                    if (proxyUser == true && LoginDisabled(ldapEntry) == true)
                    {
                        status.statusCode = SCodes.AccountDisabled;
                    }
                    else
                    if (proxyUser == true && LoginAccountExpired(ldapEntry) == true)
                    {
                        status.statusCode = SCodes.AccountDisabled;
                    }
                    else
                    {
                        if (LoginIsPasswordRequired(ldapEntry) == true)
                        {
                            if (LoginCanUserChangePassword(ldapEntry) == true)
                            {
                                if (LoginPasswordExpired(ldapEntry) == true)
                                {
                                    status.TotalGraceLogins     = LoginGraceLimit(ldapEntry);
                                    status.RemainingGraceLogins = LoginGraceRemaining(ldapEntry);

                                    if (status.statusCode == SCodes.Success &&
                                        (status.TotalGraceLogins == -1 ||
                                         status.RemainingGraceLogins >= 0))
                                    {
                                        status.statusCode = SCodes.SuccessInGrace;
                                    }
                                    else
                                    {
                                        status.statusCode = SCodes.AccountLockout;
                                    }
                                }
                            }
                        }
                    }
                }
                else
                {
                    status.statusCode       = SCodes.InternalException;
                    status.ExceptionMessage = "Failed reading LDAP attributes";
                }
            }
        }
Esempio n. 36
0
        public void AuthType_SetInvalid_ThrowsInvalidEnumArgumentException(AuthType authType)
        {
            var connection = new LdapConnection("server");

            AssertExtensions.Throws <InvalidEnumArgumentException>("value", () => connection.AuthType = authType);
        }
Esempio n. 37
0
        /// <summary>
        /// Method to reset a user's password
        /// </summary>
        /// <param name="DistinguishedUserName" mandatory="true">DistinguishedUserName to set the password on.</param>
        /// <param name="OldPassword" mandatory="true">Old password.</param>
        /// <param name="NewPassword" mandatory="true">New password.</param>
        /// <returns>Zero - iF Successful,  greater that zero for failures</returns>
        public int ResetPassword(string DistinguishedUserName, string OldPassword, string NewPassword)
        {
            log.Debug("Resetting password for: " + DistinguishedUserName);

            LdapConnection LDAPconn        = null;
            LdapConnection proxyConnection = null;
            string         UserID;

            try
            {
                LDAPconn = new LdapConnection();
                LDAPconn.SecureSocketLayer = ldapSettings.SSL;
                LDAPconn.Connect(ldapSettings.Host, ldapSettings.Port);
                LDAPconn.Bind(DistinguishedUserName, OldPassword);
                if (LDAPconn.AuthenticationDN == null)
                {
                    log.Info("LDAPconn.AuthenticationDN = null");
                    return((int)PasswordChangeStatus.IncorrectOldPassword);
                }
                int result = GetUserStatusInfo(LDAPconn, DistinguishedUserName, NewPassword.Length);
                if (result != (int)PasswordChangeStatus.FailedToResetPassword)
                {
                    log.Info("result VALUE: {0}", result);
                    return((int)result);
                }
                else
                {
                    try
                    {
                        LdapModification[] modification   = new LdapModification[2];
                        LdapAttribute      deletePassword = new LdapAttribute("userPassword", OldPassword);
                        modification[0] = new LdapModification(LdapModification.DELETE, deletePassword);
                        LdapAttribute addPassword = new LdapAttribute("userPassword", NewPassword);
                        modification[1] = new LdapModification(LdapModification.ADD, addPassword);
                        LDAPconn.Modify(DistinguishedUserName, modification);
                    }
                    catch (Exception e)
                    {
                        log.Error("Unable to reset Password for DN:" + DistinguishedUserName);
                        log.Error("Error:" + e.Message);
                        return((int)PasswordChangeStatus.FailedToResetPassword);
                    }
                    return((int)PasswordChangeStatus.Success);
                }
            }
            catch (LdapException e)
            {
                log.Error("Password Reset failed for DN:" + DistinguishedUserName);
                log.Error("LdapError:" + e.LdapErrorMessage);
                log.Error("Error:" + e.Message);

                if (e.ResultCode == LdapException.INVALID_CREDENTIALS)
                {
                    return((int)PasswordChangeStatus.IncorrectOldPassword);
                }

                proxyConnection = BindProxyUser();
                if (proxyConnection != null)
                {
                    return((int)GetUserStatusInfo(proxyConnection, DistinguishedUserName, NewPassword.Length));
                }
            }
            catch (Exception e)
            {
                log.Error("Password Reset failed for DN:" + DistinguishedUserName);
                log.Error("Error:" + e.Message);
                proxyConnection = BindProxyUser();
                if (proxyConnection != null)
                {
                    return(GetUserStatusInfo(proxyConnection, DistinguishedUserName, NewPassword.Length));
                }
            }
            finally
            {
                try{
                    if (LDAPconn != null)
                    {
                        LDAPconn.Disconnect();
                    }

                    if (proxyConnection != null)
                    {
                        proxyConnection.Disconnect();
                    }
                }catch {}
            }
            return((int)PasswordChangeStatus.FailedToResetPassword);
        }
Esempio n. 38
0
        public void SendRequest_DsmlAuthRequest_ThrowsNotSupportedException()
        {
            var connection = new LdapConnection("server");

            Assert.Throws <NotSupportedException>(() => connection.SendRequest(new DsmlAuthRequest()));
        }
Esempio n. 39
0
        /// <summary>
        /// Method to verify a user's password
        /// </summary>
        /// <param name="Username">User to verify the password against</param>
        /// <param name="Password">Password to verify</param>
        /// <param name="status">Structure used to pass additional information back to the user.</param>
        /// <returns>true - Valid password, false Invalid password</returns>
        public bool VerifyPassword(string Username, string Password, Simias.Authentication.Status status)
        {
            log.Debug("VerifyPassword for: " + Username);

            LdapConnection conn            = null;
            LdapConnection proxyConnection = null;

            // Get the distinguished name and member(user) id from the
            // simias store rather than the ldap server
            if (GetUserDN(Username, out status.DistinguishedUserName, out status.UserID) == false)
            {
                log.Debug("failed to get the user's distinguished name");
                status.statusCode = SCodes.UnknownUser;
                return(false);
            }

            bool doNotCheckStatus = false;

            try
            {
                conn = new LdapConnection();
                conn.SecureSocketLayer = ldapSettings.SSL;
                conn.UserDefinedServerCertValidationDelegate += new CertificateValidationCallback(SSLHandler);
                conn.Connect(ldapSettings.Host, ldapSettings.Port);
                conn.Bind(status.DistinguishedUserName, Password);
                if (conn.AuthenticationDN == null)
                {
                    doNotCheckStatus = true;
                    throw new LdapException("Anonymous bind is not allowed", LdapException.INAPPROPRIATE_AUTHENTICATION, "Anonymous bind is not allowed");
                }

                status.statusCode = SCodes.Success;
                GetUserStatus(false, conn, status);
                return(true);
            }
            catch (LdapException e)
            {
                log.Error("LdapError:" + e.LdapErrorMessage);
                log.Error("Error:" + e.Message);
                log.Error("DN:" + status.DistinguishedUserName);

                switch (e.ResultCode)
                {
                case LdapException.INVALID_CREDENTIALS:
                    status.statusCode = SCodes.InvalidCredentials;
                    break;

                case LdapException.SSL_HANDSHAKE_FAILED:
                case LdapException.CONNECT_ERROR:
                    if (CertFailure == true)
                    {
                        status.statusCode = SCodes.InvalidCertificate;
                    }
                    CertFailure = false;
                    break;

                default:
                    if (CertFailure == true)
                    {
                        status.statusCode = SCodes.InvalidCertificate;
                    }
                    else
                    {
                        status.statusCode = SCodes.InternalException;
                    }
                    break;
                }

                status.ExceptionMessage = e.Message;
                if (!doNotCheckStatus)
                {
                    proxyConnection = BindProxyUser();
                    if (proxyConnection != null)
                    {
                        // GetUserStatus may change the status code
                        GetUserStatus(true, proxyConnection, status);
                    }
                }
            }
            catch (Exception e)
            {
                log.Error("Error:" + e.Message);
                status.statusCode       = SCodes.InternalException;
                status.ExceptionMessage = e.Message;
                proxyConnection         = BindProxyUser();
                if (proxyConnection != null)
                {
                    // GetUserStatus may change the status code
                    GetUserStatus(true, proxyConnection, status);
                }
            }
            finally
            {
                if (conn != null)
                {
                    // In Mono 2.0 runtime environment, first connection.Disconnect()
                    // always throws exception(bug 449092).
                    // First disconnect always throws "The socket is not connected" Messages.
                    // With this try, catch only ignoring that perticular Exception
                    try
                    {
                        conn.Disconnect();
                    }
                    catch (Exception Ex)
                    {
                        if (String.Compare(Ex.Message, "The socket is not connected") != 0)
                        {
                            throw Ex;
                        }
                        else
                        {
                            log.Info("LdapConnection.Disconnect Exception {0} {1} ", Ex.Message, Ex.StackTrace);
                        }
                    }
                }

                if (proxyConnection != null)
                {
                    try{
                        proxyConnection.Disconnect();
                    }catch {}
                }
            }

            return(false);
        }
Esempio n. 40
0
        public void BeginSendRequest_ReturnModeAndSearchRequest_ThrowsInvalidNotSupportedException(PartialResultProcessing partialMode)
        {
            var connection = new LdapConnection("server");

            Assert.Throws <NotSupportedException>(() => connection.BeginSendRequest(new AddRequest(), partialMode, null, null));
        }
Esempio n. 41
0
        static void Main(string[] args)
        {
            try
            {
                string server = null, dn = null, file = null;
                bool   oneline = false;

                for (int i = 0; i < args.Length; i++)
                {
                    switch (args[i])
                    {
                    case "-s":
                    case "-server":
                        server = args[++i];
                        break;

                    case "-D":
                    case "-dn":
                    case "-b":
                    case "-base":
                        dn = args[++i];
                        break;

                    case "-o":
                        oneline = true;
                        break;

                    case "-f":
                    case "-file":
                        file = args[++i];
                        break;
                    }
                }

                using (var conn = new LdapConnection(server))
                {
                    conn.SessionOptions.ProtocolVersion = 3;
                    conn.AutoBind = false;

                    Console.Write("Binding... ");

                    conn.Bind();

                    Console.WriteLine("Bound at {0}", DateTime.Now);

                    if (dn == null)
                    {
                        var t = (SearchResponse)conn.SendRequest(new SearchRequest("", "(&(objectClass=*))", SearchScope.Base, "defaultNamingContext"));
                        dn = t.Entries[0].Attributes["defaultNamingContext"][0].ToString();
                    }

                    var mgr = new VlvManager();

                    if (!string.IsNullOrEmpty(file))
                    {
                        using (var sr = new System.IO.StreamReader(file))
                        {
                            for (string line = sr.ReadLine(); line != null; line = sr.ReadLine())
                            {
                                if (line.StartsWith("#"))
                                {
                                    continue;
                                }

                                var parts = line.Split(new[] { '\t' }, StringSplitOptions.None);

                                if (parts.Length > 3)
                                {
                                    // Dn, Filter, Sort, Scope, Skip, Take

                                    Console.Write(line); Console.Write(oneline ? "\t" : Environment.NewLine);

                                    var sw = System.Diagnostics.Stopwatch.StartNew();

                                    try
                                    {
                                        var resp = mgr.GetData(
                                            conn: conn,
                                            distinguishedName: string.IsNullOrEmpty(parts[0]) ? dn : parts[0],
                                            filter: parts[1],
                                            sortBy: parts[2],
                                            scope: string.IsNullOrEmpty(parts[3]) ? SearchScope.OneLevel : (SearchScope)Enum.Parse(typeof(SearchScope), parts[3]),
                                            skip: parts.Length > 4 ? int.Parse(parts[4]) : 0,
                                            take: parts.Length > 5 ? int.Parse(parts[5]) : 25,
                                            attrs: null);

                                        Console.WriteLine("OK\t{0}\t{1}", sw.ElapsedMilliseconds, resp.ContentCount);
                                    }
                                    catch (Exception e)
                                    {
                                        Console.WriteLine("Error\t{0}\t0\t{1}", sw.ElapsedMilliseconds, e.Message);
                                    }
                                }
                                else
                                {
                                    Console.Error.WriteLine("Skip line: {0}", line);
                                }
                            }
                        }
                    }
                    else
                    {
                        while (true)
                        {
                            Console.Write("Enter search base [{0}] > ", dn);
                            string tmp = Console.ReadLine();
                            if (!string.IsNullOrEmpty(tmp))
                            {
                                dn = tmp;
                            }

                            Console.Write("Sort attr: [displayName] > ");
                            string sort = Console.ReadLine();

                            if (string.IsNullOrEmpty(sort))
                            {
                                sort = "displayName";
                            }

                            Console.Write("Enter filter: [{0}=*] > ", sort);
                            string filter = Console.ReadLine();

                            if (string.IsNullOrEmpty(filter))
                            {
                                filter = string.Format("(&({0}=*))", sort);
                            }

                            Console.Write("How many to skip? [0] ");
                            tmp = Console.ReadLine();

                            int skip = string.IsNullOrEmpty(tmp) ? 0 : int.Parse(tmp);

                            Console.Write("How many to take? [25] > ");
                            tmp = Console.ReadLine();

                            int take = string.IsNullOrEmpty(tmp) ? 25 : int.Parse(tmp);

                            Console.Write("Enter searchScope (base, onelevel, subtree) [onelevel] > ");
                            tmp = Console.ReadLine();

                            SearchScope scope;

                            switch (tmp.ToLowerInvariant())
                            {
                            case "b":
                            case "base":
                                scope = SearchScope.Base;
                                break;

                            case "s":
                            case "sub":
                            case "subtree":
                                scope = SearchScope.Subtree;
                                break;

                            default:
                                scope = SearchScope.OneLevel;
                                break;
                            }

                            var sw = System.Diagnostics.Stopwatch.StartNew();

                            try
                            {
                                var vr = mgr.GetData(conn, dn, filter, sort, scope, skip, take, new[] { sort });

                                sw.Stop();
                                Console.WriteLine("# VLV took {0} msec; content estimate = {1}", sw.ElapsedMilliseconds, vr.ContentCount);

                                if (take > 0)
                                {
                                    int i = 1;
                                    foreach (SearchResultEntry se in vr.Entries)
                                    {
                                        Console.WriteLine(" {0,4} {1}", i++, se.DistinguishedName);
                                    }
                                }
                            }
                            catch (DirectoryOperationException de)
                            {
                                Console.WriteLine("Directory exception: {0}, {1}", de.Message, de.Response.ResultCode);

                                if (de.Data != null)
                                {
                                    foreach (var key in de.Data.Keys)
                                    {
                                        Console.WriteLine("  Data: {0} = {1}", key, de.Data[key]);
                                    }
                                }
                            }

                            Console.WriteLine("");
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("{0}, {1} :: {2}", e.GetType(), e.Message, e.StackTrace);
            }
        }
Esempio n. 42
0
    public static bool _AddUserToGroup(LdapConnection conn, System.String userdn, System.String groupdn)
    {
        // modifications for group and user
        LdapModification[] modGroup = new LdapModification[2];
        LdapModification[] modUser = new LdapModification[2];

        // Add modifications to modUser
        LdapAttribute membership = new LdapAttribute("groupMembership", groupdn);
        modUser[0] = new LdapModification(LdapModification.ADD, membership);
        LdapAttribute security = new LdapAttribute("securityEquals", groupdn);
        modUser[1] = new LdapModification(LdapModification.ADD, security);

        // Add modifications to modGroup
        LdapAttribute member = new LdapAttribute("uniqueMember", userdn);
        modGroup[0] = new LdapModification(LdapModification.ADD, member);
        LdapAttribute equivalent = new LdapAttribute("equivalentToMe", userdn);
        modGroup[1] = new LdapModification(LdapModification.ADD, equivalent);

        try
        {
            // Modify the user's attributes
            conn.Modify(userdn, modUser);
            System.Console.Out.WriteLine("Modified the user's attribute.");
        }
        catch (LdapException e)
        {
            System.Console.Out.WriteLine("Failed to modify user's attributes: " + e.LdapErrorMessage);
            return false;
        }

        try
        {
            // Modify the group's attributes
            conn.Modify(groupdn, modGroup);
            System.Console.Out.WriteLine("Modified the group's attribute.");
        }
        catch (LdapException e)
        {
            System.Console.Out.WriteLine("Failed to modify group's attributes: " + e.LdapErrorMessage);
            doCleanup(conn, userdn, groupdn);
            return false;
        }
        catch(Exception e)
        {
            Console.WriteLine("Error:" + e.Message);
            return false;
        }
        return true;
    }
Esempio n. 43
0
 /// <summary>
 /// Creates the entry object
 /// </summary>
 /// <param name="lconn">Connection object used to communicate with
 /// Ldap server</param>
 internal DirectoryEntry(LdapConnection lconn)
 {
     conn = lconn;
 }
Esempio n. 44
0
    public static void Main(System.String[] args)
    {
        if (args.Length != 5)
        {
            usage();
            System.Environment.Exit(1);
        }

        int ldapPort = LdapConnection.DEFAULT_PORT;
        int ldapVersion = LdapConnection.Ldap_V3;
        bool status = false;
        LdapConnection conn = new LdapConnection();
        System.String ldapHost = args[0];
        System.String loginDN = args[1];
        System.String password = args[2];
        System.String userDN = args[3];
        System.String groupDN = args[4];

        try
        {
            // connect to the server
            conn.Connect(ldapHost, ldapPort);
            // bind to the server
            conn.Bind(ldapVersion, loginDN, password);

            // call _AddUseToGroup() to add the user to the group
            status = _AddUserToGroup(conn, userDN, groupDN);

            if (status)
                System.Console.Out.WriteLine("User: "******" was enrolled in group: " + groupDN);
            else
                System.Console.Out.WriteLine("User: "******" could not be enrolled in group: " + groupDN);

            // disconnect with the server
            conn.Disconnect();
        }
        catch (LdapException e)
        {
            System.Console.Out.WriteLine("Error: " + e.LdapErrorMessage);
        }
        catch(Exception e)
        {
            Console.WriteLine("Error:" + e.Message);
            return;
        }
        System.Environment.Exit(0);
    }
Esempio n. 45
0
    public static void Main( String[] args )
    {
        if (args.Length != 4)
        {
            Console.Error.WriteLine("Usage:   mono CompareAttrs <host name> <login dn> "
                + "<password> <compare dn> ");
            Console.Error.WriteLine("Example: mono CompareAttrs Acme.com \"cn=Admin,"
                + "o=Acme\" secret\n         \"cn=JSmith,ou=Sales,o=Acme\"");
            Environment.Exit(1);
        }

        int ldapPort = LdapConnection.DEFAULT_PORT;
        int ldapVersion = LdapConnection.Ldap_V3;
        bool compareResults = false;
        String ldapHost = args[0];
        String loginDN  = args[1];
        String password = args[2];
        String dn = args[3];
        LdapConnection lc = new LdapConnection();
        LdapAttribute attr = null;

        try
        {
            // connect to the server
            lc.Connect( ldapHost, ldapPort );

            // authenticate to the server
            lc.Bind( ldapVersion, loginDN, password );

            attr =new LdapAttribute( "objectclass", "inetOrgPerson" );
            System.Collections.IEnumerator allValues = attr.StringValues;
            allValues.MoveNext();
            // Compare the value of the objectclass attribute.
            if ( compareResults == lc.Compare(dn, attr))
                Console.WriteLine("\t" + (String)allValues.Current
                           + " is contained in the " + attr.Name + " attribute." );
            else
                Console.WriteLine("\t" + (String)allValues.Current
                           + " is not contained in the " + attr.Name + " attribute." );

            attr = new LdapAttribute( "sn", "Bunny" );
            allValues = attr.StringValues;
            allValues.MoveNext();

            // Compare the value of the sn attribute.
            if ( compareResults == lc.Compare(dn, attr))
                Console.WriteLine("\t" + (String)allValues.Current
                           + " is contained in the " + attr.Name + " attribute." );
            else
                Console.WriteLine("\t" + (String)allValues.Current
                           + " is not contained in the " + attr.Name + " attribute." );

            // disconnect with the server
            lc.Disconnect();
        }
        catch( LdapException e )
        {
            Console.WriteLine( "Error: " + e.ToString() );
        }
        catch( Exception e )
        {
            Console.WriteLine( "Error: " + e.ToString() );
        }
        Environment.Exit(0);
    }
Esempio n. 46
0
    public static void Main( String[] args )
    {
        if (args.Length != 6)
        {
            Console.Error.WriteLine(
                 "Usage:   mono ModifyACL <host name> <port number> <login dn>"
                 + " <password> \n         <entry dn> <trustee dn>");
            Console.Error.WriteLine(
                 "Example: mono ModifyACL Acme.com 389 \"cn=Admin,o=Acme\""
                 + "  secret \n         \"cn=test,ou=Sales,o=Acme\" "
                 + "\"cn=trustee,o=Acme\"");
            Environment.Exit(1);
        }
        int privileges   = 0;
        int ldapVersion  = LdapConnection.Ldap_V3;
        int ldapPort     = System.Convert.ToInt32(args[1]);
        String ldapHost  = args[0];
        String loginDN   = args[2];
        String password  = args[3];
        String entryDN   = args[4];
        String trusteeDN = args[5];

        LdapConnection lc = new LdapConnection();

        // encode ACL value
        privileges |= System.Convert.ToInt32(LdapDSConstants.LDAP_DS_ENTRY_BROWSE);
        privileges |= System.Convert.ToInt32(LdapDSConstants.LDAP_DS_ENTRY_ADD);
        privileges |= System.Convert.ToInt32(LdapDSConstants.LDAP_DS_ENTRY_DELETE);

        String aclValue = System.Convert.ToString(privileges)+ "#" + "entry" + "#"
                            + trusteeDN + "#" + "[Entry Rights]";

        try
        {
            // connect to the server
            lc.Connect( ldapHost, ldapPort );
            // bind to the server
            lc.Bind(ldapVersion, loginDN, password);

            // modify entryDN's ACL attribute
            Console.WriteLine( "    Entry DN: " + entryDN );
            Console.WriteLine( "    Trustee DN: " + trusteeDN );
            Console.WriteLine( "    Modifying entryDN's ACL value...");

            LdapAttribute acl = new LdapAttribute( "acl", aclValue);
            lc.Modify( entryDN, new LdapModification(LdapModification.ADD, acl));
            Console.WriteLine("    Modified ACL values to grant trusteeDN  the"
                        + "\n      'read', 'write', and 'delete' entry rights.\n");

            // display entryDN's ACL values
            findACLValues(lc, entryDN);

            // remove the Modified entryDN's ACL value
            Console.WriteLine( "\n    Removing the modified ACL value..." );
            lc.Modify( entryDN, new LdapModification(LdapModification.DELETE,acl));
            Console.WriteLine( "    Removed modified ACL value." );

            lc.Disconnect();
        }
        catch( LdapException e )
        {
            if ( e.ResultCode == LdapException.NO_SUCH_OBJECT )
                Console.Error.WriteLine( "Error: ModifyACL.java, No such entry" );
            else if ( e.ResultCode == LdapException.INSUFFICIENT_ACCESS_RIGHTS )
                Console.Error.WriteLine("Error: ModifyACL.java, Insufficient rights");
            else if ( e.ResultCode == LdapException.ATTRIBUTE_OR_VALUE_EXISTS )
                Console.Error.WriteLine("Error: ModifyACL.java, Attribute or value "
                                + "exists");
            else
            {
                Console.WriteLine( "Error: ModifyACL.java, " + e.ToString() );
            }
            Environment.Exit(1);
        }
        catch( Exception e )
        {
            Console.WriteLine( "Error: " + e.ToString() );
        }
        Environment.Exit(0);
    }
Esempio n. 47
0
    protected void Execute(string ldapHost, 
        string ldapPort,
        string loginDN,
        string password,
        string searchBase)
    {
        // Connect to the LDAP Server
        LdapConnection connection = new LdapConnection();

        try
        {
          connection.Connect(ldapHost, int.Parse(ldapPort));
          connection.Bind(loginDN, password);
        }
        catch(Exception e)
        {
          Console.WriteLine("Exception occurred: {0}", e.Message);
          try
          {
        connection.Disconnect();
          }
          catch(Exception e2)
          {
          }
          Environment.Exit(1);
        }

        Console.WriteLine(STARTING_PROMPT);

        string[] noAttrs = { LdapConnection.NO_ATTRS };

        // Make an object of PSearchEventSource
        PSearchEventSource objEventSource =
          new PSearchEventSource(connection,
                 searchBase,
                 LdapConnection.SCOPE_SUB, // scope
                 "(objectClass=*)", // filter
                 noAttrs, // attrs
                 true, // typesOnly
                 null, // constraints
                 LdapEventType.LDAP_PSEARCH_ANY, // eventChangeType
                 true// changeonly
                 );

        // register MySearchResultEventHandler as the handler for the Search
        // result events...
        objEventSource.SearchResultEvent += new PSearchEventSource.SearchResultEventHandler(MySearchResultEventHandler);

        // Another listener could be added easily...
        objEventSource.SearchResultEvent += new PSearchEventSource.SearchResultEventHandler(MySearchResultEventHandler02);

        // Add a listener for Referral Event
        objEventSource.SearchReferralEvent += new PSearchEventSource.SearchReferralEventHandler(MySearchReferralEventHandler);

        // Add a listener for generic directory event
        objEventSource.DirectoryEvent += new PSearchEventSource.DirectoryEventHandler(MyDirectoryEventHandler);

        // Add a listener for exception event
        objEventSource.DirectoryExceptionEvent += new PSearchEventSource.DirectoryExceptionEventHandler(MyDirectoryExceptionEventHandler);

        string input;
        bool bContinue;
        do
        {
          Console.WriteLine(QUIT_PROMPT);
          input = Console.ReadLine();
          bContinue = (input != null) && !(input.StartsWith("q")) && !(input.StartsWith("Q"));
        } while(bContinue);

        // time to unregister
        objEventSource.SearchResultEvent -= new PSearchEventSource.SearchResultEventHandler(MySearchResultEventHandler);

        objEventSource.SearchResultEvent -= new PSearchEventSource.SearchResultEventHandler(MySearchResultEventHandler02);

        objEventSource.SearchReferralEvent -= new PSearchEventSource.SearchReferralEventHandler(MySearchReferralEventHandler);

        objEventSource.DirectoryEvent -= new LdapEventSource.DirectoryEventHandler(MyDirectoryEventHandler);

        objEventSource.DirectoryExceptionEvent -= new PSearchEventSource.DirectoryExceptionEventHandler(MyDirectoryExceptionEventHandler);

        // Disconnect
        try
        {
          connection.Disconnect();
        }
        catch(Exception e)
        {
        }
    }
Esempio n. 48
0
    public static void Main( String[] args )
    {
        if (args.Length != 5)
        {
            Console.WriteLine("Usage:   mono ClientSideSort <host name> "+
                       "<login dn> <password> <search base>\n"
                       + "         <search filter>");
            Console.WriteLine("Example: mono ClientSideSort Acme.com"
                       + " \"cn=admin,o=Acme\""
                       + " secret \"ou=sales,o=Acme\"\n"
                       + "         \"(objectclass=*)\"");
            Environment.Exit(0);
        }

        int ldapPort = LdapConnection.DEFAULT_PORT;
        int searchScope = LdapConnection.SCOPE_ONE;
        int ldapVersion  = LdapConnection.Ldap_V3;
        String ldapHost = args[0];
        String loginDN  = args[1];
        String password = args[2];
        String searchBase = args[3];
        String searchFilter = args[4];
        LdapConnection conn = new LdapConnection();

        try
        {
            // connect to the server
            conn.Connect( ldapHost, ldapPort );

            // bind to the server
            conn.Bind( ldapVersion, loginDN, password);

            LdapSearchResults searchResults = conn.Search(  searchBase,
                                                            searchScope,
                                                            searchFilter,
                                                            new String[] {"cn", "uid", "sn"}, //attributes
                                                            false);        // return attrs and values

            /* sortedResults will sort the entries according to the natural
             * ordering of LDAPEntry (by distiguished name).
             */

            ArrayList sortedResults = new ArrayList();
            while ( searchResults.hasMore())
            {
                try
                {
                    sortedResults.Add( searchResults.next() );
                }
                catch(LdapException e)
                {
                    Console.WriteLine("Error: " + e.ToString());
                    // Exception is thrown, go for next entry
                    continue;
                }
            }

            // print the sorted results
            Console.WriteLine( "\n"+
                       "****************************\n"+
                       "Search results sorted by DN:\n"+
                       "****************************");
            sortedResults.Sort();
            IEnumerator i = sortedResults.GetEnumerator(0,sortedResults.Count-1);
            while (i.MoveNext())
            {
                PrintEntry( (LdapEntry)(i.Current) );
            }

            /* resort the results an an array using a specific comparator */
            String[] namesToSortBy  = { "sn", "uid", "cn"  };
            bool[] sortAscending = { true, false, true };
            LdapCompareAttrNames myComparator = new LdapCompareAttrNames( namesToSortBy, sortAscending );

            Object[] sortedSpecial = sortedResults.ToArray();
            Array.Sort(sortedSpecial, myComparator);

            // print the re-sorted results
            Console.WriteLine( "\n" +
                   "*****************************************************\n" +
                   "Search results sorted by sn, uid(Descending), and cn:\n" +
                   "*****************************************************");
            for(int j=0; j< sortedSpecial.Length; j++)
            {
                PrintEntry( (LdapEntry) sortedSpecial[j] );
            }
            // disconnect with the server
            conn.Disconnect();
        }
        catch( LdapException e )
        {
            Console.WriteLine( "Error: " + e.ToString() );
        }
        catch( Exception e )
        {
            Console.WriteLine( "Error: " + e.ToString() );
        }
        Environment.Exit(0);
    }
    public static void Main( String[] args )
    {
        // Verify correct number of parameters
        if (args.Length != 4)
        {
            Console.WriteLine("Usage:   mono AsynchronousSortControl <host name> "
                       + "<login dn> <password> <container>");
            Console.WriteLine("Example: mono AsynchronousSortControl Acme.com"
                       + " \"cn=admin,o=Acme\" secret \"ou=Sales,o=Acme\"");
            Environment.Exit(0);
        }

        // Read command line arguments
        String  ldapHost    = args[0];
        String  loginDN     = args[1];
        String  password    = args[2];
        String  searchBase  = args[3];
        int MY_PORT = 389;
        int ldapVersion  = LdapConnection.Ldap_V3;

        try
        {
            // Create a LdapConnection object
            LdapConnection lc = new LdapConnection();

            // Connect to server
            lc.Connect( ldapHost, MY_PORT);
            lc.Bind(ldapVersion, loginDN, password );
            Console.WriteLine( "Login succeeded");

            // We will be searching for all objects
            String MY_FILTER = "(objectClass=*)";

            //  Results of the search should include givenname and cn
            String[] attrs = new String[2];
            attrs[0] = "givenname";
            attrs[1] = "cn";

            // The results should be sorted using the cn attribute
            LdapSortKey[] keys = new LdapSortKey[1];
            keys[0] = new LdapSortKey( "cn" );

            // Create a LdapSortControl object - Fail if cannot sort
            LdapSortControl sort = new LdapSortControl( keys, true );

            // Set the Sort control to be sent as part of search request
            LdapSearchConstraints cons = lc.SearchConstraints;
            cons.setControls( sort );
            lc.Constraints = cons;

            // Perform the search - ASYNCHRONOUS SEARCH USED HERE
            Console.WriteLine( "Calling search request");
            LdapSearchQueue queue = lc.Search( searchBase,
                LdapConnection.SCOPE_SUB,
                MY_FILTER,
                attrs,
                false,
                (LdapSearchQueue)null,
                (LdapSearchConstraints) null );

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

                // OPTION 1: the message is a search result reference
                if ( message is LdapSearchResultReference )
                {
                    // Not following referrals to keep things simple
                    String[] urls = ((LdapSearchResultReference)message).Referrals;
                    Console.WriteLine("Search result references:");
                    for ( int i = 0; i < urls.Length; i++ )
                        Console.WriteLine(urls[i]);
                }

                    // OPTION 2:the message is a search result
                else if ( message is LdapSearchResult )
                {
                    // Get the object name
                    LdapEntry entry = ((LdapSearchResult)message).Entry;

                    Console.WriteLine("\n" + entry.DN);
                    Console.WriteLine("\tAttributes: ");

                    // Get the attributes and print them out
                    LdapAttributeSet attributeSet = entry.getAttributeSet();
                    IEnumerator allAttributes = attributeSet.GetEnumerator();

                    while(allAttributes.MoveNext())
                    {
                        LdapAttribute attribute = (LdapAttribute)allAttributes.Current;
                        String attributeName = attribute.Name;

                        Console.WriteLine("\t\t" + attributeName);

                        // Print all values of the attribute
                        IEnumerator allValues = attribute.StringValues;
                        if( allValues != null)
                        {
                            while(allValues.MoveNext())
                            {
                                String Value = (String) allValues.Current;
                                Console.WriteLine("\t\t\t" + Value);
                            }
                        }
                    }
                }

                    // OPTION 3: The message is a search response
                else
                {
                    LdapResponse response = (LdapResponse)message;
                    int status = response.ResultCode;

                    // the return code is Ldap success
                    if ( status == LdapException.SUCCESS )
                    {
                        Console.WriteLine("Asynchronous search succeeded.");
                    }

                        // the return code is referral exception
                    else if ( status == LdapException.REFERRAL )
                    {
                        String[] urls=((LdapResponse)message).Referrals;
                        Console.WriteLine("Referrals:");
                        for ( int i = 0; i < urls.Length; i++ )
                            Console.WriteLine(urls[i]);
                    }
                    else
                    {
                        Console.WriteLine("Asynchronous search failed.");
                        Console.WriteLine( response.ErrorMessage);
                    }

                    // Server should send back a control irrespective of the
                    // status of the search request
                    LdapControl[] controls = response.Controls;
                    if ( controls != null )
                    {

                        // Theoritically we could have multiple controls returned
                        for( int i = 0; i < controls.Length; i++ )
                        {

                            // We are looking for the LdapSortResponse Control class - the control
                            // sent back in response to LdapSortControl
                            if ( controls[i] is LdapSortResponse )
                            {

                                Console.WriteLine("Received Ldap Sort Control fromserver");

                                // We must have an error code and maybe a string identifying
                                // erring attribute in the response control.  Get these.
                                String bad = ((LdapSortResponse)controls[i]).FailedAttribute;
                                int result = ((LdapSortResponse)controls[i]).ResultCode;

                                // Print out error ccode (0 if no error) and any returned
                                // attribute
                                Console.WriteLine( "Error code: " + result );
                                if ( bad != null )
                                    Console.WriteLine( "Offending " + "attribute: " + bad );
                                else
                                    Console.WriteLine( "No offending " + "attribute " + "returned" );
                            }
                        }
                    }

                }
            }

                // All done - disconnect
            if ( lc.Connected == true )
                    lc.Disconnect();
        }

        catch( LdapException e )
        {
            Console.WriteLine( e.ToString() );
        }
        catch( Exception e )
        {
            Console.WriteLine( "Error: " + e.ToString() );
        }
    }
Esempio n. 50
0
 public static string GetServerName(this LdapConnection connection)
 {
     return(((LdapDirectoryIdentifier)connection.Directory).Servers[0]);
 }
Esempio n. 51
0
    public static void Main( String[] args )
    {
        if (args.Length != 5)
        {
            Console.Error.WriteLine("Usage:   mono List <host name> <login dn>"
                + " <password> <search base>\n"
                + "         <search filter>");
            Console.Error.WriteLine("Example: mono List Acme.com \"cn=admin,o=Acme\""
                + " secret \"ou=sales,o=Acme\"\n"
                + "         \"(objectclass=*)\"");
            Environment.Exit(1);
        }

        int LdapPort = LdapConnection.DEFAULT_PORT;
        int searchScope = LdapConnection.SCOPE_ONE;
        int LdapVersion  = LdapConnection.Ldap_V3;;
        bool attributeOnly = true;
        String[] attrs = {LdapConnection.NO_ATTRS};
        String ldapHost = args[0];
        String loginDN = args[1];
        String password = args[2];
        String searchBase = args[3];
        String searchFilter = args[4];
        LdapConnection lc = new LdapConnection();

        try
        {
            // connect to the server
            lc.Connect( ldapHost, LdapPort );
            // bind to the server
            lc.Bind( LdapVersion, loginDN, password );

            LdapSearchResults searchResults =
                lc.Search(  searchBase,      // container to search
                searchScope,     // search scope
                searchFilter,    // search filter
                attrs,           // "1.1" returns entry name only
                attributeOnly);  // no attributes are returned

            // print out all the objects
            while ( searchResults.hasMore() )
            {
                LdapEntry nextEntry = null;
                try
                {
                    nextEntry = searchResults.next();
                }
                catch(LdapException e)
                {
                    Console.WriteLine("Error: " + e.ToString());

                    // Exception is thrown, go for next entry
                    continue;
                }

                Console.WriteLine("\n" + nextEntry.DN);
            }
            // disconnect with the server
            lc.Disconnect();
        }
        catch( LdapException e )
        {
            Console.WriteLine( "Error: " + e.ToString() );
        }
        catch( Exception e )
        {
            Console.WriteLine( "Error: " + e.ToString() );
        }
        Environment.Exit(0);
    }
Esempio n. 52
0
    public static void Main( String[] args )
    {
        if (args.Length != 5)
        {
            Console.Error.WriteLine("Usage:   mono SetPassword <host name> "
                + "<login dn> <password>\n"
                + "         <modify dn> <new password>");
            Console.Error.WriteLine("Example: mono SetPassword Acme.com "
                + "\"cn=Admin,o=Acme secret\"\n"
                + "         \"cn=JSmith,ou=Sales,o=Acme\""
                + " newPassword");
            Environment.Exit(1);
        }

        int ldapPort = LdapConnection.DEFAULT_PORT;
        int ldapVersion = LdapConnection.Ldap_V3;
        String ldapHost = args[0];
        String loginDN = args[1];
        String password = args[2];
        String modifyDN = args[3];
        String newPassword = args[4];
        LdapConnection lc = new LdapConnection();

        /* To set a user's password,
          *   -- User should have administrator privileges
          *   -- Specify the new password value to be set
          *   -- Specify the modify type (replace for this operation)
          *   -- Add the new value and type to the modification set
          *   -- Call LdapConnection modify method to set the password
          */

        try
        {
            // connect to the server
            lc.Connect( ldapHost, ldapPort );
            // authenticate to the server
            lc.Bind( ldapVersion, loginDN, password );

            LdapAttribute attributePassword = new LdapAttribute( "userPassword",
                newPassword);
            lc.Modify( modifyDN, new LdapModification(
                LdapModification.REPLACE, attributePassword) );

            Console.WriteLine( "Successfully set the user's password" );

            // disconnect with the server
            lc.Disconnect();
        }
        catch( LdapException e )
        {
            if ( e.ResultCode == LdapException.NO_SUCH_OBJECT )
            {
                Console.Error.WriteLine( "Error: No such entry" );
            }
            else if ( e.ResultCode ==
                LdapException.INSUFFICIENT_ACCESS_RIGHTS )
            {
                Console.Error.WriteLine( "Error: Insufficient rights" );
            }
            else
            {
                Console.Error.WriteLine( "Error: " + e.ToString() );
            }
        }
        catch( Exception e )
        {
            Console.WriteLine( "Error: " + e.ToString() );
        }
        Environment.Exit(0);
    }
Esempio n. 53
0
 private static string DN(this LdapConnection con, ParameterAccessor.Parts.Ldap ldap)
 {
     return((new LdapUrl(ldap.LdapSearchRoot)).GetDn());
 }
Esempio n. 54
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);
    }
Esempio n. 55
0
        static void Delete(string server, string searchBase, string filter, int connCount, System.Net.NetworkCredential nc)
        {
            using (LdapConnection conn = new LdapConnection(server))
            {
                conn.SessionOptions.ProtocolVersion = 3;
                conn.Credential = nc ?? System.Net.CredentialCache.DefaultNetworkCredentials;
                conn.AutoBind   = false;
                conn.Bind();

                IList <LdapConnection> conns = new List <LdapConnection>();
                for (int i = 0; i < connCount; i++)
                {
                    var c = new LdapConnection(server);

                    c.SessionOptions.ProtocolVersion = 3;
                    c.Credential = nc;
                    c.AutoBind   = false;
                    c.Bind();

                    conns.Add(c);
                }

                Console.WriteLine("Created {0} connections", conns.Count);

                var req = new SearchRequest
                {
                    DistinguishedName = searchBase,
                    Filter            = filter ?? "(&(objectClass=person)(cn=*CNF:*))"
                };

                req.Attributes.Add("1.1");

                req.Controls.Add(new PageResultRequestControl(1000)
                {
                    IsCritical = false
                });

                while (true)
                {
                    var resp = (SearchResponse)conn.SendRequest(req);
                    var lazy = new LazyCommitControl()
                    {
                        IsCritical = false
                    };

                    Parallel.ForEach(ISE(resp.Entries), entry =>
                    {
                        try
                        {
                            var delreq = new DeleteRequest(entry.DistinguishedName);
                            delreq.Controls.Add(lazy);

                            conns[Thread.CurrentThread.ManagedThreadId % connCount].SendRequest(delreq);

                            Console.Error.WriteLine("Deleted {0}", entry.DistinguishedName);
                        }
                        catch (Exception ex)
                        {
                            Console.Error.WriteLine("Failed to delete {0}: {1}", entry.DistinguishedName, ex.Message);
                            throw;
                        }
                    }
                                     );

                    if (resp.Controls.Length == 0)
                    {
                        break;
                    }

                    var prc = (PageResultResponseControl)resp.Controls[0];
                    if (prc.Cookie.Length == 0)
                    {
                        break;
                    }

                    Console.WriteLine("On to the next page!");

                    req.Controls.Clear();
                    req.Controls.Add(new PageResultRequestControl(prc.Cookie));
                }

                Console.WriteLine("Complete");
            }
        }
Esempio n. 56
0
    protected void Execute(string ldapHost, 
        string ldapPort,
        string loginDN,
        string password)
    {
        // Connect to the LDAP Server
        LdapConnection connection = new LdapConnection();

        try
        {
          connection.Connect(ldapHost, int.Parse(ldapPort));
          connection.Bind(loginDN, password);
        }
        catch(Exception e)
        {
          Console.WriteLine("Exception occurred: {0}", e.Message);
          try
          {
        connection.Disconnect();
          }
          catch(Exception e2)
          {
          }
          Environment.Exit(1);
        }

        Console.WriteLine(STARTING_PROMPT);

        EdirEventSpecifier[] specifier = new EdirEventSpecifier[1];
        specifier[0] = new EdirEventSpecifier(
                      EdirEventType.EVT_CREATE_ENTRY,
                      EdirEventResultType.EVT_STATUS_ALL
                      //, we could have optionally specified a filter here like "(attributeName=city)"
                      );

        // Make an object of EdirEventSource
        EdirEventSource objEventSource = new EdirEventSource(specifier, connection);

        // register for events
        objEventSource.EdirEvent += new EdirEventSource.EdirEventHandler(MyEdirEventHandler);

        // Another listener can be easily added
        objEventSource.EdirEvent += new EdirEventSource.EdirEventHandler(MyEdirEventHandler02);

        // Add a listener for generic directory event
        objEventSource.DirectoryEvent += new EdirEventSource.DirectoryEventHandler(MyDirectoryEventHandler);

        // Add a listener for exception event
        objEventSource.DirectoryExceptionEvent += new EdirEventSource.DirectoryExceptionEventHandler(MyDirectoryExceptionEventHandler);

        string input;
        bool bContinue;
        do
        {
          Console.WriteLine(QUIT_PROMPT);
          input = Console.ReadLine();
          bContinue = (input != null) && !(input.StartsWith("q")) && !( input.StartsWith("Q"));
        } while(bContinue);

        // time to unregister
        objEventSource.EdirEvent -= new EdirEventSource.EdirEventHandler(MyEdirEventHandler);

        objEventSource.EdirEvent -= new EdirEventSource.EdirEventHandler(MyEdirEventHandler02);

        objEventSource.DirectoryEvent -= new EdirEventSource.DirectoryEventHandler(MyDirectoryEventHandler);

        objEventSource.DirectoryExceptionEvent -= new EdirEventSource.DirectoryExceptionEventHandler(MyDirectoryExceptionEventHandler);

        // Disconnect
        try
        {
          connection.Disconnect();
        }
        catch(Exception e)
        {
        }
    }
    public static void Main(String[] args)
    {
        if (!(args.Length == 5 || args.Length == 6 || args.Length == 7))
        {
            Console.Error.WriteLine("Usage: mono GetLdapBackupRestore <host Name> "
                              + "<port number> <login dn> <password>\n "
                              + " <object DN> [encrypted password (optional)]" +
                              		" [state Info (optional)]");
            Console.Error.WriteLine("\nFor Non encrypted objects::");
            Console.Error.WriteLine("--------------------------");
            Console.Error.WriteLine("	Example: mono GetLdapBackupRestore Acme.com 389 "
                              + "\"cn=Admin,o=Acme\" secret\n "
                              + "\"cn=TestUser,o=Acme\"");
            Console.Error.WriteLine("\nFor Encrypted objects::");
            Console.Error.WriteLine("----------------------");
            Console.Error.WriteLine("	Example: mono GetLdapBackupRestore Acme.com 389 "
                              + "\"cn=Admin,o=Acme\" secret\n "
                              + "\"cn=TestUser,o=Acme\" testpassword");
            Environment.Exit(1);
        }

        int ldapVersion = LdapConnection.Ldap_V3;
        String ldapHost = args[0];
        int ldapPort = int.Parse(args[1]);
        String loginDN = args[2];
        String password = args[3];
        String objectDN = args[4];
        String encPasswd = null;
        String stateInfo = null;

        if(args.Length == 6 && args[5] != null)
        {
            encPasswd = args[5];
        }
        if(args.Length == 7 && args[6] != null)
        {
            stateInfo = args[6];
        }

        //Create a LdapConnection object
        LdapConnection ld = new LdapConnection();

        if(ldapPort == 636)
            ld.SecureSocketLayer = true;

        try
        {
            // connect to the server
            ld.Connect(ldapHost, ldapPort);

            // bind to the server
            ld.Bind(ldapVersion, loginDN, password.ToString());
            Console.WriteLine("\nLogin succeeded");
            Console.WriteLine("\n Object DN =" + objectDN);

            //Call backup method
            ArrayList objectBuffer;
            if(encPasswd == null)
                objectBuffer = backup(ld, objectDN, null, stateInfo);
            else
                objectBuffer = backup(ld, objectDN, SupportClass.ToByteArray(encPasswd), stateInfo);

            //Call restore method
            if(encPasswd == null)
                restore(ld, objectDN, null, objectBuffer);
            else
                restore(ld, objectDN, SupportClass.ToByteArray(encPasswd), objectBuffer);

            /* Done, so disconnect */
            if (ld.Connected)
                ld.Disconnect();

        }
        catch (LdapException e)
        {
            Console.WriteLine("Error: " + e.ToString());
        }
        catch (System.Exception e)
        {
            Console.WriteLine("Error: " + e.ToString());
        }
    }