Skip to content

dangerous-function-buffer-non-literal-alloc

Ensure buffer is initialized with a literal value

The Buffer constructor could be used to create a buffer in many different ways:

  • new Buffer(42) creates a Buffer of 42 bytes. Before Node.js 8, this buffer contained arbitrary memory for performance reasons, which could include anything ranging from program source code to passwords and encryption keys.
  • new Buffer('abc') creates a Buffer that contains the UTF-8-encoded version of the string 'abc'. A second argument could specify another encoding: for example, new Buffer(string, 'base64') could be used to convert a Base64 string into the original sequence of bytes that it represents.
  • There are several other combinations of arguments.

This meant that in code like var buffer = new Buffer(foo);, it is not possible to tell what exactly the contents of the generated buffer are without knowing the type of foo.

Examples

Insecure Example

Sometimes, the value of foo comes from an external source. For example, this function could be exposed as a service on a web server, converting a UTF-8 string into its Base64 form:

function stringToBase64(req, res) {
    // The request body should have the format of `{ string: 'foobar' }`.
    const rawBytes = new Buffer(req.body.string);
    const encoded = rawBytes.toString("base64");
    res.end({ encoded });
}

Because of the ambiguous overloads of new Buffer(), an attacker could intentionally send a number as part of the request. Using this, they can either:

  • Read uninitialized memory. This will leak passwords, encryption keys and other kinds of sensitive information. (Information leak)
  • Force the program to allocate a large amount of memory. For example, when specifying 500000000 as the input value, each request will allocate 500MB of memory. This can be used to either exhaust the memory available of a program completely and make it crash, or slow it down significantly. (Denial of Service)

Both of these scenarios are considered serious security issues in a real-world web server context.

Secure Example

Replace occurrences of new Buffer() with Buffer.from() or Buffer.alloc() API's.

  • Replace new Buffer(number), replace it with Buffer.alloc(number).
  • Replace new Buffer(string) or new Buffer(string, encoding) with Buffer.from(string) or Buffer.from(string, encoding).