java - 如何防止Java中BufferedReader readLine()方法的Dos攻击?

标签 java bufferedreader denial-of-service

我遇到这样的情况:我使用 BufferedReader readLine() 从套接字读取数据,但 readline() 读取数据直到找到新行字符/回车符在数据中。
如果我的数据不包含换行符,那么它将继续读取数据,直到找到新行,并且入侵者可以注入(inject) DOS 攻击。 甚至套接字也会超时。

我知道一种解决方案可能是我们需要限制行大小并只读取一些数据,然后将数据附加到缓冲区。

这是最佳解决方案还是我可以通过其他方式做到这一点?

我可以重写 BufferedReader 并重写 readLine() 方法。这是可行的解决方案吗?

最佳答案

使用Socket.setSoTimeout(int)

转自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.

另请注意,从这一行开始

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

在执行read操作之前,您必须调用Socket.setSoTimeout(int)

关于java - 如何防止Java中BufferedReader readLine()方法的Dos攻击?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6394529/

相关文章:

java - 计算除数并将字符串输出到 JLabel

java - 两个 Java 运算符之间的区别 : ! = vs !equals

java - URL 连接在小程序中不起作用

java - 是否有一种简单有效的方法来延迟 Java Servlet 的响应

java - Hibernate Elasticsearch 与 wildfly 14 兼容

java - RCP E4 @UIEventTopic 未调用

Java 从 Buffered Reader 创建字符串并比较字符串

java - 如何使用 bufferedreader 将值分配给直接从输入获取的字符串数组?

java - 如何限制每秒的网络请求以避免垃圾邮件和拒绝服务