How to prevent Dos attack for readLine () method of BufferedReader in Java?

I have a situation where I use BufferedReader readLine()to read data from a socket, but it readLine()reads data until it finds a new character / line feed character in Data.
And if my data does not contain a new line character, it will continue to read the data until it finds a new line, and the attacker can introduce a DOS attack. And even a socket can expire.

I know that one solution could be to limit the size of the row and read only some data and add data to the buffer.

Is this the best solution, or can I do it another way?

I can override the BufferedReader and override the readLine () method. Is there a possible solution?

+3
source share
1 answer

Use Socket.setSoTimeout(int)

Qutoing of javadoc

Enable / disable SO_TIMEOUT with the specified timeout in milliseconds. If this parameter is set to a non-zero timeout, the call to read () in the InputStream associated with this Socket will be blocked only for this amount of time.

If the timeout expires, a java.net.SocketTimeoutException is thrown, although Socket is still valid. The option must be activated before the lock operation is entered. The timeout must be> 0. A zero timeout is interpreted as an infinite timeout.

Also note that from this line

The option must be activated before the lock operation is entered.

You must call Socket.setSoTimeout(int)before performing the operation read.

0

All Articles