C# - Socket to log on to Firewall

2019-03-02 21:40发布

问题:

I wrote an app to automatically connect to our different Firewalls. All of them work with the same frontend. We telnet to the IP and they give the message LOGIN or LOGOUT and ask for a username or password.

I used this code:

    public static void ConnectToFirewall(string strUsername, string strPassword, string strFirewallIp)
    {
        IPAddress[] ipaIpAddressCollection = Dns.GetHostAddresses(strFirewallIp);
        IPEndPoint ipeIpEndPoint = new IPEndPoint(ipaIpAddressCollection[0], intPort);
        Socket sckSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        sckSocket.Connect(ipeIpEndPoint);
        string strData = strUsername + "\r\n"+ strPassword + "\r\n";
        byte[] bytData = new byte[1024];
        bytData = Encoding.ASCII.GetBytes(strData);
        sckSocket.Send(bytData);
        byte[] bytDataReceived = new byte[1024];
        int intData = sckSocket.Receive(bytDataReceived);
        sckSocket.Close();
    }

If I am not logged in, when I telnet to it, I receive the message: LOGIN, username: / Password:. If I am logged on, I receive LOGOUT, username: / Password.

This works perfectly well with the above method for half of my firewalls, it does not seem to work (I keep getting login as if I had not tried to pass credentials). I also tried it with

    TcpClient tcpConnection = new TcpClient(myip,myport);

but this gives the same result. It works for certain firewall ip's. fails for others. They are all in the same domain.

Does anyone have idea how I could get past this or what steps I could undertake to troubleshoot this or what may be the cause of some server not accepting this method, allthough it does accept if I telnet to it?

Any help or suggestions are appreciated.

Many thanks in advance.

回答1:

When you call sckSocket.Send(bytData), how does the socket know to send only the portion of the bytData that has been initialized with the username and password? I have a feeling that Send() will send the entire 1024 bytes along, most of which will be 0x00 bytes. I would not expect a router to handle this gracefully.

I've seen systems that accepted the password only after the prompt for the password has been generated and sent. Try sending the username and password with two separate requests. If your environment makes it feasible to set the TCP_NODELAY socket option to disable Nagle's algorithm, it might help to get the username string sent along more quickly. (I wouldn't bother with this unless you also split apart sending the username from the password.)