了解使用C#代码模拟LDAP响应

时间:2019-05-18 18:40:32

标签: c# ldap tcplistener

我需要模拟一个LDAP目录,以将预定义的响应发送到需要LDAP才能工作的一个应用程序。我正在使用LDAP浏览器和LDAP Admin侦听389端口进行一些测试。要编写响应,我将使用NetworkStream和StreamWriter。通过LDAP RFC,我得到了下面显示的搜索响应模型。我不知道如何建立这个信封,我必须建立一个字节序列吗?

SearchResultEntry ::= [APPLICATION 4] SEQUENCE {
                objectName      LDAPDN,
                 attributes      PartialAttributeList }

        PartialAttributeList ::= SEQUENCE OF SEQUENCE {
                type    AttributeDescription,
                vals    SET OF AttributeValue }
        -- implementors should note that the PartialAttributeList may
        -- have zero elements (if none of the attributes of that entry
        -- were requested, or could be returned), and that the vals set
        -- may also have zero elements (if types only was requested, or
        -- all values were excluded from the result.)

        SearchResultReference ::= [APPLICATION 19] SEQUENCE OF LDAPURL
        -- at least one LDAPURL element must be present

        SearchResultDone ::= [APPLICATION 5] LDAPResult

我收到了客户端正在发送的请求,我可以识别请求的字符串部分,但是我没有找到正确的答案。通过在请求中找到的字符串,我可以弄清楚客户端正在发送哪种消息。

public static void Connect()
{
        try
        {
            int port = 389;
            IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
            TcpListener listener = new TcpListener(ipAddress, port);
            listener.Server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);

            listener.Start();

            while (true)
            {
                LDAPLayer handler = new LDAPLayer(listener.AcceptTcpClient());
                Thread thread = new Thread(new ThreadStart(handler.LDAPListener));
                thread.Start();
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
        finally
        {
            client.Close();
        }
}

public void LDAPListener()
{
        try
        {
            while (true)
            {
                string line = reader.ReadLine();
                string date = DateTime.Now.ToString("yyyyMMdd_HHmmss");

                while (line != null)
                {
                    Console.WriteLine(line);

                    if (line.Contains("objectClass"))
                    {
                        writer.Write(0);
                    }

                    line = reader.ReadLine();
                }
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("Error: " + e.Message);
        }
}

1 个答案:

答案 0 :(得分:0)

LDAP不是文本协议。必须根据X.690规范使用BER规则对每个LDAP消息进行编码。