buffer: throw if both length and enc are passed by mafintosh · Pull Request #4514 · nodejs/node (original) (raw)

The problem is that Buffer(arg, encoding) implies that arg is gonna be a string but if you pass a number as arg it'll allocate a non-zeroed out buffer instead. This means that if you have code that forgets to check if arg is a string and you get the arg from a third-party you might end up exposing internal memory.

Consider the following example

// a service that takes a json payload {hexString: str} and converts it to base64 var server = http.createServer(function (req, res) { var buf = '' req.setEncoding('utf-8') req.on('data', function (data) { buf += data }) req.on('end', function () { var body = JSON.parse(buf) res.end(new Buffer(body.hexString, 'hex').toString('base64')) }) })

server.listen(8080)

If you post {hexString: 'aa'} to it, it will return qq==. However if you post {hexString: 20} it will return 20 bytes of internal memory as base64 since that will invoke the new Buffer(number) constructor.

Like I mentioned above this is fixable by explicitly checking if hexString is a string but since we're passing hex as the encoding this is implied and therefore it would be a help if node would throw.