Avoid using the `Buffer()` constructorJS-D026
NodeJS has deprecated the Buffer
constructor due to the multitude of security vulnerabilities around it.
For instance, the constructor is vulnerable to Remote Memory Disclosure and Denial Of Service.
We recommend using Buffer.from()
, Buffer.alloc()
, or Buffer.allocUnsafe()
as alternatives, keeping the following points in mind:
Buffer.alloc(size[, fill[, encoding]])
returns a new initialized Buffer of the specified size. This method is slower thanBuffer.allocUnsafe(size)
, but guarantees that newly created Buffer instances never contain potentially sensitive data. If the size is not a number, then it will throw aTypeError
.Buffer.allocUnsafe(size)
andBuffer.allocUnsafeSlow(size)
each return a new uninitialized Buffer of the specified size. Because the Buffer is uninitialized, the allocated segment of memory might contain potentially sensitive data.
The Buffer
constructor behaves differently based on the type of its argument.
Passing an argument from user input to Buffer()
without validating its type can lead to security vulnerabilities mentioned above.
Errors in handling buffers allocated with Buffer.allocUnsafe()
could result in various issues, ranging from unexpected behavior of your code to sensitive data (user input, passwords, certs) leaking to the remote attacker.
When calling Buffer.allocUnsafe()
, the segment of allocated memory is uninitialized (it is not zeroed-out). While this design allocates memory quite fast, the allocated memory segment might contain old and potentially sensitive data. Using a Buffer created by Buffer.allocUnsafe()
without completely overwriting the memory can allow this old data to leak.
Bad Practice
Buffer([1, 2, 3])
Buffer(1240)
new Buffer([1, 2, 3])
Recommended
Buffer.alloc(5)
Buffer.from([1, 2, 3])
// Or, once the arg has been validated:
Buffer.alloc(req.body.amount)
Buffer.from(req.body.values)