expressjs / compression

Node.js compression middleware
MIT License
2.77k stars 241 forks source link

Compression Bomb Protection #70

Closed mallocator closed 8 years ago

mallocator commented 8 years ago

Hi I'm trying to figure out a way to protect against compression bombs in express ([this](https://en.wikipedia.org/wiki/Zip_bomb] might help if that term is new).

I haven't found any resources that might help in how to deal with that in this library. Usually I would pass the stream through a counter that just throws an exception when a threshold is passed.

I'm new to express so the solution might be so simple that I just don't see it, but if not then this would be a great feature to add.

mallocator commented 8 years ago

With a little fiddling I found my own solution in case someone else is looking for it. This might still be considered a nice feature to have though.

// Prevent compression bomb
app.use((req, res, next) => {
    var length = 0;
    req.on('data', (chunk) => {
        length += chunk.length;
        if (length > 1048576) {
            req.removeAllListeners('data');
            req.removeAllListeners('end');
            res.header('Connection', 'close');
            res.status(413).send('Message too long, will not process');
        }
    });
    req.on('end', () => {
        next();
    })
});
dougwilson commented 8 years ago

I'm not sure what you are looking for here. Your example code does not even use this module, and the module had nothing to do with incoming requests.

If you are looking to gunzip request bodies, you should be using the "body-parser" module, which has gunzip built-in, including compression bomb protection.