如何防止从服务器端上传大文件

How to prevent large file upload from server side

我希望防止我的应用程序受到 resource consumption 类型的 DoS 攻击。这意味着攻击者可以通过将大文件上传到服务器来消耗服务器资源,例如内存和磁盘容量。

我想知道是否可以检查传入文件的元数据(例如大小)并在达到限制后取消上传。否则攻击者可能会向服务器上传一个 20 GB 的文件,如果服务器等待上传完成进行验证,那么即使在上传完成之前,我的服务器也可能已经被如此大的文件淹没了。

我想知道如何用 Java 做到这一点。我正在使用 Apache/coyote 1.1.


更新:

我在PHP中找到了如下解决方案。

post_max_size integer
    Sets max size of post data allowed. This setting also affects file upload.
    To upload large files, this value must be larger than upload_max_filesize.
    If memory limit is enabled by your configure script, memory_limit also
    affects file uploading. Generally speaking, memory_limit should be larger
    than post_max_size. When an integer is used, the value is measured in bytes.
    Shorthand notation, as described in this FAQ, may also be used. If the size
    of post data is greater than post_max_size, the $_POST and $_FILES
    superglobals are empty [...]

max_file_uploads integer
    The maximum number of files allowed to be uploaded simultaneously. Starting
    with PHP 5.3.4, upload fields left blank on submission do not count towards
    this limit.

在Java中是否有任何替代品?

https://www.netroby.com/view.php?id=3585,看看你限制文件上传大小是否可行。

我们可以通过以下方式测量上传文件的大小,

  1. 客户端(有HTML5、JSP、JS等,)

  2. 上传时动态测量(容器级别)

  3. 上传结束后测量(容器级别)

因为可以 tweak/hack #1 实现。依靠#2很好。 MultipartConfig 能够在达到限制时中断文件上传(属于 #2)。

注:

  1. 您可以将多部分配置用作注释(或)用作 servlet web.xml 文件中的配置元素