# Report

New research: Dependency attacks 2026 ·

Complexity Score

Low

Open Issues

6

Dependent Projects

2,557

Weekly Downloads global

264,286,951

## Keywords

[buffer](/content/navigator/search?q=keywords%3A+buffer&registry=all/index.html) [buffer allocate](/content/navigator/search?q=keywords%3A+buffer+allocate&registry=all/index.html) [node security](/content/navigator/search?q=keywords%3A+node+security&registry=all/index.html) [safe](/content/navigator/search?q=keywords%3A+safe&registry=all/index.html) [safe-buffer](/content/navigator/search?q=keywords%3A+safe-buffer&registry=all/index.html) [security](/content/navigator/search?q=keywords%3A+security&registry=all/index.html) [uninitialized](/content/navigator/search?q=keywords%3A+uninitialized&registry=all/index.html) [javascript](/content/navigator/search?q=keywords%3A+javascript&registry=all/index.html) [nodejs](/content/navigator/search?q=keywords%3A+nodejs&registry=all/index.html)

## License

- **MIT**

## Readme

# safe-buffer

#### Safer Node.js Buffer API

**Use the new Node.js Buffer APIs (`Buffer.from`, `Buffer.alloc`,**  
**`Buffer.allocUnsafe`, `Buffer.allocUnsafeSlow`) in all versions of Node.js.**

**Uses the built-in implementation when available.**

## install

```
npm install safe-buffer
```

## usage

The goal of this package is to provide a safe replacement for the node.js `Buffer`.

It’s a drop-in replacement for `Buffer`. You can use it by adding one `require` line to
the top of your node.js modules:

```
var Buffer = require('safe-buffer').Buffer

// Existing buffer code will continue to work without issues:

new Buffer('hey', 'utf8')
new Buffer([1, 2, 3], 'utf8')
new Buffer(obj)
new Buffer(16) // create an uninitialized buffer (potentially unsafe)

// But you can use these new explicit APIs to make clear what you want:

Buffer.from('hey', 'utf8') // convert from many types to a Buffer
Buffer.alloc(16) // create a zero-filled buffer (safe)
Buffer.allocUnsafe(16) // create an uninitialized buffer (potentially unsafe)
```

## api

### Class Method: Buffer.from(array)

- `array` {Array}

Allocates a new `Buffer` using an `array` of octets.

```
const buf = Buffer.from([0x62,0x75,0x66,0x66,0x65,0x72]);
  // creates a new Buffer containing ASCII bytes
  // ['b','u','f','f','e','r']
```

A `TypeError` will be thrown if `array` is not an `Array`.

### Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]])

- `arrayBuffer` {ArrayBuffer} The `.buffer` property of a `TypedArray` or
a `new ArrayBuffer()`
- `byteOffset` {Number} Default: `0`
- `length` {Number} Default: `arrayBuffer.length - byteOffset`

When passed a reference to the `.buffer` property of a `TypedArray` instance,
the newly created `Buffer` will share the same allocated memory as the
TypedArray.

```
const arr = new Uint16Array(2);
arr[0] = 5000;
arr[1] = 4000;

const buf = Buffer.from(arr.buffer); // shares the memory with arr;

console.log(buf);
  // Prints: <Buffer 88 13 a0 0f>

// changing the TypedArray changes the Buffer also
arr[1] = 6000;

console.log(buf);
  // Prints: <Buffer 88 13 70 17>
```

The optional `byteOffset` and `length` arguments specify a memory range within
the `arrayBuffer` that will be shared by the `Buffer`.

```
const ab = new ArrayBuffer(10);
const buf = Buffer.from(ab, 0, 2);
console.log(buf.length);
  // Prints: 2
```

A `TypeError` will be thrown if `arrayBuffer` is not an `ArrayBuffer`.

### Class Method: Buffer.from(buffer)

- `buffer` {Buffer}

Copies the passed `buffer` data onto a new `Buffer` instance.

```
const buf1 = Buffer.from('buffer');
const buf2 = Buffer.from(buf1);

buf1[0] = 0x61;
console.log(buf1.toString());
  // 'auffer'
console.log(buf2.toString());
  // 'buffer' (copy is not changed)
```

A `TypeError` will be thrown if `buffer` is not a `Buffer`.

### Class Method: Buffer.from(str[, encoding])

- `str` {String} String to encode.
- `encoding` {String} Encoding to use, Default: `'utf8'`

Creates a new `Buffer` containing the given JavaScript string `str`. If
provided, the `encoding` parameter identifies the character encoding.
If not provided, `encoding` defaults to `'utf8'`.

```
const buf1 = Buffer.from('this is a tést');
console.log(buf1.toString());
  // prints: this is a tést
console.log(buf1.toString('ascii'));
  // prints: this is a tC)st

const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex');
console.log(buf2.toString());
  // prints: this is a tést
```

A `TypeError` will be thrown if `str` is not a string.

### Class Method: Buffer.alloc(size[, fill[, encoding]])

- `size` {Number}
- `fill` {Value} Default: `undefined`
- `encoding` {String} Default: `utf8`

Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the
`Buffer` will be _zero-filled_.

```
const buf = Buffer.alloc(5);
console.log(buf);
  // <Buffer 00 00 00 00 00>
```

The `size` must be less than or equal to the value of
`require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is
`(2^31)-1`). Otherwise, a 
[`RangeError`](https://nodejs.org/api/errors.html#errors_class_rangesearch_error) will be thrown. A zero-length Buffer will
be created if a `size` less than or equal to 0 is specified.

If `fill` is specified, the allocated `Buffer` will be initialized by calling
`buf.fill(fill)`. See [`buf.fill()`](https://nodejs.org/api/buffer.html#buffer_buf_fill_value_encoding_start_end) for more information.

```
const buf = Buffer.alloc(5, 'a');
console.log(buf);
  // <Buffer 61 61 61 61 61>
```

If both `fill` and `encoding` are specified, the allocated `Buffer` will be
initialized by calling `buf.fill(fill, encoding)`. For example:

```
const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64');
console.log(buf);
  // <Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64>
```

Calling `Buffer.alloc(size)` can be significantly slower than the alternative
`Buffer.allocUnsafe(size)` but ensures that the newly created `Buffer` instance
contents will _never contain sensitive data_.

A `TypeError` will be thrown if `size` is not a number.

### Class Method: Buffer.allocUnsafe(size)

- `size` {Number}

Allocates a new _non-zero-filled_`Buffer` of `size` bytes. The `size` must
be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit
architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a 
[`RangeError`](https://nodejs.org/api/errors.html#errors_class_rangesearch_error) will be thrown. A zero-length Buffer will
be created if a `size` less than or equal to 0 is specified.

The underlying memory for `Buffer` instances created in this way is _not_
_initialized_. The contents of the newly created `Buffer` are unknown and
_may contain sensitive data_. Use [`buf.fill(0)`](https://nodejs.org/api/buffer.html#buffer_buf_fill_value_encoding_start_end) to initialize such
`Buffer` instances to zeroes.

```
const buf = Buffer.allocUnsafe(5);
console.log(buf);
  // <Buffer 78 e0 82 02 01>
  // (octets will be different, every time)
buf.fill(0);
console.log(buf);
  // <Buffer 00 00 00 00 00>
```

A `TypeError` will be thrown if `size` is not a number.

### Class Method: Buffer.allocUnsafeSlow(size)

- `size` {Number}

Allocates a new _non-zero-filled_ and non-pooled `Buffer` of `size` bytes. The
`size` must be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is
`(2^31)-1`). Otherwise, a [RangeError](https://nodejs.org/api/errors.html#errors_class_rangesearch_error) will be thrown. A zero-length Buffer will
be created if a `size` less than or equal to 0 is specified.

## Why is `Buffer` unsafe?

Today, the node.js `Buffer` constructor is overloaded to handle many different argument
types like `String`, `Array`, `Object`, `TypedArrayView` (`Uint8Array`, etc.),
`ArrayBuffer`, and also `Number`.

The API is optimized for convenience: you can throw any type at it, and it will try to do
what you want.

Because the Buffer constructor is so powerful, you often see code like this:

```javascript
// Convert UTF-8 strings to hex
function toHex (str) {
  return new Buffer(str).toString('hex')
}
```

### Remote Memory Disclosure

If an attacker can make your program call the `Buffer` constructor with a `Number`
argument, then they can make it allocate uninitialized memory from the node.js process.
This could potentially disclose TLS private keys, user data, or database passwords.

When the `Buffer` constructor is passed a `Number` argument, it returns an
**UNINITIALIZED** block of memory of the specified `size`. When you create a `Buffer` like
this, you **MUST** overwrite the contents before returning it to the user.

`new Buffer(size)`

- `size` Number

The underlying memory for `Buffer` instances created in this way is not initialized.
**The contents of a newly created `Buffer` are unknown and could contain sensitive**
**data.** Use `buf.fill(0)` to initialize a Buffer to zeroes.

(Emphasis our own.)

Whenever the programmer intended to create an uninitialized `Buffer` you often see code
like this:

```javascript
var buf = new Buffer(16)

// Immediately overwrite the uninitialized buffer with data from another buffer
for (var i = 0; i < buf.length; i++) {
  buf[i] = otherBuf[i]
}
```

### Which real-world packages were vulnerable?

#### `bittorrent-dht`

Mathias Buus and I (Feross Aboukhadijeh) found this issue in one of our own packages,
`bittorrent-dht`. The bug would allow anyone on the internet to send a series of messages
to a user of `bittorrent-dht` and get them to reveal 20 bytes at a time of uninitialized
memory from the node.js process.

#### `ws`

That got us wondering if there were other vulnerable packages. Sure enough, within a short
period of time, we found the same issue in `ws`, the most popular WebSocket implementation in node.js.

### What’s the solution?

It’s important that node.js offers a fast way to get memory otherwise performance-critical
applications would needlessly get a lot slower.

But we need a better way to _signal our intent_ as programmers. **When we want**
**uninitialized memory, we should request it explicitly.**

### Conclusion

We think there’s a serious design issue with the `Buffer` API as it exists today. It
promotes insecure software by putting high-risk functionality into a convenient API
with friendly “developer ergonomics”.

Fortunately, there’s an easy fix that can be applied today. Use `safe-buffer` in place of
`buffer`.

```
var Buffer = require('safe-buffer').Buffer
```

Eventually, we hope that node.js core can switch to this new, safer behavior. We believe
the impact on the ecosystem would be minimal since it’s not a breaking change.
Well-maintained, popular packages would be updated to use `Buffer.alloc` quickly,
while older, insecure packages would magically become safe from this attack vector.
