Buffer()
and Buffer#allocUnsafe()
JS-D025NodeJS has deprecated the Buffer
constructor due to the multitude of security vulnerabilities it is affected by, such as Remote Memory Disclosure and Denial Of Service.
We recommend using Buffer.from()
, Buffer.alloc()
, and 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 than Buffer.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 a TypeError
.Buffer.allocUnsafe(size)
and Buffer.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.In Node.js, the behavior of the Buffer
constructor is different depending on the type of its argument.
Passing an argument from user input to Buffer()
without validating its type can lead to security vulnerabilities such as Remote Memory Disclosure and Denial of Service.
Errors in handling buffers allocated with Buffer.allocUnsafe()
could result in various issues, ranging from undefined 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.
Buffer([1, 2, 3])
new Buffer([1, 2, 3])
Buffer.allocUnsafe(5)
Buffer.alloc(5)
new Buffer.Foo()
Buffer.from([1, 2, 3])
foo(Buffer)
Buffer.alloc(res.body.amount)
Buffer.from(res.body.values)