public void ChangePassword(
            string userDN,
            string oldPassword,
            string newPassword
            )
        {
            DirectoryAttributeModification deleteMod =
                new DirectoryAttributeModification();

            deleteMod.Name = "unicodePwd";
            deleteMod.Add(GetPasswordData(oldPassword));
            deleteMod.Operation = DirectoryAttributeOperation.Delete;

            DirectoryAttributeModification addMod =
                new DirectoryAttributeModification();

            addMod.Name = "unicodePwd";
            addMod.Add(GetPasswordData(newPassword));
            addMod.Operation = DirectoryAttributeOperation.Add;

            ModifyRequest request = new ModifyRequest(
                userDN,
                deleteMod,
                addMod
                );

            DirectoryResponse response = _connection.SendRequest(request);
        }
        /// <summary>
        /// For the username passed, change the password to the new value passed in newpassword
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="newPassword"></param>
        /// <returns></returns>
        public bool ChangePassword(
            string userName,
            string newPassword
            )
        {
            string attributeName  = this.PasswordPolicy.AttributeName;
            string attributeValue = newPassword;

            var modRequest = new ModifyRequest(
                userName, DirectoryAttributeOperation.Replace,
                attributeName, attributeValue);

            try
            {
                DirectoryResponse response = this.ldapConnection.SendRequest(modRequest);
                if (string.IsNullOrEmpty(response.ErrorMessage))
                {
                    return(true);
                }
            }
            catch (LdapException ex)
            {
                this.ldapLogger.logMessage(LogLevel.FATAL, this, "LDAPException thrown while updating password for user {0}: {1}", userName, ex.Message);
                return(false);
            }
            catch (DirectoryOperationException dex)
            {
                this.ldapLogger.logMessage(LogLevel.FATAL, this, "Directory operation exception thrown while updating password for user {0}: {1}", userName, dex.Message);
                return(false);
            }

            return(false);
        }
        /// <summary>
        /// called when data is available following an async call
        /// </summary>
        /// <param name="response">the fetched data</param>
        private List <MusicItem> FolderToMusicItems(DirectoryResponse response)
        {
            var ret        = new List <MusicItem>();
            var songOrDirs = response.directory.child;

            if (songOrDirs != null)
            {
                AddAll(songOrDirs, ret);
            }
            return(ret);
        }
Beispiel #4
0
 internal static void AssertSuccess(this DirectoryResponse response)
 {
     if (response == null)
     {
         throw new LdapException("Null response returned from server.");
     }
     if (response.ResultCode != ResultCode.Success)
     {
         throw new LdapException(response.ToLogString());
     }
 }
        public bool ModifyEntry(string dn, DirectoryAttributeModification[] attributes)
        {
            if (this.whatIf)
            {
                return(true);
            }

            var request = new ModifyRequest(dn, attributes);
            DirectoryResponse response = this.ldapConnection.SendRequest(request);

            ////var addResponse = response as AddResponse;
            return(response?.ResultCode == ResultCode.Success);
        }
        public bool DeleteEntry(string dn)
        {
            if (this.whatIf)
            {
                return(true);
            }

            var request = new DeleteRequest(dn);
            DirectoryResponse response = this.ldapConnection.SendRequest(request);

            ////var addResponse = response as AddResponse;
            return(response?.ResultCode == ResultCode.Success);
        }
        public bool MoveEntry(string oldDn, string newBaseDn, string cn)
        {
            if (this.whatIf)
            {
                return(true);
            }

            var request = new ModifyDNRequest(oldDn, newBaseDn, cn);
            DirectoryResponse response = this.ldapConnection.SendRequest(request);

            ////var addResponse = response as AddResponse;
            return(response?.ResultCode == ResultCode.Success);
        }
Beispiel #8
0
        public override LdapResultCompleteStatus Handle(SafeHandle handle, Native.Native.LdapResultType resType,
                                                        IntPtr msg, out DirectoryResponse response)
        {
            response = default;
            switch (resType)
            {
            case LdapForNet.Native.Native.LdapResultType.LDAP_RES_COMPARE:
                response = new CompareResponse();
                return(LdapResultCompleteStatus.Complete);

            default:
                return(LdapResultCompleteStatus.Unknown);
            }
        }
Beispiel #9
0
        public void CanCreateDirectoryResponse()
        {
            var directoryResponseXml = new StreamReader("Util\\TestResponses\\DirectoryResponse.xml").ReadToEnd();

            var directoryResponse = new DirectoryResponse(directoryResponseXml);

            Assert.AreEqual(20, directoryResponse.AcquirerId);
            Assert.AreEqual("2011-06-01T12:19:48.073Z", directoryResponse.CreateDateTimeStamp);
            Assert.AreEqual(DateTime.Parse("2011-06-01T12:19:48.073Z"), directoryResponse.CreateDateTimeStampLocalTime);
            Assert.AreEqual("2009-10-08T00:00:00.000Z", directoryResponse.DirectoryDateTimeStamp);
            Assert.AreEqual(DateTime.Parse("2009-10-08T00:00:00.000Z"), directoryResponse.DirectoryDateTimeStampLocalTime);
            Assert.AreEqual(3, directoryResponse.Issuers.Count);
            Assert.AreEqual(121, directoryResponse.Issuers.First().Id);
            Assert.AreEqual("Test Issuer", directoryResponse.Issuers.First().Name);
            Assert.AreEqual(ListType.Shortlist, directoryResponse.Issuers.First().ListType);
        }
Beispiel #10
0
        public override LdapResultCompleteStatus Handle(SafeHandle handle, Native.Native.LdapResultType resType,
                                                        IntPtr msg, out DirectoryResponse response)
        {
            response = default;
            switch (resType)
            {
            case LdapForNet.Native.Native.LdapResultType.LDAP_RES_EXTENDED:
                var    requestName  = IntPtr.Zero;
                var    requestValue = IntPtr.Zero;
                string name         = null;
                byte[] value        = null;
                var    rc           = Native.ldap_parse_extended_result(handle, msg, ref requestName, ref requestValue, 0);
                if (rc == (int)LdapForNet.Native.Native.ResultCode.Success)
                {
                    if (requestName != IntPtr.Zero)
                    {
                        name = Encoder.Instance.PtrToString(requestName);
                        Native.ldap_memfree(requestName);
                    }

                    if (requestValue != IntPtr.Zero)
                    {
                        var berval = Marshal.PtrToStructure <Native.Native.berval>(requestValue);
                        if (berval.bv_len != 0 && berval.bv_val != IntPtr.Zero)
                        {
                            value = new byte[berval.bv_len];
                            Marshal.Copy(berval.bv_val, value, 0, berval.bv_len);
                        }

                        Native.ldap_memfree(requestValue);
                    }
                }

                response = new ExtendedResponse
                {
                    ResultCode    = (Native.Native.ResultCode)rc,
                    ResponseName  = name,
                    ResponseValue = value
                };
                msg = IntPtr.Zero;
                return(LdapResultCompleteStatus.Complete);

            default:
                return(LdapResultCompleteStatus.Unknown);
            }
        }
Beispiel #11
0
        static void ReferralTest()
        {
            Console.WriteLine("Sending a request that will generate a referral");
            SearchRequest searchRequest = new SearchRequest();

            searchRequest.DistinguishedName =
                "OU=Users,DC=non-existing,DC=fabrikam,DC=com";

            // send the request through the connection
            DirectoryResponse response = ldapConnection.SendRequest(searchRequest);

            Console.WriteLine("ResultCode:" + response.ResultCode);
            foreach (Uri referral in response.Referral)
            {
                Console.WriteLine("Referral:" + referral);
            }

            Console.WriteLine("Referral is received successfully.");
        }
        internal static string ToLogString(this DirectoryResponse response)
        {
            var sb = new StringBuilder();

            sb.AppendFormat("{0} >", response.GetType().Name);
            sb.AppendLine();
            sb.AppendLine("ResultCode: " + response.ResultCode);
            sb.AppendLine("ErrorMessage: " + response.ErrorMessage);
            sb.AppendLine("MatchedDN: " + response.MatchedDN);
            sb.AppendLine("Referral: " + string.Join(", ", response.Referral.Select(u => u.ToString()).ToArray()));
            sb.AppendLine("RequestId: " + response.RequestId);
            sb.AppendLine("Controls: ");
            foreach (DirectoryControl control in response.Controls)
            {
                control.AppendTo(sb);
            }
            sb.AppendLine();
            return(sb.ToString());
        }
        public void SetPassword(
            string userDN,
            string password
            )
        {
            DirectoryAttributeModification pwdMod =
                new DirectoryAttributeModification();

            pwdMod.Name = "unicodePwd";
            pwdMod.Add(GetPasswordData(password));
            pwdMod.Operation = DirectoryAttributeOperation.Replace;

            ModifyRequest request = new ModifyRequest(
                userDN,
                pwdMod
                );

            DirectoryResponse response =
                _connection.SendRequest(request);
        }
        private DirectoryResponse SendChanges(List <DirectoryAttributeModification> changes)
        {
            var modifyRequest = new ModifyRequest();

            modifyRequest.DistinguishedName = DistinguishedName;


            foreach (var directoryAttributeModification in changes)
            {
                modifyRequest.Modifications.Add(directoryAttributeModification);
            }

            DirectoryResponse result = null;

            if (modifyRequest.Modifications.Count > 0)
            {
                result = _ldap.Connect().SendRequest(modifyRequest);
            }



            if (BackwardLinkMods?.Any() == true)
            {
                foreach (var forwardLinkMod in BackwardLinkMods)
                {
                    var backwardLinkAttribute =
                        _ldap.GetAttributeInfoByLinkID(forwardLinkMod.AttributeInfo.LinkedID.Value);


                    foreach (var s in forwardLinkMod.ValueAsEnumerableOf <string>())
                    {
                        _ldap.SetBacklinkAttribute(s, DistinguishedName, backwardLinkAttribute.Name);
                    }
                }
            }


            return(result);
        }
Beispiel #15
0
        public override LdapResultCompleteStatus Handle(SafeHandle handle, Native.Native.LdapResultType resType,
                                                        IntPtr msg, out DirectoryResponse response)
        {
            response = default;
            switch (resType)
            {
            case LdapForNet.Native.Native.LdapResultType.LDAP_RES_SEARCH_ENTRY:
                var ber = Marshal.AllocHGlobal(IntPtr.Size);
                _response.Entries.AddRange(GetLdapEntries(handle, msg, ber));
                Marshal.FreeHGlobal(ber);
                Native.ldap_msgfree(msg);
                return(LdapResultCompleteStatus.Partial);

            case LdapForNet.Native.Native.LdapResultType.LDAP_RES_SEARCH_REFERENCE:
                return(LdapResultCompleteStatus.Partial);

            case LdapForNet.Native.Native.LdapResultType.LDAP_RES_SEARCH_RESULT:
                response = _response;
                return(LdapResultCompleteStatus.Complete);

            default:
                return(LdapResultCompleteStatus.Unknown);
            }
        }
Beispiel #16
0
 // Token: 0x06001099 RID: 4249 RVA: 0x000501D8 File Offset: 0x0004E3D8
 public static SearchStatsControl FindSearchStatsControl(DirectoryResponse response)
 {
     return(SearchStatsControl.FindSearchStatsControl(response.Controls));
 }
Beispiel #17
0
        public static void HandleDirectoryResponse(Client client, DirectoryResponse packet)
        {
            if (client.Value.FrmFm == null)
            {
                return;
            }

            client.Value.FrmFm.Invoke((MethodInvoker) delegate { client.Value.FrmFm.lstDirectory.Items.Clear(); });

            new Thread(() =>
            {
                ListViewItem lviBack = new ListViewItem(new string[] { "..", "", "Directory" })
                {
                    Tag        = "dir",
                    ImageIndex = 0
                };

                client.Value.FrmFm.Invoke(
                    (MethodInvoker) delegate { client.Value.FrmFm.lstDirectory.Items.Add(lviBack); });

                if (packet.Folders.Length != 0)
                {
                    for (int i = 0; i < packet.Folders.Length; i++)
                    {
                        if (packet.Folders[i] != DELIMITER)
                        {
                            ListViewItem lvi = new ListViewItem(new string[] { packet.Folders[i], "", "Directory" })
                            {
                                Tag        = "dir",
                                ImageIndex = 1
                            };

                            try
                            {
                                client.Value.FrmFm.Invoke(
                                    (MethodInvoker) delegate { client.Value.FrmFm.lstDirectory.Items.Add(lvi); });
                            }
                            catch
                            {
                                break;
                            }
                        }
                    }
                }

                if (packet.Files.Length != 0)
                {
                    for (int i = 0; i < packet.Files.Length; i++)
                    {
                        if (packet.Files[i] != DELIMITER)
                        {
                            ListViewItem lvi =
                                new ListViewItem(new string[] { packet.Files[i], Helper.Helper.GetDataSize(packet.FilesSize[i]), "File" })
                            {
                                Tag        = "file",
                                ImageIndex = Helper.Helper.GetFileIcon(Path.GetExtension(packet.Files[i]))
                            };

                            try
                            {
                                client.Value.FrmFm.Invoke(
                                    (MethodInvoker) delegate { client.Value.FrmFm.lstDirectory.Items.Add(lvi); });
                            }
                            catch
                            {
                                break;
                            }
                        }
                    }
                }

                client.Value.LastDirectorySeen = true;
            }).Start();
        }
	public DirectoryOperationException(DirectoryResponse response, string message, System.Exception inner) {}
	public DirectoryOperationException(DirectoryResponse response, string message) {}
        /// <summary>
        ///
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="userPassword"></param>
        /// <param name="displayName"></param>
        /// <param name="employeeId"></param>
        /// <param name="employeeType"></param>
        /// <param name="errMessage"></param>
        /// <returns></returns>
        public bool CreateUser(
            string userName,
            string userPassword,
            string displayName,
            string employeeId,
            string employeeType,
            out string errMessage)
        {
            errMessage = string.Empty;
            var dn = string.Format("uid={0},ou=People,dc=cashamerica", userName);

            try
            {
                if (ldapConnection != null)
                {
                    var dAttrib = new DirectoryAttribute("objectClass")
                    {
                        "top", "person", "organizationalPerson", "inetOrgPerson"
                    };
                    var dGivenName = new DirectoryAttribute("givenName", userName);
                    var dSn        = new DirectoryAttribute("sn", userName);
                    var dCn        = new DirectoryAttribute("cn", userName);
                    var dPwd       = new DirectoryAttribute("userPassword", userPassword);
                    var dDisp      = new DirectoryAttribute("displayName", displayName);
                    var dEmpId     = new DirectoryAttribute("employeeNumber", employeeId);
                    var dEmpType   = new DirectoryAttribute("employeeType", employeeType);
                    var addRequest =
                        new AddRequest(
                            dn,
                            dAttrib,
                            dGivenName,
                            dSn,
                            dCn,
                            dPwd,
                            dDisp,
                            dEmpId,
                            dEmpType);
                    DirectoryResponse response = ldapConnection.SendRequest(addRequest);
                    errMessage = response.ErrorMessage;
                    if (string.IsNullOrEmpty(response.ErrorMessage))
                    {
                        return(true);
                    }
                }
            }
            catch (LdapException ex)
            {
                this.ldapLogger.logMessage(LogLevel.FATAL, this, "LDAPException thrown while creating user" + ex.Message);
                errMessage = ex.Message;
                return(false);
            }
            catch (DirectoryOperationException dex)
            {
                this.ldapLogger.logMessage(LogLevel.FATAL, this, "Directory operation exception thrown while creating user {0}", dex.Message);
                errMessage = dex.Message;
                return(false);
            }
            catch (Exception eX)
            {
                this.ldapLogger.logMessage(LogLevel.ERROR, this, "Exception thrown while adding user to LDAP: {0}", eX.Message);
                errMessage = eX.Message;
            }

            return(false);
        }
Beispiel #21
0
 public DirectoryOperationException(DirectoryResponse response, string message)
 {
 }
Beispiel #22
0
 public DirectoryOperationException(DirectoryResponse response, string message, System.Exception inner)
 {
 }
Beispiel #23
0
 public DirectoryOperationException(DirectoryResponse response)
 {
 }
        public override LdapResultCompleteStatus Handle(SafeHandle handle, Native.Native.LdapResultType resType, IntPtr msg, out DirectoryResponse response)
        {
            response = _response;
            LdapResultCompleteStatus resultStatus;

            switch (resType)
            {
            case LdapForNet.Native.Native.LdapResultType.LDAP_RES_SEARCH_ENTRY:
                var ber = Marshal.AllocHGlobal(IntPtr.Size);
                try
                {
                    var directoryEntries = GetLdapEntries(handle, msg, ber).ToList();
                    _response.Entries.AddRange(directoryEntries);

                    OnPartialResult(_response.MessageId, directoryEntries);
                }
                finally
                {
                    Marshal.FreeHGlobal(ber);
                    Native.ldap_msgfree(msg);
                }

                resultStatus = LdapResultCompleteStatus.Partial;
                break;

            case LdapForNet.Native.Native.LdapResultType.LDAP_RES_SEARCH_REFERENCE:
                var reference = GetLdapReference(handle, msg);
                if (reference != null)
                {
                    _response.References.Add(reference);
                }
                resultStatus = LdapResultCompleteStatus.Partial;
                break;

            case LdapForNet.Native.Native.LdapResultType.LDAP_RES_SEARCH_RESULT:
                resultStatus = LdapResultCompleteStatus.Complete;
                break;

            default:
                resultStatus = LdapResultCompleteStatus.Unknown;
                break;
            }

            return(resultStatus);
        }
	public void CopyTo(DirectoryResponse[] value, int i) {}
Beispiel #26
0
 public abstract LdapResultCompleteStatus Handle(SafeHandle handle, Native.Native.LdapResultType resType, IntPtr msg,
                                                 out DirectoryResponse response);
	public DirectoryOperationException(DirectoryResponse response) {}
Beispiel #28
0
 public override LdapResultCompleteStatus Handle(SafeHandle handle, Native.Native.LdapResultType resType,
                                                 IntPtr msg, out DirectoryResponse response)
 {
     throw new NotImplementedException();
 }
Beispiel #29
0
        public string Reset(string Username, string OldPassword, string NewPassword1, string NewPassword2)
        {
            string    returnInfo = "";
            string    server     = "192.168.144.21:636";
            string    domain     = "pmhu.local";
            const int ldapErrorInvalidCredentials = 0x31;

            try
            {
                var ldapConnection    = new LdapConnection(server);
                var networkCredential = new NetworkCredential(Username, OldPassword, domain);
                ldapConnection.SessionOptions.SecureSocketLayer = true;
                ldapConnection.AuthType = AuthType.Negotiate;
                ldapConnection.Bind(networkCredential);

                returnInfo = "A felhasználó hitelesített!";

                DirectoryEntry    entry   = new DirectoryEntry("LDAP://" + server, Username, OldPassword);
                DirectorySearcher Dsearch = new DirectorySearcher(entry);
                Dsearch.Filter = "(&(objectClass=user)(samaccountname=" + Username + "))";
                SearchResult result = Dsearch.FindOne();

                if (result != null)
                {
                    DirectoryEntry userEntry = result.GetDirectoryEntry();
                    string         Name      = userEntry.Properties["name"].Value.ToString();
                    string         userDN    = userEntry.Properties["distinguishedName"].Value.ToString();
                    if ((NewPassword1 != "") && (NewPassword2 != "") && (NewPassword1 == NewPassword2))
                    {
                        returnInfo = "A jelszavak egyeznek!";
                        try
                        {
                            DirectoryAttributeModification deleteMod = new DirectoryAttributeModification();
                            deleteMod.Name = "unicodePwd";
                            deleteMod.Add(GetPasswordData(OldPassword));
                            deleteMod.Operation = DirectoryAttributeOperation.Delete;

                            DirectoryAttributeModification addMod = new DirectoryAttributeModification();
                            addMod.Name = "unicodePwd";
                            addMod.Add(GetPasswordData(NewPassword1));
                            addMod.Operation = DirectoryAttributeOperation.Add;

                            ModifyRequest     request  = new ModifyRequest(userDN, deleteMod, addMod);
                            DirectoryResponse response = ldapConnection.SendRequest(request);
                            returnInfo = "A jelszó módosítása sikerült!";
                        }
                        catch (Exception excep)
                        {
                            returnInfo  = "A jelszó módosítása nem sikerült!";
                            returnInfo += excep.Message;
                        }
                    }
                    else
                    {
                        returnInfo = "A jelszavaknak egyezni kell és nem lehet üres!";
                    }
                }
            }
            catch (LdapException ldapException)
            {
                // Invalid credentials throw an exception with a specific error code
                if (ldapException.ErrorCode.Equals(ldapErrorInvalidCredentials))
                {
                    //return false;
                    returnInfo = "A felhasználói adatok nem megfelelőek!";
                }
                returnInfo = "Kapcsolódási hiba!";
            }
            return(returnInfo);
        }