Connect() public method

Connects to the specified host and port. If this LdapConnection object represents an open connection, the connection is closed first before the new connection is opened. At this point, there is no authentication, and any operations are conducted as an anonymous client. When more than one host name is specified, each host is contacted in turn until a connection can be established.
LdapException A general exception which includes an error /// message and an Ldap error code. /// ///
public Connect ( System host, int port ) : void
host System A host name or a dotted string representing the IP address /// of a host running an Ldap server. It may also /// contain a list of host names, space-delimited. Each host /// name can include a trailing colon and port number. /// ///
port int The TCP or UDP port number to connect to or contact. /// The default Ldap port is 389. The port parameter is /// ignored for any host hame which includes a colon and /// port number. /// ///
return void
        public bool CheckUser(string UserName, string OldPassword)
        {
            bool   result = true;
            string User   = UserName;
            string Pass   = OldPassword;

            // Creating an LdapConnection instance
            Novell.Directory.Ldap.LdapConnection ldapConn = new Novell.Directory.Ldap.LdapConnection();

            string dn = "uid = " + UserName + ",ou=users,dc=example,dc=com";

            try
            {
                //Connect function will create a socket connection to the server
                ldapConn.Connect(ldapHost, ldapPort);

                //Bind function will Bind the user object Credentials to the Server
                ldapConn.Bind(dn, OldPassword);
            }

            catch (Novell.Directory.Ldap.LdapException e)
            {
                TempData["msg"] = "<script>alert('Could not authenticate user!');</script>";
                result          = false;
                return(result);
            }

            finally
            {
                // Disconnect from LDAP
                ldapConn.Disconnect();
            }

            return(result);
        }
    public static void  Main(System.String[] args)
    {
        if (args.Length != 5)
        {
            System.Console.Error.WriteLine("Usage:   mono ListReplicas <host Name> " + "<port number> <login dn> <password>" + "\n         <server ND>");
            System.Console.Error.WriteLine("Example: mono ListReplicas Acme.com 389 " + "\"cn=Admin,o=Acme\" secret" + "\n         \"cn=myServer,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  serverDN = args[4];
        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");

            LdapExtendedOperation request = new ListReplicasRequest(serverDN);

            LdapExtendedResponse response = ld.ExtendedOperation(request);

            if ((response.ResultCode == LdapException.SUCCESS) && (response is ListReplicasResponse))
            {
                System.Console.Out.WriteLine("Replica List: ");
                System.String[] rList = ((ListReplicasResponse)response).ReplicaList;
                int             len   = rList.Length;
                for (int i = 0; i < len; i++)
                {
                    System.Console.Out.WriteLine(rList[i]);
                }

                System.Console.Out.WriteLine("\nList replica request succeeded\n");
            }
            else
            {
                System.Console.Out.WriteLine("List Replicas request failed." + response.ResultCode);
//				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("\nError: " + e.ToString());
        }
    }
Example #3
0
        //--- Methods ---
        private LdapConnection GetLdapConnectionFromBindingDN(string server, string bindingdn, string password) {
            LdapConnection conn = null;
            try {
                conn = new LdapConnection();
                conn.SecureSocketLayer = _config.SSL;
                int port = _config.SSL ? LDAPS_PORT : LDAP_PORT;
                conn.UserDefinedServerCertValidationDelegate += new CertificateValidationCallback(ValidateCert);

                string[] temp = server.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
                server = temp[0];
                if(temp.Length > 1) {
                    int.TryParse(temp[1], out port);
                }

                //if server has a port number specified, it's used instead.
                conn.Connect(server, port);

                if (!string.IsNullOrEmpty(bindingdn)) {
                    conn.Bind(bindingdn, password);
                }

            } catch (Exception x) {
                UnBind(conn);
                _log.WarnExceptionMethodCall(x, "GetLdapConnection", string.Format("Failed to bind to LDAP server: '{0}' with bindingdn: '{1}'. Password provided? {2}. Exception: {3}", server, bindingdn, string.IsNullOrEmpty(password), x));
                throw;
            }
            return conn;
        }
Example #4
0
        static void Main(string[] args)
        {
            if ( args.Length != 4)
            {
            Console.WriteLine("Usage:   mono SecureBind <host name> <ldap port>  <login dn>" + " <password> \n");
            Console.WriteLine("Example: mono SecureBind Acme.com 636"  + " \"cn=admin,o=Acme\"" + " secret \n");
            Console.WriteLine("Import the server Trusted Root Certificate in Mono trust store using certmgr.exe utility e.g.\n");
            Console.WriteLine("certmgr -add -c Trust /home/exports/TrustedRootCert.cer\n");
            return;
            }

            string ldapHost = args[0];
            int ldapPort = System.Convert.ToInt32(args[1]);
            String loginDN  = args[2];
            String password = args[3];
            LdapConnection conn=null;
            try
            {
            conn= new LdapConnection();
            conn.SecureSocketLayer=true;
            Console.WriteLine("Connecting to:" + ldapHost);
            conn.Connect(ldapHost,ldapPort);
            conn.Bind(loginDN,password);
            Console.WriteLine(" SSL Bind Successfull");
            }
            catch(Exception e)
            {
            Console.WriteLine("Error:" + e.Message);
            }
            conn.Disconnect();
        }
    public static void Main(System.String[] args)
    {
        if (args.Length != 5)
        {
            System.Console.Error.WriteLine("Usage:   mono PartitionEntryCount <host Name> " + "<port number> <login dn> <password>" + "\n         <partition dn>");
            System.Console.Error.WriteLine("Example: mono PartitionEntryCount Acme.com 389 " + "\"cn=Admin,o=Acme\" secret" + "\n         \"ou=Sales,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 partitionDN = args[4];
        int count = 0;
        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");

            LdapExtendedOperation request = new PartitionEntryCountRequest(partitionDN);

            LdapExtendedResponse response = ld.ExtendedOperation(request);

            if ((response.ResultCode == LdapException.SUCCESS) && (response is PartitionEntryCountResponse))
            {
                count = ((PartitionEntryCountResponse) response).Count;
                System.Console.Out.WriteLine("\n    Entry count of partition " + partitionDN + " is: " + count);

                System.Console.Out.WriteLine("\nPartitionEntryCount succeeded\n");
            }
            else
            {
                System.Console.Out.WriteLine("\nPartitionEntryCount 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);
        }
        catch(Exception e)
        {
            Console.WriteLine("Error:" + e.Message);
            return;
        }
    }
Example #6
0
		private void InitBlock()
		{
			_conn = new LdapConnection();
			LdapUrl lUrl=new LdapUrl(SearchRoot.ADsPath);
			_Host=lUrl.Host;
			_Port=lUrl.Port;
			_conn.Connect(_Host,_Port);
			_conn.Bind(SearchRoot.Username,SearchRoot.Password,(Novell.Directory.Ldap.AuthenticationTypes)SearchRoot.AuthenticationType);

		}
		private void InitBlock()
		{
			_conn = new LdapConnection();
			LdapUrl lUrl=new LdapUrl(SearchRoot.Path);
			_Host=lUrl.Host;
			_Port=lUrl.Port;
			_conn.Connect(_Host,_Port);
			_conn.Bind(SearchRoot.Username,SearchRoot.Password);

		}
Example #8
0
        public UserViewModel Login(string username, string password)
        {
            // Creating an LdapConnection instance
            var ldapConn       = new LdapConnection();
            var tempDomainName = new StringBuilder(100);

            if (!string.IsNullOrEmpty(_settings.DomainName))
            {
                tempDomainName.Append(_settings.DomainName);
                tempDomainName.Append('\\');
            }

            tempDomainName.Append(username);
            //Connect function will create a socket connection to the server
            ldapConn.Connect(_settings.Address, _settings.PortNumber);

            //Bind function will Bind the user object Credentials to the Server
            ldapConn.Bind(tempDomainName.ToString(), password);


            var uservm = new UserViewModel()
            {
                UserName = username, Name = username
            };
            var cons = ldapConn.SearchConstraints;

            cons.ReferralFollowing = true;
            ldapConn.Constraints   = cons;

            var attributes = _settings.Attributes?.Trim() == "" ? null : _settings.Attributes?.Split(",").Select(s => s.Trim());
            var lsc        = ldapConn.Search(_settings.DistinguishedName,
                                             (int)Enum.Parse <SearchScope>(_settings.SearchScope),
                                             $"(sAMAccountName={username})",
                                             attributes?.ToArray(),
                                             false,
                                             (LdapSearchConstraints)null);

            while (lsc.HasMore())
            {
                LdapEntry nextEntry = null;
                nextEntry = lsc.Next();
                var attributeSet = nextEntry.GetAttributeSet();
                System.Collections.IEnumerator ienum = attributeSet.GetEnumerator();
                while (ienum.MoveNext())
                {
                    var attribute     = (LdapAttribute)ienum.Current;
                    var attributeName = attribute.Name;
                    var attributeVal  = attribute.StringValue;

                    uservm.CustomClaims.Add(new Claim(attributeName, attributeVal));
                }
            }

            return(uservm);
        }
Example #9
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);
    }
Example #10
0
    public static void Main(System.String[] args)
    {
        if (args.Length != 5)
        {
            System.Console.Error.WriteLine("Usage:   mono ListReplicas <host Name> " + "<port number> <login dn> <password>" + "\n         <server ND>");
            System.Console.Error.WriteLine("Example: mono ListReplicas Acme.com 389 " + "\"cn=Admin,o=Acme\" secret" + "\n         \"cn=myServer,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 serverDN = args[4];
        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");

            LdapExtendedOperation request = new ListReplicasRequest(serverDN);

            LdapExtendedResponse response = ld.ExtendedOperation(request);

            if ((response.ResultCode == LdapException.SUCCESS) && (response is ListReplicasResponse))
            {
                System.Console.Out.WriteLine("Replica List: ");
                System.String[] rList = ((ListReplicasResponse) response).ReplicaList;
                int len = rList.Length;
                for (int i = 0; i < len; i++)
                    System.Console.Out.WriteLine(rList[i]);

                System.Console.Out.WriteLine("\nList replica request succeeded\n");
            }
            else
            {
                System.Console.Out.WriteLine("List Replicas request failed." + response.ResultCode);
        //				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("\nError: " + e.ToString());
        }
    }
Example #11
0
    public static void  Main(System.String[] args)
    {
        if (args.Length != 4)
        {
            System.Console.Error.WriteLine("Usage:   mono GetBindDN " + "<host Name> <port number> <login dn>" + "\n              <password>");
            System.Console.Error.WriteLine("Example: mono GetBindDN Acme.com " + "389 \"cn=Admin,o=Acme\" secret");
            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];
        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");

            LdapExtendedOperation request = new GetBindDNRequest();

            LdapExtendedResponse response = ld.ExtendedOperation(request);

            if (((response.ResultCode) == LdapException.SUCCESS) && (response is GetBindDNResponse))
            {
                System.Console.Out.WriteLine("You were logged in as: " + ((GetBindDNResponse)response).Identity);
                System.Console.Out.WriteLine("\nGetBindDN succeeded.\n");
            }
            else
            {
                System.Console.Out.WriteLine("GetBindDN failed.\n");
                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("\nError: " + e.LdapErrorMessage);
        }
    }
Example #12
0
        public void Initialize(NameValueCollection properties)
        {
            this.properties = properties;

            if(!Utility.KeyExists(properties, "server"))
                throw(new Exception("Server property not specified."));

            if(!Utility.KeyExists(properties, "base"))
                throw(new Exception("Base property not specified."));

            connection = new LdapConnection();

            connection.Connect(properties["server"], Utility.KeyExists(properties, "port") ? int.Parse(properties["port"]) : LdapConnection.DEFAULT_PORT);
        }
Example #13
0
        static void Main(string[] args)
        {
            if ( args.Length != 5)
            {
            Console.WriteLine("Usage:   mono AddEntry <host name> <ldap port>  <login dn>" + " <password> <container>");
            Console.WriteLine("Example: mono AddEntry Acme.com 389"  + " \"cn=admin,o=Acme\"" + " secret \"ou=sales,o=Acme\"");
            return;
            }

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

            try
            {
            LdapAttributeSet attributeSet = new LdapAttributeSet();
            attributeSet.Add(	new LdapAttribute(
                                "objectclass", "inetOrgPerson"));
                                attributeSet.Add( new LdapAttribute("cn",
                                new string[]{"James Smith", "Jim Smith", "Jimmy Smith"}));
            attributeSet.Add(	new LdapAttribute("givenname",
                                 "James"));
            attributeSet.Add(	new LdapAttribute("sn", "Smith"));
            attributeSet.Add(	new LdapAttribute("telephonenumber","1 801 555 1212"));
            attributeSet.Add(	new LdapAttribute("mail", "*****@*****.**"));
            attributeSet.Add(	new LdapAttribute("userpassword","newpassword"));

            string  dn  = "cn=KSmith," + containerName;
            LdapEntry newEntry = new LdapEntry( dn, attributeSet );
            LdapConnection conn= new LdapConnection();
            Console.WriteLine("Connecting to:" + ldapHost);
            conn.Connect(ldapHost,ldapPort);
            conn.Bind(loginDN,password);
            conn.Add( newEntry );
            Console.WriteLine("Entry:" + dn + "  Added Successfully");
            conn.Disconnect();
            }
            catch(LdapException e)
            {
            Console.WriteLine("Error:" + e.LdapErrorMessage);
            return;
            }
            catch(Exception e)
            {
            Console.WriteLine("Error:" + e.Message);
            return;
            }
        }
Example #14
0
        static void Main(string[] args)
        {
            if ( args.Length != 5)
            {
            Console.WriteLine("Usage:   mono ModifyEntry <host name> <ldap port>  <login dn>" + " <password> <Modify dn>");
            Console.WriteLine("Example: mono ModifyEntry Acme.com 389"  + " \"cn=admin,o=Acme\"" + " secret \"cn=ksmith,o=Acme\"");
            return;
            }

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

            try
            {
            Console.WriteLine("Connecting to:" + ldapHost);
            LdapConnection conn= new LdapConnection();
            ArrayList modList = new ArrayList();
            String desc = "This object belongs to test user";
            // Add a new value to the description attribute
            LdapAttribute attribute = new LdapAttribute( "description", desc);
            modList.Add( new LdapModification(LdapModification.ADD, attribute));

            String email = "*****@*****.**";
            attribute = new LdapAttribute( "mail", email);
            modList.Add( new LdapModification(LdapModification.REPLACE, attribute));
            LdapModification[] mods = new LdapModification[modList.Count];
            mods = (LdapModification[])modList.ToArray(typeof(LdapModification));

            conn.Connect(ldapHost,ldapPort);
            conn.Bind(loginDN,password);
            conn.Modify(dn,mods);
            Console.WriteLine(" Entry: " + dn + "Modified Successfully");
            conn.Disconnect();

            }
            catch(LdapException e)
            {
            Console.WriteLine("Error:" + e.LdapErrorMessage);
            return;
            }
            catch(Exception e)
            {
            Console.WriteLine("Error:" + e.Message);
            return;
            }
        }
		/// <summary> Initializes the Connection and other properties.
		/// 
		/// </summary>
		private void InitBlock()
		{
			try			{
				LdapUrl lUrl=new LdapUrl(_Bpath);
				_Conn = new LdapConnection();
				_Conn.Connect(lUrl.Host,lUrl.Port);
				_Conn.Bind(_Buser,_Bpass);
			}
			catch(LdapException ex)			{
				throw ex;
			}
			catch(Exception e)				{
				throw e;
			}
		}
Example #16
0
    public static void Main(System.String[] args)
    {
        if (args.Length != 4)
        {
            System.Console.Error.WriteLine("Usage:   mono GetBindDN " + "<host Name> <port number> <login dn>" + "\n              <password>");
            System.Console.Error.WriteLine("Example: mono GetBindDN Acme.com " + "389 \"cn=Admin,o=Acme\" secret");
            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];
        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");

            LdapExtendedOperation request = new GetBindDNRequest();

            LdapExtendedResponse response = ld.ExtendedOperation(request);

            if (((response.ResultCode) == LdapException.SUCCESS) && (response is GetBindDNResponse))
            {
                System.Console.Out.WriteLine("You were logged in as: " + ((GetBindDNResponse) response).Identity);
                System.Console.Out.WriteLine("\nGetBindDN succeeded.\n");
            }
            else
            {
                System.Console.Out.WriteLine("GetBindDN failed.\n");
                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("\nError: " + e.LdapErrorMessage);
        }
    }
Example #17
0
        protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
        {
            try
            {
                LdapConnection conn = new LdapConnection();
                //Console.WriteLine("Connecting to:" + ldapHost);
                conn.Connect("192.168.36.10", 389);
                conn.Bind(Login1.UserName, Login1.Password);
                conn.Disconnect();

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
		public Task LoginAsync (string username, string password, CancellationToken cancellationToken)
		{
			ValidateConfiguration ();

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

				if (!string.IsNullOrEmpty (username))
					conn.Bind (username, password);

			}, cancellationToken);
		}
        public User Login(string userName, string password)
        {
            User user = new User();


            using (var cn = new Novell.Directory.Ldap.LdapConnection())
            {
                cn.Connect(config.Path, config.Port);

                try
                {
                    cn.Bind(config.UserDomainName + "\\" + userName, password);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                    Console.WriteLine("Failed login attempt for user " + userName);
                    user = null;
                    return(user);
                }

                string filter = "sAMAccountname=" + userName;

                string baseStr = "OU=BLS,DC=blacklanternsecurity,DC=com";

                LdapSearchResults result = (LdapSearchResults)cn.Search(baseStr, LdapConnection.ScopeSub, filter, null, false);

                LdapEntry entry = null;
                try
                {
                    entry = result.First();
                }
                catch (LdapException e)
                {
                    Console.WriteLine("Error: " + e.LdapErrorMessage);
                }

                LdapAttributeSet attributeSet = entry.GetAttributeSet();

                user.DisplayName = attributeSet.GetAttribute("displayName").StringValue;
                user.GivenName   = attributeSet.GetAttribute("givenName").StringValue;
                user.UserName    = userName;

                return(user);
            }
        }
Example #20
0
        static void Main(string[] args)
        {
            if ( args.Length != 7)
            {
            Console.WriteLine("Usage:   mono AddReplica <host name> <ldap port>  <login dn>" + " <password> <replica dn> <replica type> <server dn> ");
            Console.WriteLine("Example: mono AddReplica Acme.com 389"  + " \"cn=admin,o=Acme\"" + " secret \"ou=Sales,o=Acme\" 1 \"cn=myServer,o=Acme\"");
            return;
            }

            string ldapHost = args[0];
            int ldapPort = System.Convert.ToInt32(args[1]);
            String loginDN  = args[2];
            String password = args[3];
            String replicaDN   = args[4];
            int    replicaType = System.Convert.ToInt32(args[5]);
            String serverDN    = args[6];
            try
            {
            LdapConnection conn= new LdapConnection();
            Console.WriteLine("Connecting to:" + ldapHost);
            conn.Connect(ldapHost,ldapPort);
            conn.Bind(loginDN,password);
            LdapExtendedOperation request = new AddReplicaRequest(	replicaDN,
                                                                    serverDN,
                                                                    replicaType,
                                                                    ReplicationConstants.Ldap_ENSURE_SERVERS_UP);

            LdapExtendedResponse response = conn.ExtendedOperation(request);
            if ( response.ResultCode == LdapException.SUCCESS )
            {
                Console.WriteLine("Add Replica Request succeeded\n");
            }
            conn.Disconnect();
            }
            catch(LdapException e)
            {
            Console.WriteLine("Error:" + e.LdapErrorMessage);
            return;
            }
            catch(Exception e)
            {
            Console.WriteLine("Error:" + e.Message);
            return;
            }
        }
Example #21
0
        public bool AuthenticateUser(string host, string username, string password, string port, out string Errmsg)
        {
            try
            {
                LdapConnection conn = new LdapConnection();
                conn.Connect(host, Convert.ToInt32(port));
                conn.Bind(username, password);
                conn.Disconnect();
                Errmsg = "";
                return true;

            }
            catch (Exception ex)
            {
                Errmsg = ex.Message;
                return false;
            }
        }
Example #22
0
        static void Main(string[] args)
        {
            if ( args.Length != 5)
            {
            Console.WriteLine("Usage:   mono ModifyPass <host name> <ldap port>  <login dn>" + " <old password> <new password>");
            Console.WriteLine("Example: mono ModifyPass Acme.com 389"  + " \"cn=tjhon,o=Acme\"" + " secret \"newpass\"");
            return;
            }

            string ldapHost = args[0];
            int ldapPort = System.Convert.ToInt32(args[1]);
            String loginDN  = args[2];
            String opassword = args[3];
            String npassword = args[4];

            try
            {
            LdapConnection conn= new LdapConnection();
            Console.WriteLine("Connecting to:" + ldapHost);
            conn.Connect(ldapHost,ldapPort);
            conn.Bind(loginDN,opassword);
            LdapModification[] modifications = new LdapModification[2];
            LdapAttribute deletePassword = new LdapAttribute("userPassword", opassword);
            modifications[0] = new LdapModification(LdapModification.DELETE, deletePassword);
            LdapAttribute addPassword = new LdapAttribute("userPassword", npassword);
            modifications[1] = new LdapModification(LdapModification.ADD, addPassword);

            conn.Modify(loginDN, modifications);

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

            conn.Disconnect();
            }
            catch(LdapException e)
            {
            Console.WriteLine("Error:" + e.LdapErrorMessage);
            return;
            }
            catch(Exception e)
            {
            Console.WriteLine("Error:" + e.Message);
            return;
            }
        }
        static void Main(string[] args)
        {
            if ( args.Length != 4)
            {
            Console.WriteLine("Usage:   mono RefreshLdapServer <host name> <ldap port>  <login dn>" + " <password> ");
            Console.WriteLine("Example: mono RefreshLdapServer Acme.com 389"  + " \"cn=admin,o=Acme\"" + " secret ");
            return;
            }

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

            try
            {
            LdapConnection conn= new LdapConnection();
            Console.WriteLine("Connecting to:" + ldapHost);
            conn.Connect(ldapHost,ldapPort);
            conn.Bind(loginDN,password);
               		LdapExtendedOperation request = new RefreshLdapServerRequest();
               	LdapExtendedResponse response = conn.ExtendedOperation(request);
            if ( response.ResultCode == LdapException.SUCCESS )
            {
                Console.WriteLine("Refresh Ldap Server Request succeeded\n");
            }
            conn.Disconnect();
            }
            catch(LdapException e)
            {
            Console.WriteLine("Error:" + e.LdapErrorMessage);
            return;
            }
            catch(Exception e)
            {
            Console.WriteLine("Error:" + e.Message);
            return;
            }
        }
Example #24
0
        static void Main(string[] args)
        {
            if ( args.Length != 7)
            {
            Console.WriteLine("Usage:   mono RenameEntry <host name> <ldap port>  <login dn>" + " <password> <old dn> <new rdn> <parentDN>");
            Console.WriteLine("Example: mono RenameEntry Acme.com 389"  + " \"cn=admin,o=Acme\"" + " secret \"cn=ksmith,o=Acme\"   cn=JamesSmith \"o=Products,o=Acme\"");
            return;
            }

            string ldapHost = args[0];
            int ldapPort = System.Convert.ToInt32(args[1]);
            String loginDN  = args[2];
            String password = args[3];
            String oldDN = args[4];
            String newRDN = args[5];
            String parentDN = args[6];

            try
            {
            Console.WriteLine("Connecting to:" + ldapHost);
            LdapConnection conn= new LdapConnection();
            conn.Connect(ldapHost,ldapPort);
            conn.Bind(loginDN,password);
            conn.Rename(oldDN, newRDN, parentDN, true);
            Console.WriteLine( "Entry " + oldDN + " has been renamed as " + newRDN + "," + parentDN  );
            conn.Disconnect();
            }
            catch(LdapException e)
            {
            Console.WriteLine("Error:" + e.LdapErrorMessage);
            return;
            }
            catch(Exception e)
            {
            Console.WriteLine("Error:" + e.Message);
            return;
            }
        }
Example #25
0
        //--- Methods ---
        private LdapConnection GetLdapConnectionFromBindingDN(string server, string bindingdn, string password) {
            LdapConnection conn = null;
            try {
                conn = new LdapConnection();
                conn.SecureSocketLayer = _config.SSL;
                int port = _config.SSL ? LDAPS_PORT : LDAP_PORT;
                conn.UserDefinedServerCertValidationDelegate += new CertificateValidationCallback(ValidateCert);

                //if server has a port number specified, it's used instead.
                conn.Connect(server, port);

                if (!string.IsNullOrEmpty(bindingdn)) {
                    conn.Bind(bindingdn, password);
                }

            } catch (Exception x) {
                UnBind(conn);

                LogUtils.LogWarning(_log, x, "GetLdapConnection", string.Format("Failed to bind to LDAP server: '{0}' with bindingdn: '{1}'. Password provided? {2}. Exception: {3}", server, bindingdn, string.IsNullOrEmpty(password).ToString(), x.ToString()));
                throw;
            }
            return conn;
        }
Example #26
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);
    }
Example #27
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)
        {
        }
    }
		/// <summary> Initializes the Connection and other properties.
		/// 
		/// </summary>
		private void InitBlock()
		{
			try			{
				_conn= new LdapConnection ();
				LdapUrl lUrl = new LdapUrl (ADsPath);
				_conn.Connect(lUrl.Host,lUrl.Port);
				_conn.Bind(Username,Password, (Novell.Directory.Ldap.AuthenticationTypes)AuthenticationType);
			}
			catch(LdapException ex)			{
				throw ex;
			}
			catch(Exception e)			{
				throw e;
			}
		}
Example #29
0
        public async Task ValidateAsync(ResourceOwnerPasswordValidationContext context)
        {
            try
            {
                if (String.IsNullOrEmpty(context.UserName) || String.IsNullOrEmpty(context.Password))
                {
                    context.Result = new GrantValidationResult(TokenRequestErrors.InvalidRequest, "As credenciais do usuário são obrigatórias", null);
                    return;
                }

                string cpfMok = null;
                switch (context.UserName)
                {
                case "sisgp_gestor": cpfMok = "08056275029"; break;

                case "sisgp_cg": cpfMok = "95387502500"; break;

                case "sisgp_coget": cpfMok = "43321040565"; break;

                case "sisgp_coordenador": cpfMok = "25715446597"; break;

                case "sisgp_diretor": cpfMok = "39178470510"; break;

                case "sisgp_servidor": cpfMok = "08152972541"; break;

                case "sisgp_servidor1": cpfMok = "59516301002"; break;

                case "sisgp_servidor2": cpfMok = "18761704091"; break;

                case "sisgp_servidor3": cpfMok = "07721701007"; break;

                case "sisgp_servidor4": cpfMok = "51884275087"; break;
                }

                Pessoa pessoa = null;
                if (!string.IsNullOrEmpty(cpfMok))
                {
                    //if (context.Password.ToUpper() == "S20211014")
                    //{
                    pessoa = await this.PessoaRepository.ObterPorCriteriosAsync(null, cpfMok);

                    //}
                }
                else
                {
                    if (this.Options.Value.Configurations == null)
                    {
                        context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, "As configurações do LDAP são inválidas", null);
                    }
                    else
                    {
                        pessoa = await Task.Run(() =>
                        {
                            foreach (var configuration in this.Options.Value.Configurations)
                            {
                                using (var connection = new Novell.Directory.Ldap.LdapConnection())
                                {
                                    try
                                    {
                                        connection.Connect(configuration.Url, configuration.Port);
                                        connection.Bind(configuration.BindDN, configuration.BindPassword);
                                    }
                                    catch
                                    {
                                        context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, "Não foi possível pesquisar no LDAP. A autenticação do usuário de serviço falhou", null);
                                        return(null);
                                    }

                                    List <string> attibutes = new List <string>();
                                    if (!String.IsNullOrEmpty(configuration.SisrhIdAttributeFilter))
                                    {
                                        attibutes.Add(configuration.SisrhIdAttributeFilter);
                                    }
                                    if (!String.IsNullOrEmpty(configuration.EmailAttributeFilter))
                                    {
                                        attibutes.Add(configuration.EmailAttributeFilter);
                                    }
                                    if (!String.IsNullOrEmpty(configuration.CpfAttributeFilter))
                                    {
                                        attibutes.Add(configuration.CpfAttributeFilter);
                                    }

                                    var searchFilter = String.Format(configuration.SearchFilter, context.UserName);
                                    var entities     = connection.Search(
                                        configuration.SearchBaseDC,
                                        Novell.Directory.Ldap.LdapConnection.ScopeSub,
                                        searchFilter,
                                        attibutes.ToArray(),
                                        false);

                                    while (entities.HasMore())
                                    {
                                        var entity           = entities.Next();
                                        var entityAttributes = entity.GetAttributeSet();

                                        //Valida o password
                                        connection.Bind(entity.Dn, context.Password);

                                        var sisrhId = GetAttributeValue(entity, configuration.SisrhIdAttributeFilter);
                                        if (!String.IsNullOrEmpty(sisrhId))
                                        {
                                            var _pessoa = this.PessoaRepository.ObterAsync(Int64.Parse(sisrhId));
                                            if (_pessoa != null)
                                            {
                                                return(_pessoa);
                                            }
                                        }

                                        string email = GetAttributeValue(entity, configuration.EmailAttributeFilter);
                                        string cpf   = GetAttributeValue(entity, configuration.CpfAttributeFilter);

                                        var dadosPessoa = this.PessoaRepository.ObterPorCriteriosAsync(email, cpf);
                                        if (dadosPessoa != null)
                                        {
                                            return(dadosPessoa);
                                        }
                                    }
                                }
                            }

                            return(null);
                        });
                    }
                }

                if (pessoa != null)
                {
                    context.Result = new GrantValidationResult(pessoa.PessoaId.ToString(), "password", null, "local", null);
                }
                else
                {
                    if (context.Result == null)
                    {
                        context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, "Não foi encontrado usuário com esse login", null);
                    }
                }
            }
            catch (Novell.Directory.Ldap.LdapException ex)
            {
                context.Result       = new GrantValidationResult(TokenRequestErrors.InvalidGrant, ex.Message, null);
                context.Result.Error = ex.StackTrace.ToString();
            }
        }
Example #30
0
    public static void  Main(System.String[] args)
    {
        if (args.Length != 6)
        {
            System.Console.Error.WriteLine("Usage:    mono GetReplicaInfo <host Name> " + "<port number> <login dn> <password>\n        " + " <partition DN> <server ND>");
            System.Console.Error.WriteLine("Example:  mono GetReplicaInfo Acme.com 389 " + "\"cn=Admin,o=Acme\" secret\n         " + "\"ou=Sales,o=Acme\" \"cn=myServer,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 partitionDN = args[4];
        System.String serverDN    = args[5];
        int           intInfo;

        System.String  strInfo;
        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");

            LdapExtendedOperation request = new GetReplicaInfoRequest(serverDN, partitionDN);

            LdapExtendedResponse response = ld.ExtendedOperation(request);

            if ((response.ResultCode == LdapException.SUCCESS) && (response is GetReplicaInfoResponse))
            {
                System.Console.Out.WriteLine("Repica Info:");
                strInfo = ((GetReplicaInfoResponse)response).getpartitionDN();
                System.Console.Out.WriteLine("    Partition DN: " + strInfo);
                intInfo = ((GetReplicaInfoResponse)response).getpartitionID();
                System.Console.Out.WriteLine("    Partition ID: " + intInfo);
                intInfo = ((GetReplicaInfoResponse)response).getreplicaState();
                System.Console.Out.WriteLine("    Replica state: " + intInfo);
                intInfo = ((GetReplicaInfoResponse)response).getmodificationTime();
                System.Console.Out.WriteLine("    Modification Time: " + intInfo);
                intInfo = ((GetReplicaInfoResponse)response).getpurgeTime();
                System.Console.Out.WriteLine("    Purge Time: " + intInfo);
                intInfo = ((GetReplicaInfoResponse)response).getlocalPartitionID();
                System.Console.Out.WriteLine("    Local partition ID: " + intInfo);
                intInfo = ((GetReplicaInfoResponse)response).getreplicaType();
                System.Console.Out.WriteLine("    Replica Type: " + intInfo);
                intInfo = ((GetReplicaInfoResponse)response).getflags();
                System.Console.Out.WriteLine("    Flags: " + intInfo);
                System.Console.Out.WriteLine("\nget replica information succeeded\n");
            }
            else
            {
                System.Console.Out.WriteLine("Could not get replica information.\n");
                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.ToString());
        }
    }
Example #31
0
		/// <summary> Synchronously reads the entry specified by the Ldap URL, using the
		/// specified constraints.
		/// 
		/// When this method is called, a new connection is created
		/// automatically, using the host and port specified in the URL. After
		/// finding the entry, the method closes the connection (in other words,
		/// it disconnects from the Ldap server).
		/// 
		/// If the URL specifies a filter and scope, they are not used. Of the
		/// information specified in the URL, this method only uses the Ldap host
		/// name and port number, the base distinguished name (DN), and the list
		/// of attributes to return.
		/// 
		/// </summary>
		/// <returns> The entry specified by the base DN.
		/// 
		/// </returns>
		/// <param name="toGet">      Ldap URL specifying the entry to read.
		/// 
		/// </param>
		/// <param name="cons">      Constraints specific to the operation.
		/// 
		/// </param>
		/// <exception> LdapException if the object was not found
		/// </exception>
		public static LdapEntry Read(LdapUrl toGet, LdapSearchConstraints cons)
		{
			LdapConnection lconn = new LdapConnection();
			lconn.Connect(toGet.Host, toGet.Port);
			LdapEntry toReturn = lconn.Read(toGet.getDN(), toGet.AttributeArray, cons);
			lconn.Disconnect();
			return toReturn;
		}
		/// <summary>
		/// Searches the directory store at the specified path to see whether 
		/// an entry exists
		/// </summary>
		/// <param name="path">
		/// The path at which to search the directory store. 
		/// </param>
		/// <returns>
		/// true if an entry exists in the directory store at the specified 
		/// path; otherwise, false.
		/// </returns>
		public static bool Exists(string path)
		{
			LdapConnection aconn=new LdapConnection();
			LdapUrl lurl=new LdapUrl(path);
			aconn.Connect(lurl.Host,lurl.Port);
			aconn.Bind("","");
			if(CheckEntry(aconn,path))
				return true;
			else
				return false;
		}
        public ActionResult ChangeUserPass(string UserName, string PassWord, string RPassWord, string OldPassword)
        {
            string userName    = UserName.ToString();
            string newPassword = PassWord.ToString();
            string OldPass     = OldPassword.ToString();
            string RPass       = RPassWord.ToString();

            TempData["msg"] = "";

            if (newPassword == RPass)
            {
                // Creating an LdapConnection instance
                Novell.Directory.Ldap.LdapConnection ldapConn = new Novell.Directory.Ldap.LdapConnection();

                string dn = "uid=" + userName + ",ou=users,dc=example,dc=com";

                // Check if User Exists in LDAP
                if (CheckUser(userName, OldPass) == true)
                {
                    try
                    {
                        //Connect function will create a socket connection to the server
                        ldapConn.Connect(ldapHost, ldapPort);

                        //Bind function will Bind the user object Credentials to the Server
                        ldapConn.Bind(adminUname, adminPword);

                        ArrayList modList = new ArrayList();

                        //Replace the existing email  with the new email value
                        LdapAttribute attributes = new LdapAttribute("userPassword", newPassword);
                        modList.Add(new LdapModification(LdapModification.REPLACE, attributes));

                        LdapModification[] mods = new LdapModification[modList.Count];
                        Type mtype = Type.GetType("Novell.Directory.LdapModification");
                        mods = (LdapModification[])modList.ToArray(typeof(LdapModification));

                        //Modify the entry in the directory
                        ldapConn.Modify(dn, mods);
                    }

                    catch (Novell.Directory.Ldap.LdapException e)
                    {
                        string error = "Error: " + e;
                        TempData["msg"] = "<script>alert('" + error + "');</script>";
                        Thread.Sleep(2000);
                        return(View("Index"));
                    }


                    finally
                    {
                        // Disconnect from LDAP
                        ldapConn.Disconnect();
                    }

                    TempData["msg"] = "<script>alert('Password Changed Successfully!');</script>";
                    Thread.Sleep(2000);
                    return(View("Index"));
                }

                else
                {
                    TempData["msg"] = "<script>alert('Could not authenticate user!');</script>";
                    Thread.Sleep(2000);
                    return(View("Index"));
                }
            }

            else
            {
                TempData["msg"] = "<script>alert('New passwords do not match!');</script>";
                Thread.Sleep(2000);
                return(View("Index"));
            }
        }
    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(System.String[] args)
    {
        if (args.Length != 5)
        {
            System.Console.Error.WriteLine("Usage:   mono PartitionEntryCount <host Name> " + "<port number> <login dn> <password>" + "\n         <partition dn>");
            System.Console.Error.WriteLine("Example: mono PartitionEntryCount Acme.com 389 " + "\"cn=Admin,o=Acme\" secret" + "\n         \"ou=Sales,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  partitionDN = args[4];
        int            count       = 0;
        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");

            LdapExtendedOperation request = new PartitionEntryCountRequest(partitionDN);

            LdapExtendedResponse response = ld.ExtendedOperation(request);

            if ((response.ResultCode == LdapException.SUCCESS) && (response is PartitionEntryCountResponse))
            {
                count = ((PartitionEntryCountResponse)response).Count;
                System.Console.Out.WriteLine("\n    Entry count of partition " + partitionDN + " is: " + count);

                System.Console.Out.WriteLine("\nPartitionEntryCount succeeded\n");
            }
            else
            {
                System.Console.Out.WriteLine("\nPartitionEntryCount 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);
        }
        catch (Exception e)
        {
            Console.WriteLine("Error:" + e.Message);
            return;
        }
    }
        public LdapConnectionResult Test(string username, string password)
        {
            // Creating an LdapConnection instance
            var ldapConn       = new LdapConnection();
            var tempDomainName = new StringBuilder(100);

            if (!string.IsNullOrEmpty(_settings.DomainName))
            {
                tempDomainName.Append(_settings.DomainName);
                tempDomainName.Append('\\');
            }

            tempDomainName.Append(username);
            try
            {
                //Connect function will create a socket connection to the server
                ldapConn.Connect(_settings.Address, _settings.PortNumber);

                //Bind function will Bind the user object Credentials to the Server
                ldapConn.Bind(tempDomainName.ToString(), password);
            }
            catch (Exception e)
            {
                return(new LdapConnectionResult(false, e.Message, "Login"));
            }

            // Searches in the Marketing container and return all child entries just below this
            //container i.e. Single level search

            var claims = new List <ClaimViewModel>();

            try
            {
                var cons = ldapConn.SearchConstraints;
                cons.ReferralFollowing = true;
                ldapConn.Constraints   = cons;

                var attributes = _settings.Attributes?.Trim() == "" ? null : _settings.Attributes?.Split(",").Select(s => s.Trim());
                var lsc        = ldapConn.Search(_settings.DistinguishedName,
                                                 (int)Enum.Parse <SearchScope>(_settings.SearchScope),
                                                 $"(sAMAccountName={username})",
                                                 attributes?.ToArray(),
                                                 false,
                                                 (LdapSearchConstraints)null);

                while (lsc.HasMore())
                {
                    LdapEntry nextEntry = null;
                    try
                    {
                        nextEntry = lsc.Next();
                    }
                    catch (LdapException e)
                    {
                        ldapConn.Disconnect();
                        return(new LdapConnectionResult(false, e.Message, "Search Error"));
                    }
                    var attributeSet = nextEntry.GetAttributeSet();
                    System.Collections.IEnumerator ienum = attributeSet.GetEnumerator();
                    while (ienum.MoveNext())
                    {
                        var attribute     = (LdapAttribute)ienum.Current;
                        var attributeName = attribute.Name;
                        var attributeVal  = attribute.StringValue;

                        claims.Add(new ClaimViewModel(attributeName, attributeVal));
                    }
                }
            }
            catch (Exception e)
            {
                ldapConn.Disconnect();
                return(new LdapConnectionResult(false, e.Message, "Search Error"));
            }

            ldapConn.Disconnect();
            return(new LdapConnectionResult(true, claims.OrderBy(b => b.Type).ToList()));
        }
    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() );
        }
    }
Example #38
0
		/// <summary> get an LdapConnection object so that we can follow a referral.
		/// This function is never called if cons.getReferralFollowing() returns
		/// false.
		/// 
		/// </summary>
		/// <param name="referrals">the array of referral strings
		/// 
		/// 
		/// </param>
		/// <returns> The referralInfo object
		/// 
		/// </returns>
		/// <exception> LdapReferralException A general exception which includes
		/// an error message and an Ldap error code.
		/// </exception>
		private ReferralInfo getReferralConnection(System.String[] referrals)
		{
			ReferralInfo refInfo = null;
			System.Exception ex = null;
			LdapConnection rconn = null;
			LdapReferralHandler rh = defSearchCons.getReferralHandler();
			int i = 0;
			// Check if we use LdapRebind to get authentication credentials
			if ((rh == null) || (rh is LdapAuthHandler))
			{
				for (i = 0; i < referrals.Length; i++)
				{
					// dn, pw are null in the default case (anonymous bind)
					System.String dn = null;
					sbyte[] pw = null;
					try
					{
						rconn = new LdapConnection();
						rconn.Constraints = defSearchCons;
						LdapUrl url = new LdapUrl(referrals[i]);
						rconn.Connect(url.Host, url.Port);
						if (rh != null)
						{
							if (rh is LdapAuthHandler)
							{
								// Get application supplied dn and pw
								LdapAuthProvider ap = ((LdapAuthHandler) rh).getAuthProvider(url.Host, url.Port);
								dn = ap.DN;
								pw = ap.Password;
							}
						}
						rconn.Bind(Ldap_V3, dn, pw);
						ex = null;
						refInfo = new ReferralInfo(rconn, referrals, url);
						// Indicate this connection created to follow referral
						rconn.Connection.ActiveReferral = refInfo;
						break;
					}
					catch (System.Exception lex)
					{
						if (rconn != null)
						{
							try
							{
								rconn.Disconnect();
								rconn = null;
								ex = lex;
							}
							catch (LdapException e)
							{
								; // ignore
							}
						}
					}
				}
			}
				// Check if application gets connection and does bind
			else
			{
				//  rh instanceof LdapBind
				try
				{
					rconn = ((LdapBindHandler) rh).Bind(referrals, this);
					if (rconn == null)
					{
						LdapReferralException rex = new LdapReferralException(ExceptionMessages.REFERRAL_ERROR);
						rex.setReferrals(referrals);
						throw rex;
					}
					// Figure out which Url belongs to the connection
					for (int idx = 0; idx < referrals.Length; idx++)
					{
						try
						{
							LdapUrl url = new LdapUrl(referrals[idx]);
							if (url.Host.ToUpper().Equals(rconn.Host.ToUpper()) && (url.Port == rconn.Port))
							{
								refInfo = new ReferralInfo(rconn, referrals, url);
								break;
							}
						}
						catch (System.Exception e)
						{
							; // ignore
						}
					}
					if (refInfo == null)
					{
						// Could not match LdapBind.bind() connecction with URL list
						ex = new LdapLocalException(ExceptionMessages.REFERRAL_BIND_MATCH, LdapException.CONNECT_ERROR);
					}
				}
				catch (System.Exception lex)
				{
					rconn = null;
					ex = lex;
				}
			}
			if (ex != null)
			{
				// Could not connect to any server, throw an exception
				LdapException ldapex;
				if (ex is LdapReferralException)
				{
					throw (LdapReferralException) ex;
				}
				else if (ex is LdapException)
				{
					ldapex = (LdapException) ex;
				}
				else
				{
					ldapex = new LdapLocalException(ExceptionMessages.SERVER_CONNECT_ERROR, new System.Object[]{conn.Host}, LdapException.CONNECT_ERROR, ex);
				}
				// Error attempting to follow a referral
				LdapReferralException rex = new LdapReferralException(ExceptionMessages.REFERRAL_ERROR, ldapex);
				rex.setReferrals(referrals);
				// Use last URL string for the failed referral
				rex.FailedReferral = referrals[referrals.Length - 1];
				throw rex;
			}
			
			// We now have an authenticated connection
			// to be used to follow the referral.
			return refInfo;
		}
Example #39
-1
        static void Main(string[] args)
        {
            if ( args.Length != 4)
            {
            Console.WriteLine("Usage:   mono Bind <host name> <ldap port>  <login dn>" + " <password> ");
            Console.WriteLine("Example: mono Bind Acme.com 389"  + " \"cn=admin,o=Acme\"" + " secret ");
            return;
            }

            string ldapHost = args[0];
            int ldapPort = System.Convert.ToInt32(args[1]);
            String loginDN  = args[2];
            String password = args[3];
            try
            {
            LdapConnection conn= new LdapConnection();
            Console.WriteLine("Connecting to:" + ldapHost);
            conn.Connect(ldapHost,ldapPort);
            conn.Bind(loginDN,password);
            Console.WriteLine(" Bind Successfull");
            conn.Disconnect();
            }
            catch(LdapException e)
            {
            Console.WriteLine("Error:" + e.LdapErrorMessage);
            return;
            }
            catch(Exception e)
            {
            Console.WriteLine("Error:" + e.Message);
            return;
            }
        }
Example #40
-1
		/*
		* Ldap URL search
		*/
		
		/// <summary> Synchronously perfoms the search specified by the Ldap URL, using
		/// the specified search constraints (such as the maximum number of
		/// entries to find or the maximum time to wait for search results).
		/// 
		/// When this method is called, a new connection is created
		/// automatically, using the host and port specified in the URL. After
		/// all search results have been received from the server, the method
		/// closes the connection (in other words, it disconnects from the Ldap
		/// server).
		/// 
		/// As part of the search constraints, a choice can be made as to whether
		/// to have the results delivered all at once or in smaller batches. If
		/// the results are to be delivered in smaller batches, each iteration
		/// blocks only until the next batch of results is returned.
		/// 
		/// 
		/// </summary>
		/// <param name="toGet">         Ldap URL specifying the entry to read.
		/// 
		/// </param>
		/// <param name="cons">          The constraints specific to the search.
		/// 
		/// </param>
		/// <exception> LdapException A general exception which includes an error
		/// message and an Ldap error code.
		/// </exception>
		public static LdapSearchResults Search(LdapUrl toGet, LdapSearchConstraints cons)
		{
			LdapConnection lconn = new LdapConnection();
			lconn.Connect(toGet.Host, toGet.Port);
			if (cons == null)
			{
				// This is a clone, so we already have our own copy
				cons = lconn.SearchConstraints;
			}
			else
			{
				// get our own copy of user's constraints because we modify it
				cons = (LdapSearchConstraints) cons.Clone();
			}
			cons.BatchSize = 0; // Must wait until all results arrive
			LdapSearchResults toReturn = lconn.Search(toGet.getDN(), toGet.Scope, toGet.Filter, toGet.AttributeArray, false, cons);
			lconn.Disconnect();
			return toReturn;
		}