Java – How to Prevent Dos attack for BufferedReader readLine() method in Java

bufferedreaderdenial-of-servicejava

I have situation where I am using BufferedReader readLine() to read data from a socket, but readline() reads data until it finds new line character/ return carriage in the Data.
And if my data does not contain new line character then it will keep on reading the data until it finds a new line and an intruder can inject DOS attack.
And even socket can timeout.

I know one solution might be we need to restrict line size and read only some data, and append data to the buffer.

Is it optimal solution or i can do it in some other way?.

I can override BufferedReader and override readLine() method. Is it feasible solution?.

Best Answer

Use Socket.setSoTimeout(int)

Qutoing from javadoc

Enable/disable SO_TIMEOUT with the specified timeout, in milliseconds. With this option set to a non-zero timeout, a read() call on the InputStream associated with this Socket will block for only this amount of time.

If the timeout expires, a java.net.SocketTimeoutException is raised, though the Socket is still valid. The option must be enabled prior to entering the blocking operation to have effect. The timeout must be > 0. A timeout of zero is interpreted as an infinite timeout.

Also note that from this line

The option must be enabled prior to entering the blocking operation to have effect.

you must call Socket.setSoTimeout(int) before doing the read operation.