How to limit the maximum size read via ObjectInput

2019-04-16 05:17发布

Is there a way to limit the maximum buffer size to be read from an ObjectInputStream in java?

I want to stop the deserialization if it becomes clear that the Object in question is crafted maliciously huge.

Of course, there is ObjectInputStream.read(byte[] buf, int off, int len), but I do not want to suffer the performance penalty of allocating, say byte[1000000].

Am I missing something here?

3条回答
Melony?
2楼-- · 2019-04-16 05:36

You write a FilterInputStream which will throw an exception if it discovers it has read more than a certain amount of data from its underlying stream.

查看更多
别忘想泡老子
3楼-- · 2019-04-16 05:44

I can see two ways:
1) do your reads in a loop, grabbing chunks whose allocation size you're comfortable with, and exit and stop when you hit your limit; or 2) Allocate your max-size buffer once and re-use it for subsequent reads.

查看更多
我欲成王,谁敢阻挡
4楼-- · 2019-04-16 05:46

Actually, there's a really easy way.

You can use NIO's ByteBuffer, and use the allocateDirect method. This method will allow you to allocate a memory-mapped file, so it doesn't have a huge overhead, and you can limit its size.

Then, instead of getting the stream from the socket, get the Channel.

Code:

    Socket s;

    ByteBuffer buffer = ByteBuffer.allocateDirect(10 * 1024 * 1024);
    s.getChannel().read(buffer);

Now, don't try to call the "array()" method on the byte buffer; it doesn't work on a directly-allocated buffer. However, you can wrap the buffer as an input stream and send it to the ObjectInputStream for further processing.

查看更多
登录 后发表回答