Bind() private method

private Bind ( int version, System dn, sbyte passwd, LdapResponseQueue queue ) : LdapResponseQueue
version int
dn System
passwd sbyte
queue LdapResponseQueue
return LdapResponseQueue
        public static IPrincipal AuthenticateUser(string domain, string userName, string password, out string errorMessage)
        {
            WindowsPrincipal principal = null;
            int responseCode;
            errorMessage = null;

            if (UserInfo.IsLocalDomain(domain))
            {
                // Set the domain as the local machine if one is not specified
                if (string.IsNullOrEmpty(domain))
                    domain = Environment.MachineName;

                responseCode = AuthenticateUser(userName, password);

                if (responseCode == 0)
                    principal = new WindowsPrincipal(new UnixIdentity(domain, userName));
                else
                    errorMessage = string.Format("Failed to authenticate \"{0}\": {1}", userName, GetPAMErrorMessage(responseCode));
            }
            else
            {
                // Attempt PAM based authentication first - if configured, this will be the best option
                string domainUserName = string.Format("{0}\\{1}", domain, userName);

                responseCode = AuthenticateUser(domainUserName, password);

                if (responseCode == 0)
                    principal = new WindowsPrincipal(new UnixIdentity(domain, userName));

                // Try really hard to find a configured LDAP host
                string ldapHost = GetLdapHost();

                // If LDAP host cannot be determined, no LdapConnection can be established - if authentication
                // succeeded, user will be treated as a local user
                if ((object)ldapHost == null)
                {
                    if ((object)principal == null)
                        errorMessage = string.Format("Failed to authenticate \"{0}\": {1}", domainUserName, GetPAMErrorMessage(responseCode));
                    else
                        errorMessage = string.Format("User authentication succeeded, but no LDAP path could be derived.");
                }
                else
                {
                    try
                    {
                        // Attempt LDAP account authentication                    
                        LdapConnection connection = new LdapConnection();

                        if (ldapHost.StartsWith("LDAP", StringComparison.OrdinalIgnoreCase))
                        {
                            Uri ldapURI = new Uri(ldapHost);
                            ldapHost = ldapURI.Host + (ldapURI.Port == 0 ? "" : ":" + ldapURI.Port);
                        }

                        // If host LDAP path contains suffixed port number (e.g., host:port), this will be preferred over specified 389 default
                        connection.Connect(ldapHost, 389);
                        connection.Bind(string.Format("{0}@{1}", userName, domain), password);

                        if ((object)principal == null)
                            principal = new WindowsPrincipal(new UnixIdentity(domain, userName, connection));
                        else
                            ((UnixIdentity)principal.Identity).Connection = connection;
                    }
                    catch (Exception ex)
                    {
                        if (responseCode == 0)
                            errorMessage = string.Format("User authentication succeeded, but LDAP connection failed. LDAP response: {0}", ex.Message);
                        else
                            errorMessage = string.Format("LDAP response: {0}{1}PAM response: {2}", ex.Message, Environment.NewLine, GetPAMErrorMessage(responseCode));
                    }
                }
            }

            // Set current thread principal to authenticated user principal - this will allow access to
            // needed LdapConnection information on the current thread...
            Thread.CurrentPrincipal = principal;

            return principal;
        }
        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);
        }
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 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());
        }
    }
    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 #7
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 #8
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 #9
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 #10
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 #11
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 #13
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);
        }
    }
		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);
		}
Example #15
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 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 #17
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 #18
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 #19
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 #21
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 #22
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 #23
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 #24
0
        static void Main(string[] args)
        {
            if ( args.Length != 5)
            {
                Console.WriteLine("Usage:   mono SearchPersist <host name> <ldap port>  <login dn>" + " <password> <search base>" );
                Console.WriteLine("Example: mono SearchPersist Acme.com 389"  + " \"cn=admin,o=Acme\"" + " secret \"ou=sales,o=Acme\"");
                return;
            }

            int ldapVersion  = LdapConnection.Ldap_V3;
            String ldapHost = args[0];
            int ldapPort = Convert.ToInt32(args[1]);;
            String loginDN = args[2];
            String password = args[3];
            String searchBase = args[4];
            LdapSearchQueue queue = null;
            LdapSearchConstraints constraints;
            LdapPersistSearchControl psCtrl;
            LdapConnection lc = new LdapConnection();
            constraints =  new LdapSearchConstraints();

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

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

                // add the persistent search control to the search constraints
                constraints.setControls( psCtrl );

                // perform the search with no attributes returned
                String[] noAttrs = {LdapConnection.NO_ATTRS};
                queue = lc.Search(
                    searchBase,                // container to search
                    LdapConnection.SCOPE_SUB,  // search container's subtree
                    "(objectClass=*)",         // search filter, all objects
                    noAttrs,                   // don't return attributes
                    false,                     // return attrs and values, ignored
                    null,                      // use default search queue
                    constraints);              // use default search constraints
            }
            catch( LdapException e )
            {
                Console.WriteLine( "Error: " + e.ToString() );
                try { lc.Disconnect(); }
                catch(LdapException e2) {  }
                Environment.Exit(1);
            }
            catch(Exception e)
            {
                Console.WriteLine( "Error: " + e.Message );
                return;
            }

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

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

            try
            {
                //Monitor till the timeout happens
                while (DateTime.Now.CompareTo(timeOut) < 0)
                {
                    if (!checkForAChange(queue))
                        break;
                    System.Threading.Thread.Sleep(10);
                }
            }
            catch (System.IO.IOException e)
            {
                System.Console.Out.WriteLine(e.Message);
            }
            catch (System.Threading.ThreadInterruptedException e)
            {
            }

            //Disconnect from the server before exiting
            try
            {
                lc.Abandon(queue); //abandon the search
                lc.Disconnect();
            }
            catch (LdapException e)
            {
                Console.Out.WriteLine();
                Console.Out.WriteLine("Error: " + e.ToString());
            }

            Environment.Exit(0);
        }
		/// <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;
		}
Example #26
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);

		}
        static void Main( string[] args )
        {
            if (args.Length != 6)
            {
                System.Console.Error.WriteLine("Usage:   mono GetEffectivePrivilegesList " + "<host Name> <port number> <login dn> " + "\n         <password> <object dn> <trustee dn>");
                System.Console.Error.WriteLine("Example: mono GetEffectivePrivilegesList 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],null}"
                //String rightName = "{[All Attributes Rights],null}";
                //String rightName = "{attr1,attr2,attr3,.... ,null}"
                System.String[] rightName = {"acl","cn","dn",null};
                LdapExtendedOperation request = new GetEffectivePrivilegesListRequest(objectDN,trusteeDN,rightName);
                LdapExtendedResponse response = ld.ExtendedOperation(request);

                if ( response.ResultCode == LdapException.SUCCESS &&
                    ( response is GetEffectivePrivilegesListResponse ))
                {
                    iRight = ((GetEffectivePrivilegesListResponse)response).getPrivileges();
                    if(iRight.Length == (rightName.Length-1))
                    {
                        sRight = new System.String[iRight.Length];
                        for ( int i =0 ; rightName[i] != null ; i++)
                        {
                            if ( rightName[i].ToUpper().Equals("[Entry Rights]".ToUpper()) )
                                sRight[i] = "object rights";
                            else if ( rightName[i].ToUpper().Equals("[All Attributes Rights]".ToUpper()))
                                sRight[i] = "attribute rights";
                            else
                                sRight[i] = rightName[i];
                        }
                        System.Console.WriteLine("\"" + trusteeDN + "\" has the following rights on \""+ objectDN+"\'s ");
                        for(int i=0;rightName[i]!=null;i++)
                        {
                            System.Console.WriteLine("'" + sRight[i] + "':");
                            PrintRights( rightName[i], iRight[i] );
                            System.Console.WriteLine("\nGet Effective Privileges succeeded");
                        }
                    }
                    else
                    {
                        System.Console.WriteLine("You have provided the wrong input in terms of attribute list");
                    }
                }
                else
                {
                    System.Console.WriteLine("Get Effective Privileges List 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);
            }
        }
Example #28
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());
        }
    }
    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 #30
0
        static void Main(string[] args)
        {
            if ( args.Length != 6)
            {
            Console.WriteLine("Usage:   mono Search <host name> <ldap port>  <login dn>" + " <password> <search base>" + " <search filter>");
            Console.WriteLine("Example: mono Search Acme.com 389"  + " \"cn=admin,o=Acme\"" + " secret \"ou=sales,o=Acme\"" + "         \"(objectclass=*)\"");
            return;
            }

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

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

            while (lsc.hasMore())
            {
                LdapEntry nextEntry = null;
                try
                {
                    nextEntry = lsc.next();
                }
                catch(LdapException e)
                {
                    Console.WriteLine("Error: " + e.LdapErrorMessage);
                    // Exception is thrown, go for next entry
                continue;
                }
                Console.WriteLine("\n" + nextEntry.DN);
                LdapAttributeSet attributeSet = nextEntry.getAttributeSet();
                System.Collections.IEnumerator ienum=attributeSet.GetEnumerator();
                while(ienum.MoveNext())
                {
                    LdapAttribute attribute=(LdapAttribute)ienum.Current;
               					string attributeName = attribute.Name;
                    string attributeVal = attribute.StringValue;
                    if(!Base64.isLDIFSafe(attributeVal))
                    {
                        byte[] tbyte=SupportClass.ToByteArray(attributeVal);
                        attributeVal=Base64.encode(SupportClass.ToSByteArray(tbyte));
                    }
               				        Console.WriteLine( attributeName + "value:" + attributeVal);
                }
            }
            conn.Disconnect();
            }
            catch(LdapException e)
            {
            Console.WriteLine("Error:" + e.LdapErrorMessage);
            return;
            }
            catch(Exception e)
            {
            Console.WriteLine("Error:" + e.Message);
            return;
            }
        }
Example #31
0
        static void Main( string[] args )
        {
            if ( args.Length != 4 )
            {
            Console.WriteLine("Usage:   mono InteractiveSSL <host name> <ldap port>  <login dn> <password>\n");
            Console.WriteLine("Example: mono InteractiveSSL Acme.com 636"  + " \"cn=admin,o=Acme\"" + " secret\n");
            return;
            }
            LdapConnection conn=null;
            string ldapHost = args[0];
            int ldapPort = System.Convert.ToInt32(args[1]);
            String loginDN  = args[2];
            String password = args[3];
            bHowToProceed = true;
            String continueBind;

            try
            {
            do
            {
                bindCount++;
                conn= new LdapConnection();
                conn.SecureSocketLayer=true;
                Console.WriteLine( "Connecting to:" + ldapHost );

                conn.UserDefinedServerCertValidationDelegate += new
                    CertificateValidationCallback(MySSLHandler);
                if(bHowToProceed == false)
                    conn.Disconnect();
                if(bHowToProceed == true)
                {
                    conn.Connect(ldapHost,ldapPort);
                    conn.Bind(loginDN,password);
                    Console.WriteLine( " SSL Bind Successfull " );
                    conn.Disconnect();
                }

                Console.WriteLine ( "\nDo you wish to Bind again to the server (y/n)?" );
                continueBind = Console.ReadLine();

                if(continueBind == "y" || continueBind == "Y")
                    quit = false;
                if(continueBind == "n" || continueBind == "N")
                    quit = true;

            }while(quit == false);
            }
            catch(LdapException ee)
            {
            Console.WriteLine(ee.LdapErrorMessage);
            }
            catch(Exception e)
            {
            Console.WriteLine(e.StackTrace);
            }
            conn.Disconnect();
        }
        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()));
        }
        private UnixIdentity AttemptAnonymousBinding(UnixIdentity unixIdentity)
        {
            try
            {
                // Try really hard to find a configured LDAP host
                string ldapHost = string.IsNullOrEmpty(m_parent.m_ldapPath) ? GetLdapHost() : m_parent.m_ldapPath;

                // If LDAP host cannot be determined, no LdapConnection can be established
                if (!string.IsNullOrEmpty(ldapHost))
                {
                    // Attempt LDAP account authentication                    
                    LdapConnection connection = new LdapConnection();

                    if (ldapHost.StartsWith("LDAP", StringComparison.OrdinalIgnoreCase))
                    {
                        Uri ldapURI = new Uri(ldapHost);
                        ldapHost = ldapURI.Host + (ldapURI.Port == 0 ? "" : ":" + ldapURI.Port);
                    }

                    // If host LDAP path contains suffixed port number (e.g., host:port), this will be preferred over specified 389 default
                    connection.Connect(ldapHost, 389);
                    connection.Bind(null, null);

                    if ((object)unixIdentity == null)
                    {
                        unixIdentity = new UnixIdentity(m_parent.Domain, m_parent.UserName, connection);
                        Thread.CurrentPrincipal = new WindowsPrincipal(unixIdentity);
                    }
                    else
                    {
                        unixIdentity.Connection = connection;
                    }

                    m_connection = connection;
                    m_ldapRoot = unixIdentity.LdapRoot ?? m_parent.Domain;

                    if (string.IsNullOrEmpty(m_parent.m_ldapPath))
                        m_parent.m_ldapPath = ldapHost;
                }
            }
            catch
            {
                m_connection = null;
            }

            return unixIdentity;
        }
		/// <summary> Initializes the Connection and other properties.
		/// 
		/// </summary>
		private void InitBlock()
		{
			try			{
				_conn= new LdapConnection ();
				LdapUrl lUrl=new LdapUrl (Path);
				_conn.Connect(lUrl.Host,lUrl.Port);
				_conn.Bind(Username,Password);
			}
			catch(LdapException ex)			{
				throw ex;
			}
			catch(Exception e)			{
				throw 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 #36
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 #37
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;
		}
		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);

		}
        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"));
            }
        }
Example #40
-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;
            }
        }