Esempio n. 1
0
        private void SetPassword(string username, string newPassword)
        {
            var distinguishedName = string.Format(@"CN={0},{1}", username, _config.DistinguishedName);

            Logger.Info("Setting password for user: \"{0}\"", username);
            Logger.Info("Distinguished name: \"{0}\"", distinguishedName);

            // the 'unicodePWD' attribute is used to handle pwd handling requests
            const string attribute = "unicodePwd";

            if (!String.IsNullOrEmpty(newPassword))
            {
                // do we have a pwd to set -> set pwd
                var directoryAttributeModificationReplace = new DirectoryAttributeModification
                {
                    Name      = attribute,
                    Operation = DirectoryAttributeOperation.Replace
                };

                directoryAttributeModificationReplace.Add(BuildBytePwd(newPassword));

                var damList       = new[] { directoryAttributeModificationReplace };
                var modifyRequest = new ModifyRequest(distinguishedName, damList);

                // Should we utilize pwd history on the pwd reset?
                var value      = BerConverter.Encode("{i}", new object[] { 0x1 });
                var pwdHistory = new DirectoryControl(LdapServerPolicyHintsOid, value, false, true);

                modifyRequest.Controls.Add(pwdHistory);

                var response = _connection.SendRequest(modifyRequest);

                // TODO: handle bad response.
            }
        }
 public void Decode(byte[] data)
 {
     this.Tag = GetMessageType(data);
     object[] message = BerConverter.Decode("{iV}", data);
     this.MessageID  = (int)message[0];
     this.ProtocolOp = message[1];
 }
Esempio n. 3
0
        public void PageCookie(int pageSize)
        {
            FirstPagingRun = true;

            LastPageSize = pageSize;

            byte[] cvalue = BerConverter.Encode("{io}", new object[] { pageSize, PagingCookie });

            DirectoryControl dcpage = new DirectoryControl("1.2.840.113556.1.4.319", cvalue, true, true);

            if (PagingCookie != null)
            {
                PageControl = new PageResultRequestControl(PagingCookie);
            }

            else if (Scope != SearchScope.Base)
            {
                PageControl = new PageResultRequestControl(pageSize);
            }

            if (PageControl != null)
            {
                PageCount = 0;

                Request.Controls.Add(PageControl);

                DoPaging = true;
            }
        }
        public byte[] Encode(int type)
        {
            switch (type)
            {
            case 3:
            {
                LDAPBindResponse protocolOp = (LDAPBindResponse)this.ProtocolOp;
                return(BerConverter.Encode("{it{eooto}}", this.MessageID, 0x61, protocolOp.ResultCode, protocolOp.MatchedDN, protocolOp.DiagnosticMessage, 0x87, protocolOp.ServerSaslCreds));
            }

            case 4:
            {
                LDAPSearchResEntry protocolOp = (LDAPSearchResEntry)this.ProtocolOp;
                return(BerConverter.Encode("{it{sto}}", this.MessageID, 0x64, protocolOp.ObjectDN, 0x30, protocolOp.Attributes));
            }

            case 5:
            {
                LDAPSearchResDone protocolOp = (LDAPSearchResDone)this.ProtocolOp;
                return(BerConverter.Encode("{it{eoo}}", this.MessageID, 0x65, protocolOp.ResultCode, protocolOp.MatchedDN, protocolOp.ErrorMessage));
            }
            }

            return(null);
        }
Esempio n. 5
0
        protected void StatsCookie()
        {
            if (QueryInfo.ExecStatsQuery)
            {
                if (QueryInfo.RootDse)
                {
                    GlobalEventHandler.RaiseErrorOccured("Retreiving statistics from a rootDSE query cannot be done", true);
                }

                else if (QueryInfo.MustGetSingleObjectPath)
                {
                    GlobalEventHandler.RaiseErrorOccured(String.Format("Switched to single object path base query {0}\t-> retreiving staistics doesn't make sense", Environment.NewLine), true);
                }

                else
                {
                    RetreiveStatistics = QueryInfo.ExecStatsQuery;

                    byte[] controlvalue = BerConverter.Encode("{i}", new object[] { 0x1 });

                    controlvalue = null;

                    Request.Controls.Add(new DirectoryControl(STATISTCS_CONTROL_OID, controlvalue, false, true));
                }
            }
        }
Esempio n. 6
0
        public void Encode_Objects_ReturnsExpected(string format, object[] values, byte[] expected)
        {
            var actual = BerConverter.Encode(format, values);

            _testOutputHelper.WriteLine($"expected: [{string.Join(',', expected)}]");
            _testOutputHelper.WriteLine($"actual: [{string.Join(',', actual)}]");
            Assert.Equal(expected, actual);
        }
Esempio n. 7
0
        public void Decode_Bytes_ReturnsExpected(string format, byte[] values, object[] expected)
        {
            var value = BerConverter.Decode(format, values);

            _testOutputHelper.WriteLine($"expected: [{string.Join(',', expected)}]");
            _testOutputHelper.WriteLine($"actual: [{string.Join(',', value)}]");
            Assert.Equal(expected, value);
        }
Esempio n. 8
0
 public void Encode_Invalid_ThrowsArgumentException(string format, object[] values)
 {
     try
     {
         AssertExtensions.Throws <ArgumentException>(null, () => BerConverter.Encode(format, values));
     }
     catch (System.Exception ex)
     {
         Console.WriteLine(ex.GetType().Name + ":" + ex.Message);
     }
 }
Esempio n. 9
0
        public List <DynamicBerConverterField> Decode(byte[] val)
        {
            List <DynamicBerConverterField> ret = new List <DynamicBerConverterField>();

            object[] decoded = null;

            int berpos = -1;

            foreach (int curpos in ConversionRules.Keys)
            {
                try
                {
                    decoded = BerConverter.Decode(ConversionRules[curpos], val);

                    berpos = curpos;

                    break;
                }

                catch (Exception ex)
                { ex.ToDummy(); }
            }

            if (berpos != -1)
            {
                try
                {
                    foreach (int pos in FieldNames[berpos].Keys)
                    {
                        DynamicBerConverterField bf = new DynamicBerConverterField();

                        bf.Name = FieldNames[berpos][pos];

                        bf.FieldType = FieldTypes[berpos][pos];

                        bf.Value = Convert.ChangeType(decoded[pos], bf.FieldType);

                        if (bf.FieldType == typeof(string))
                        {
                            bf.Value = ((string)bf.Value).Replace("\0", String.Empty);
                        }                                                              // \0 -> nothing returned due to missing perms?

                        ret.Add(bf);
                    }
                }

                catch (Exception ex)
                { ex.ToDummy(); }
            }

            return(ret);
        }
Esempio n. 10
0
        public static SearchStats Parse(byte[] value)
        {
            SearchStats searchStats = null;

            try
            {
                object[] array = BerConverter.Decode("{iiiiiiiiiaia}", value);
                searchStats                 = new SearchStats();
                searchStats.callTime        = (int)array[3];
                searchStats.entriesReturned = (int)array[5];
                searchStats.entriesVisited  = (int)array[7];
                searchStats.filter          = (string)array[9];
                searchStats.index           = (string)array[11];
            }
            catch (BerConversionException)
            {
            }
            catch (InvalidCastException)
            {
            }
            catch (DecoderFallbackException)
            {
            }
            if (searchStats != null)
            {
                if (!string.IsNullOrEmpty(searchStats.filter))
                {
                    SearchStats searchStats2 = searchStats;
                    string      text         = searchStats.filter;
                    char[]      trimChars    = new char[1];
                    searchStats2.filter = text.TrimEnd(trimChars);
                }
                if (string.IsNullOrEmpty(searchStats.filter))
                {
                    searchStats.filter = "<null>";
                }
                if (!string.IsNullOrEmpty(searchStats.index))
                {
                    SearchStats searchStats3 = searchStats;
                    string      text2        = searchStats.index;
                    char[]      trimChars2   = new char[1];
                    searchStats3.index = text2.TrimEnd(trimChars2);
                }
                if (string.IsNullOrEmpty(searchStats.index))
                {
                    searchStats.index = "<null>";
                }
            }
            return(searchStats);
        }
Esempio n. 11
0
        public void Encode_Decode_Should_Returns_Expected(string printFormat, string scanFormat, object[] values,
                                                          string[] platforms = null)
        {
            if (platforms != null && !platforms.Any(_ => RuntimeInformation.IsOSPlatform(OSPlatform.Create(_))))
            {
                return;
            }
            var encoded = BerConverter.Encode(printFormat, values);

            _testOutputHelper.WriteLine($"encoded: [{string.Join(',', encoded)}]");
            var decoded = BerConverter.Decode(scanFormat, encoded);

            Assert.Equal(values, decoded);
        }
Esempio n. 12
0
        static void HandleBerConversionException()
        {
            try
            {
                Console.WriteLine("\r\nTrying to decode a binary " +
                                  "value with an incorrect decode string...");

                BerConverter.Decode("{iii}",
                                    new byte[] { 0x00, 0xFF, 0x30, 0x84, 0x00, 0x00, 0x00 });
            }
            catch (BerConversionException e)
            {
                Console.WriteLine(e.GetType().Name + ": Message:" + e.Message);
            }
        }
Esempio n. 13
0
 internal static void TransformControls(DirectoryControl[] controls)
 {
     if (controls != null)
     {
         for (int i = 0; i < (int)controls.Length; i++)
         {
             if (!(controls[i].GetType() != typeof(DirectoryControl)) && controls[i].Type == "1.2.840.113556.1.4.1504")
             {
                 byte[]               value                = controls[i].GetValue();
                 object[]             objArray             = BerConverter.Decode("{e}", value);
                 int                  num                  = (int)objArray[0];
                 ADAsqResponseControl aDAsqResponseControl = new ADAsqResponseControl(num, controls[i].IsCritical, value);
                 controls[i] = aDAsqResponseControl;
             }
         }
         return;
     }
     else
     {
         return;
     }
 }
Esempio n. 14
0
 public void Encode_Objects_ReturnsExpected(string format, object[] values, byte[] expected)
 {
     AssertExtensions.Equal(expected, BerConverter.Encode(format, values));
 }
Esempio n. 15
0
 public void Decode_Invalid_ThrowsBerConversionException(string format, byte[] values)
 {
     Assert.Throws <BerConversionException>(() => BerConverter.Decode(format, values));
 }
Esempio n. 16
0
 public void UnknownFormat_ThrowsArgumentException(string format, byte[] values)
 {
     AssertExtensions.Throws <ArgumentException>(null, () => BerConverter.Decode(format, values));
 }
Esempio n. 17
0
        public void Decode_Bytes_ReturnsExpected(string format, byte[] values, object[] expected)
        {
            object value = BerConverter.Decode(format, values);

            Assert.Equal(expected, value);
        }
Esempio n. 18
0
 public void Encode_InvalidFormat_ThrowsBerConversionException(string format)
 {
     Assert.Throws <BerConversionException>(() => BerConverter.Encode(format, new object[0]));
 }
Esempio n. 19
0
        static void DoBerEncoding()
        {
            try
            {
                bool     boolValue    = true;
                int      intValue     = 5;
                byte[]   binaryValue  = new byte[] { 0x00, 0x01, 0x02, 0x03 };
                string   strValue     = "abcdef";
                string[] strValues    = { "abc", "def", "xyzw" };
                byte[][] binaryValues =
                {
                    new byte[] { 0x00, 0x01, 0x02, 0x03 },
                    new byte[] { 0x04, 0x05, 0x06, 0x07 },
                    new byte[] { 0x08, 0x09,0x0A },
                    new byte[] { 0x0B, 0x0C }
                };

                Console.WriteLine("\r\nBer encoding objects...");
                byte[] berEncodedValue = BerConverter.Encode("{bios{v}{V}}",
                                                             new object[] {
                    boolValue,
                    intValue,
                    binaryValue,
                    strValue,
                    strValues,
                    binaryValues
                });

                Console.WriteLine("\r\nBer decoding the byte array...");
                object[] decodedObjects = BerConverter.Decode("{biOavV}",
                                                              berEncodedValue);

                Console.WriteLine("\r\nThe decoded objects are:");
                foreach (object o in decodedObjects)
                {
                    if (o is byte[])
                    {
                        Console.WriteLine(ByteArrayToStringInHex((byte[])o));
                    }
                    else if (o is byte[][])
                    {
                        byte[][] byteArrays = (byte[][])o;
                        for (int i = 0; i < byteArrays.Length; i++)
                        {
                            Console.Write(ByteArrayToStringInHex(byteArrays[i])
                                          + " - ");
                        }
                        Console.WriteLine();
                    }
                    else if (o is string[])
                    {
                        string[] strArray = (string[])o;
                        for (int i = 0; i < strArray.Length; i++)
                        {
                            Console.Write(strArray[i] + " - ");
                        }
                        Console.WriteLine();
                    }
                    else
                    {
                        Console.WriteLine(o);
                    }
                }
            }
            catch (BerConversionException e)
            {
                Console.WriteLine("BerConversionException:" + e.Message);
            }
            catch (ArgumentException e)
            {
                Console.WriteLine("ArgumentException:" + e.Message);
            }
        }
 public override byte[] GetValue()
 {
     _directoryControlValue = BerConverter.Encode("{s}", new object[] { AttributeName });
     return(base.GetValue());
 }
 public byte[] Encode(LDAPSearchResDone resdone)
 {
     return(BerConverter.Encode("{it{eoo}}", this.MessageID, 0x65, resdone.ResultCode, resdone.MatchedDN, resdone.ErrorMessage));
 }
        /// <summary>
        /// LDAP でパスワードを変更する。
        /// </summary>
        /// <param name="accountDN">アカウントの DN</param>
        /// <param name="oldPasswd">現在のパスワード</param>
        /// <param name="newPasswd">変更後のパスワード</param>
        /// <param name="ldapServer">LDAP サーバーのホスト名または IP アドレス</param>
        /// <param name="isTls">LDAPS にする場合 true。LDAP のままにする場合 false。</param>
        public static void ChangePassword(string accountDN, string oldPasswd, string newPasswd, string ldapServer, bool isTls)
        {
            if (accountDN == null || oldPasswd == null || newPasswd == null || ldapServer == null)
            {
                throw new ArgumentNullException();
            }

            if (accountDN.Length < 1 || oldPasswd.Length < 1 || newPasswd.Length < 1 || ldapServer.Length < 1)
            {
                throw new ArgumentException();
            }

            ldapServer = ServerPortSpecify(ldapServer, isTls);

            LdapConnection ldapConnection = new LdapConnection(ldapServer)
            {
                Credential = new NetworkCredential(accountDN, oldPasswd),
                AuthType   = AuthType.Basic,
                Timeout    = new TimeSpan(0, 0, 10)
            };

            ldapConnection.SessionOptions.ProtocolVersion   = 3;
            ldapConnection.SessionOptions.SecureSocketLayer = isTls;

            // https://tools.ietf.org/html/rfc3062
            var ber = BerConverter.Encode("{tststs}",
                                          LDAP_TAG_EXOP_MODIFY_PASSWD_ID, accountDN,
                                          LDAP_TAG_EXOP_MODIFY_PASSWD_OLD, oldPasswd,
                                          LDAP_TAG_EXOP_MODIFY_PASSWD_NEW, newPasswd);
            var modifyPasswdRequest = new ExtendedRequest(LDAP_EXOP_MODIFY_PASSWD, ber);

            try
            {
                // 認証したいユーザーでバインドする
                ldapConnection.Bind();

                // パスワード変更要求を送信
                var modifyPasswdResponse = (ExtendedResponse)ldapConnection.SendRequest(modifyPasswdRequest);

                // 応答が「成功」か確認
                if (modifyPasswdResponse.ResultCode != ResultCode.Success)
                {
                    throw new Exception("Could not change password. ("
                                        + Enum.GetName(typeof(ResultCode), modifyPasswdResponse.ResultCode) + ")");
                }
            }
            finally
            {
                if (ldapConnection != null)
                {
                    try
                    {
                        ldapConnection.Dispose();
                    }
                    catch (Exception e)
                    {
                        System.Diagnostics.Debug.WriteLine(e);
                    }
                }
            }
        }
Esempio n. 23
0
 public byte[] Encode()
 {
     return(BerConverter.Encode("{st{v}}", this.Type, 0x31, this.Vals));
 }
Esempio n. 24
0
 public override byte[] GetValue()
 {
     object[] objArray = new object[1];
     objArray[0] = this._inputDN;
     return(BerConverter.Encode("{s}", objArray));
 }
Esempio n. 25
0
 public byte[] Encode()
 {
     return(BerConverter.Encode("t{eoo}", 0x65, this.ResultCode, this.MatchedDN, this.ErrorMessage));;
 }
Esempio n. 26
0
 public void Encode_NullFormat_ThrowsArgumentNullException()
 {
     AssertExtensions.Throws <ArgumentNullException>("format", () => BerConverter.Encode(null, new object[0]));
 }
        internal static void TransformControls(DirectoryControl[] controls)
        {
            for (int i = 0; i < controls.Length; i++)
            {
                Debug.Assert(controls[i] != null);
                byte[] value = controls[i].GetValue();
                if (controls[i].Type == "1.2.840.113556.1.4.319")
                {
                    // The control is a PageControl.
                    object[] result = BerConverter.Decode("{iO}", value);
                    Debug.Assert((result != null) && (result.Length == 2));

                    int size = (int)result[0];
                    // user expects cookie with length 0 as paged search is done.
                    byte[] cookie = (byte[])result[1] ?? Array.Empty <byte>();

                    PageResultResponseControl pageControl = new PageResultResponseControl(size, cookie, controls[i].IsCritical, controls[i].GetValue());
                    controls[i] = pageControl;
                }
                else if (controls[i].Type == "1.2.840.113556.1.4.1504")
                {
                    // The control is an AsqControl.
                    object[] o = BerConverter.Decode("{e}", value);
                    Debug.Assert((o != null) && (o.Length == 1));

                    int result             = (int)o[0];
                    AsqResponseControl asq = new AsqResponseControl(result, controls[i].IsCritical, controls[i].GetValue());
                    controls[i] = asq;
                }
                else if (controls[i].Type == "1.2.840.113556.1.4.841")
                {
                    // The control is a DirSyncControl.
                    object[] o = BerConverter.Decode("{iiO}", value);
                    Debug.Assert(o != null && o.Length == 3);

                    int    moreData      = (int)o[0];
                    int    count         = (int)o[1];
                    byte[] dirsyncCookie = (byte[])o[2];

                    DirSyncResponseControl dirsync = new DirSyncResponseControl(dirsyncCookie, (moreData == 0 ? false : true), count, controls[i].IsCritical, controls[i].GetValue());
                    controls[i] = dirsync;
                }
                else if (controls[i].Type == "1.2.840.113556.1.4.474")
                {
                    // The control is a SortControl.
                    int      result    = 0;
                    string   attribute = null;
                    object[] o         = BerConverter.TryDecode("{ea}", value, out bool decodeSucceeded);

                    // decode might fail as AD for example never returns attribute name, we don't want to unnecessarily throw and catch exception
                    if (decodeSucceeded)
                    {
                        Debug.Assert(o != null && o.Length == 2);
                        result    = (int)o[0];
                        attribute = (string)o[1];
                    }
                    else
                    {
                        // decoding might fail as attribute is optional
                        o = BerConverter.Decode("{e}", value);
                        Debug.Assert(o != null && o.Length == 1);

                        result = (int)o[0];
                    }

                    SortResponseControl sort = new SortResponseControl((ResultCode)result, attribute, controls[i].IsCritical, controls[i].GetValue());
                    controls[i] = sort;
                }
                else if (controls[i].Type == "2.16.840.1.113730.3.4.10")
                {
                    // The control is a VlvResponseControl.
                    int      position;
                    int      count;
                    int      result;
                    byte[]   context = null;
                    object[] o       = BerConverter.TryDecode("{iieO}", value, out bool decodeSucceeded);

                    if (decodeSucceeded)
                    {
                        Debug.Assert(o != null && o.Length == 4);
                        position = (int)o[0];
                        count    = (int)o[1];
                        result   = (int)o[2];
                        context  = (byte[])o[3];
                    }
                    else
                    {
                        o = BerConverter.Decode("{iie}", value);
                        Debug.Assert(o != null && o.Length == 3);
                        position = (int)o[0];
                        count    = (int)o[1];
                        result   = (int)o[2];
                    }

                    VlvResponseControl vlv = new VlvResponseControl(position, count, context, (ResultCode)result, controls[i].IsCritical, controls[i].GetValue());
                    controls[i] = vlv;
                }
            }
        }
 public byte[] Encode(LDAPSearchResEntry search)
 {
     return(BerConverter.Encode("{it{stX}}", this.MessageID, 0x64, search.ObjectDN, 0x30, search.Attributes));
 }
 public byte[] Encode()
 {
     return(BerConverter.Encode("{iX}", this.MessageID, this.ProtocolOp));
 }
Esempio n. 30
0
 public void Encode_Invalid_ThrowsArgumentException(string format, object[] values)
 {
     AssertExtensions.Throws <ArgumentException>(null, () => BerConverter.Encode(format, values));
 }