{
  "name": "safe-buffer",
  "description": "Safer Node.js Buffer API",
  "version": "5.0.1",
  "author": {
    "name": "Feross Aboukhadijeh",
    "email": "feross@feross.org",
    "url": "http://feross.org"
  },
  "bugs": {
    "url": "https://github.com/feross/safe-buffer/issues"
  },
  "browser": "./browser.js",
  "devDependencies": {
    "standard": "^7.0.0",
    "tape": "^4.0.0",
    "zuul": "^3.0.0"
  },
  "homepage": "https://github.com/feross/safe-buffer",
  "keywords": [
    "buffer",
    "buffer allocate",
    "node security",
    "safe",
    "safe-buffer",
    "security",
    "uninitialized"
  ],
  "license": "MIT",
  "main": "index.js",
  "repository": {
    "type": "git",
    "url": "git://github.com/feross/safe-buffer.git"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "readme": "# safe-buffer [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][npm-url]\n\n#### Safer Node.js Buffer API\n\n**Use the new Node.js v6 Buffer APIs (`Buffer.from`, `Buffer.alloc`,\n`Buffer.allocUnsafe`, `Buffer.allocUnsafeSlow`) in Node.js v0.10, v0.12, v4.x, and v5.x.**\n\n**Uses the built-in implementations when available.**\n\n[travis-image]: https://img.shields.io/travis/feross/safe-buffer.svg\n[travis-url]: https://travis-ci.org/feross/safe-buffer\n[npm-image]: https://img.shields.io/npm/v/safe-buffer.svg\n[npm-url]: https://npmjs.org/package/safe-buffer\n[downloads-image]: https://img.shields.io/npm/dm/safe-buffer.svg\n\n## install\n\n```\nnpm install safe-buffer\n```\n\n## usage\n\nThe goal of this package is to provide a safe replacement for the node.js `Buffer`.\n\nIt's a drop-in replacement for `Buffer`. You can use it by adding one `require` line to\nthe top of your node.js modules:\n\n```js\nvar Buffer = require('safe-buffer').Buffer\n\n// Existing buffer code will continue to work without issues:\n\nnew Buffer('hey', 'utf8')\nnew Buffer([1, 2, 3], 'utf8')\nnew Buffer(obj)\nnew Buffer(16) // create an uninitialized buffer (potentially unsafe)\n\n// But you can use these new explicit APIs to make clear what you want:\n\nBuffer.from('hey', 'utf8') // convert from many types to a Buffer\nBuffer.alloc(16) // create a zero-filled buffer (safe)\nBuffer.allocUnsafe(16) // create an uninitialized buffer (potentially unsafe)\n```\n\n## api\n\n### Class Method: Buffer.from(array)\n<!-- YAML\nadded: v3.0.0\n-->\n\n* `array` {Array}\n\nAllocates a new `Buffer` using an `array` of octets.\n\n```js\nconst buf = Buffer.from([0x62,0x75,0x66,0x66,0x65,0x72]);\n  // creates a new Buffer containing ASCII bytes\n  // ['b','u','f','f','e','r']\n```\n\nA `TypeError` will be thrown if `array` is not an `Array`.\n\n### Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]])\n<!-- YAML\nadded: v5.10.0\n-->\n\n* `arrayBuffer` {ArrayBuffer} The `.buffer` property of a `TypedArray` or\n  a `new ArrayBuffer()`\n* `byteOffset` {Number} Default: `0`\n* `length` {Number} Default: `arrayBuffer.length - byteOffset`\n\nWhen passed a reference to the `.buffer` property of a `TypedArray` instance,\nthe newly created `Buffer` will share the same allocated memory as the\nTypedArray.\n\n```js\nconst arr = new Uint16Array(2);\narr[0] = 5000;\narr[1] = 4000;\n\nconst buf = Buffer.from(arr.buffer); // shares the memory with arr;\n\nconsole.log(buf);\n  // Prints: <Buffer 88 13 a0 0f>\n\n// changing the TypedArray changes the Buffer also\narr[1] = 6000;\n\nconsole.log(buf);\n  // Prints: <Buffer 88 13 70 17>\n```\n\nThe optional `byteOffset` and `length` arguments specify a memory range within\nthe `arrayBuffer` that will be shared by the `Buffer`.\n\n```js\nconst ab = new ArrayBuffer(10);\nconst buf = Buffer.from(ab, 0, 2);\nconsole.log(buf.length);\n  // Prints: 2\n```\n\nA `TypeError` will be thrown if `arrayBuffer` is not an `ArrayBuffer`.\n\n### Class Method: Buffer.from(buffer)\n<!-- YAML\nadded: v3.0.0\n-->\n\n* `buffer` {Buffer}\n\nCopies the passed `buffer` data onto a new `Buffer` instance.\n\n```js\nconst buf1 = Buffer.from('buffer');\nconst buf2 = Buffer.from(buf1);\n\nbuf1[0] = 0x61;\nconsole.log(buf1.toString());\n  // 'auffer'\nconsole.log(buf2.toString());\n  // 'buffer' (copy is not changed)\n```\n\nA `TypeError` will be thrown if `buffer` is not a `Buffer`.\n\n### Class Method: Buffer.from(str[, encoding])\n<!-- YAML\nadded: v5.10.0\n-->\n\n* `str` {String} String to encode.\n* `encoding` {String} Encoding to use, Default: `'utf8'`\n\nCreates a new `Buffer` containing the given JavaScript string `str`. If\nprovided, the `encoding` parameter identifies the character encoding.\nIf not provided, `encoding` defaults to `'utf8'`.\n\n```js\nconst buf1 = Buffer.from('this is a tést');\nconsole.log(buf1.toString());\n  // prints: this is a tést\nconsole.log(buf1.toString('ascii'));\n  // prints: this is a tC)st\n\nconst buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex');\nconsole.log(buf2.toString());\n  // prints: this is a tést\n```\n\nA `TypeError` will be thrown if `str` is not a string.\n\n### Class Method: Buffer.alloc(size[, fill[, encoding]])\n<!-- YAML\nadded: v5.10.0\n-->\n\n* `size` {Number}\n* `fill` {Value} Default: `undefined`\n* `encoding` {String} Default: `utf8`\n\nAllocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the\n`Buffer` will be *zero-filled*.\n\n```js\nconst buf = Buffer.alloc(5);\nconsole.log(buf);\n  // <Buffer 00 00 00 00 00>\n```\n\nThe `size` must be less than or equal to the value of\n`require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is\n`(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will\nbe created if a `size` less than or equal to 0 is specified.\n\nIf `fill` is specified, the allocated `Buffer` will be initialized by calling\n`buf.fill(fill)`. See [`buf.fill()`][] for more information.\n\n```js\nconst buf = Buffer.alloc(5, 'a');\nconsole.log(buf);\n  // <Buffer 61 61 61 61 61>\n```\n\nIf both `fill` and `encoding` are specified, the allocated `Buffer` will be\ninitialized by calling `buf.fill(fill, encoding)`. For example:\n\n```js\nconst buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64');\nconsole.log(buf);\n  // <Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64>\n```\n\nCalling `Buffer.alloc(size)` can be significantly slower than the alternative\n`Buffer.allocUnsafe(size)` but ensures that the newly created `Buffer` instance\ncontents will *never contain sensitive data*.\n\nA `TypeError` will be thrown if `size` is not a number.\n\n### Class Method: Buffer.allocUnsafe(size)\n<!-- YAML\nadded: v5.10.0\n-->\n\n* `size` {Number}\n\nAllocates a new *non-zero-filled* `Buffer` of `size` bytes.  The `size` must\nbe less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit\narchitectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is\nthrown. A zero-length Buffer will be created if a `size` less than or equal to\n0 is specified.\n\nThe underlying memory for `Buffer` instances created in this way is *not\ninitialized*. The contents of the newly created `Buffer` are unknown and\n*may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such\n`Buffer` instances to zeroes.\n\n```js\nconst buf = Buffer.allocUnsafe(5);\nconsole.log(buf);\n  // <Buffer 78 e0 82 02 01>\n  // (octets will be different, every time)\nbuf.fill(0);\nconsole.log(buf);\n  // <Buffer 00 00 00 00 00>\n```\n\nA `TypeError` will be thrown if `size` is not a number.\n\nNote that the `Buffer` module pre-allocates an internal `Buffer` instance of\nsize `Buffer.poolSize` that is used as a pool for the fast allocation of new\n`Buffer` instances created using `Buffer.allocUnsafe(size)` (and the deprecated\n`new Buffer(size)` constructor) only when `size` is less than or equal to\n`Buffer.poolSize >> 1` (floor of `Buffer.poolSize` divided by two). The default\nvalue of `Buffer.poolSize` is `8192` but can be modified.\n\nUse of this pre-allocated internal memory pool is a key difference between\ncalling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`.\nSpecifically, `Buffer.alloc(size, fill)` will *never* use the internal Buffer\npool, while `Buffer.allocUnsafe(size).fill(fill)` *will* use the internal\nBuffer pool if `size` is less than or equal to half `Buffer.poolSize`. The\ndifference is subtle but can be important when an application requires the\nadditional performance that `Buffer.allocUnsafe(size)` provides.\n\n### Class Method: Buffer.allocUnsafeSlow(size)\n<!-- YAML\nadded: v5.10.0\n-->\n\n* `size` {Number}\n\nAllocates a new *non-zero-filled* and non-pooled `Buffer` of `size` bytes.  The\n`size` must be less than or equal to the value of\n`require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is\n`(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will\nbe created if a `size` less than or equal to 0 is specified.\n\nThe underlying memory for `Buffer` instances created in this way is *not\ninitialized*. The contents of the newly created `Buffer` are unknown and\n*may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such\n`Buffer` instances to zeroes.\n\nWhen using `Buffer.allocUnsafe()` to allocate new `Buffer` instances,\nallocations under 4KB are, by default, sliced from a single pre-allocated\n`Buffer`. This allows applications to avoid the garbage collection overhead of\ncreating many individually allocated Buffers. This approach improves both\nperformance and memory usage by eliminating the need to track and cleanup as\nmany `Persistent` objects.\n\nHowever, in the case where a developer may need to retain a small chunk of\nmemory from a pool for an indeterminate amount of time, it may be appropriate\nto create an un-pooled Buffer instance using `Buffer.allocUnsafeSlow()` then\ncopy out the relevant bits.\n\n```js\n// need to keep around a few small chunks of memory\nconst store = [];\n\nsocket.on('readable', () => {\n  const data = socket.read();\n  // allocate for retained data\n  const sb = Buffer.allocUnsafeSlow(10);\n  // copy the data into the new allocation\n  data.copy(sb, 0, 0, 10);\n  store.push(sb);\n});\n```\n\nUse of `Buffer.allocUnsafeSlow()` should be used only as a last resort *after*\na developer has observed undue memory retention in their applications.\n\nA `TypeError` will be thrown if `size` is not a number.\n\n### All the Rest\n\nThe rest of the `Buffer` API is exactly the same as in node.js.\n[See the docs](https://nodejs.org/api/buffer.html).\n\n\n## Related links\n\n- [Node.js issue: Buffer(number) is unsafe](https://github.com/nodejs/node/issues/4660)\n- [Node.js Enhancement Proposal: Buffer.from/Buffer.alloc/Buffer.zalloc/Buffer() soft-deprecate](https://github.com/nodejs/node-eps/pull/4)\n\n## Why is `Buffer` unsafe?\n\nToday, the node.js `Buffer` constructor is overloaded to handle many different argument\ntypes like `String`, `Array`, `Object`, `TypedArrayView` (`Uint8Array`, etc.),\n`ArrayBuffer`, and also `Number`.\n\nThe API is optimized for convenience: you can throw any type at it, and it will try to do\nwhat you want.\n\nBecause the Buffer constructor is so powerful, you often see code like this:\n\n```js\n// Convert UTF-8 strings to hex\nfunction toHex (str) {\n  return new Buffer(str).toString('hex')\n}\n```\n\n***But what happens if `toHex` is called with a `Number` argument?***\n\n### Remote Memory Disclosure\n\nIf an attacker can make your program call the `Buffer` constructor with a `Number`\nargument, then they can make it allocate uninitialized memory from the node.js process.\nThis could potentially disclose TLS private keys, user data, or database passwords.\n\nWhen the `Buffer` constructor is passed a `Number` argument, it returns an\n**UNINITIALIZED** block of memory of the specified `size`. When you create a `Buffer` like\nthis, you **MUST** overwrite the contents before returning it to the user.\n\nFrom the [node.js docs](https://nodejs.org/api/buffer.html#buffer_new_buffer_size):\n\n> `new Buffer(size)`\n>\n> - `size` Number\n>\n> The underlying memory for `Buffer` instances created in this way is not initialized.\n> **The contents of a newly created `Buffer` are unknown and could contain sensitive\n> data.** Use `buf.fill(0)` to initialize a Buffer to zeroes.\n\n(Emphasis our own.)\n\nWhenever the programmer intended to create an uninitialized `Buffer` you often see code\nlike this:\n\n```js\nvar buf = new Buffer(16)\n\n// Immediately overwrite the uninitialized buffer with data from another buffer\nfor (var i = 0; i < buf.length; i++) {\n  buf[i] = otherBuf[i]\n}\n```\n\n\n### Would this ever be a problem in real code?\n\nYes. It's surprisingly common to forget to check the type of your variables in a\ndynamically-typed language like JavaScript.\n\nUsually the consequences of assuming the wrong type is that your program crashes with an\nuncaught exception. But the failure mode for forgetting to check the type of arguments to\nthe `Buffer` constructor is more catastrophic.\n\nHere's an example of a vulnerable service that takes a JSON payload and converts it to\nhex:\n\n```js\n// Take a JSON payload {str: \"some string\"} and convert it to hex\nvar server = http.createServer(function (req, res) {\n  var data = ''\n  req.setEncoding('utf8')\n  req.on('data', function (chunk) {\n    data += chunk\n  })\n  req.on('end', function () {\n    var body = JSON.parse(data)\n    res.end(new Buffer(body.str).toString('hex'))\n  })\n})\n\nserver.listen(8080)\n```\n\nIn this example, an http client just has to send:\n\n```json\n{\n  \"str\": 1000\n}\n```\n\nand it will get back 1,000 bytes of uninitialized memory from the server.\n\nThis is a very serious bug. It's similar in severity to the\n[the Heartbleed bug](http://heartbleed.com/) that allowed disclosure of OpenSSL process\nmemory by remote attackers.\n\n\n### Which real-world packages were vulnerable?\n\n#### [`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht)\n\n[Mathias Buus](https://github.com/mafintosh) and I\n([Feross Aboukhadijeh](http://feross.org/)) found this issue in one of our own packages,\n[`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht). The bug would allow\nanyone on the internet to send a series of messages to a user of `bittorrent-dht` and get\nthem to reveal 20 bytes at a time of uninitialized memory from the node.js process.\n\nHere's\n[the commit](https://github.com/feross/bittorrent-dht/commit/6c7da04025d5633699800a99ec3fbadf70ad35b8)\nthat fixed it. We released a new fixed version, created a\n[Node Security Project disclosure](https://nodesecurity.io/advisories/68), and deprecated all\nvulnerable versions on npm so users will get a warning to upgrade to a newer version.\n\n#### [`ws`](https://www.npmjs.com/package/ws)\n\nThat got us wondering if there were other vulnerable packages. Sure enough, within a short\nperiod of time, we found the same issue in [`ws`](https://www.npmjs.com/package/ws), the\nmost popular WebSocket implementation in node.js.\n\nIf certain APIs were called with `Number` parameters instead of `String` or `Buffer` as\nexpected, then uninitialized server memory would be disclosed to the remote peer.\n\nThese were the vulnerable methods:\n\n```js\nsocket.send(number)\nsocket.ping(number)\nsocket.pong(number)\n```\n\nHere's a vulnerable socket server with some echo functionality:\n\n```js\nserver.on('connection', function (socket) {\n  socket.on('message', function (message) {\n    message = JSON.parse(message)\n    if (message.type === 'echo') {\n      socket.send(message.data) // send back the user's message\n    }\n  })\n})\n```\n\n`socket.send(number)` called on the server, will disclose server memory.\n\nHere's [the release](https://github.com/websockets/ws/releases/tag/1.0.1) where the issue\nwas fixed, with a more detailed explanation. Props to\n[Arnout Kazemier](https://github.com/3rd-Eden) for the quick fix. Here's the\n[Node Security Project disclosure](https://nodesecurity.io/advisories/67).\n\n\n### What's the solution?\n\nIt's important that node.js offers a fast way to get memory otherwise performance-critical\napplications would needlessly get a lot slower.\n\nBut we need a better way to *signal our intent* as programmers. **When we want\nuninitialized memory, we should request it explicitly.**\n\nSensitive functionality should not be packed into a developer-friendly API that loosely\naccepts many different types. This type of API encourages the lazy practice of passing\nvariables in without checking the type very carefully.\n\n#### A new API: `Buffer.allocUnsafe(number)`\n\nThe functionality of creating buffers with uninitialized memory should be part of another\nAPI. We propose `Buffer.allocUnsafe(number)`. This way, it's not part of an API that\nfrequently gets user input of all sorts of different types passed into it.\n\n```js\nvar buf = Buffer.allocUnsafe(16) // careful, uninitialized memory!\n\n// Immediately overwrite the uninitialized buffer with data from another buffer\nfor (var i = 0; i < buf.length; i++) {\n  buf[i] = otherBuf[i]\n}\n```\n\n\n### How do we fix node.js core?\n\nWe sent [a PR to node.js core](https://github.com/nodejs/node/pull/4514) (merged as\n`semver-major`) which defends against one case:\n\n```js\nvar str = 16\nnew Buffer(str, 'utf8')\n```\n\nIn this situation, it's implied that the programmer intended the first argument to be a\nstring, since they passed an encoding as a second argument. Today, node.js will allocate\nuninitialized memory in the case of `new Buffer(number, encoding)`, which is probably not\nwhat the programmer intended.\n\nBut this is only a partial solution, since if the programmer does `new Buffer(variable)`\n(without an `encoding` parameter) there's no way to know what they intended. If `variable`\nis sometimes a number, then uninitialized memory will sometimes be returned.\n\n### What's the real long-term fix?\n\nWe could deprecate and remove `new Buffer(number)` and use `Buffer.allocUnsafe(number)` when\nwe need uninitialized memory. But that would break 1000s of packages.\n\n~~We believe the best solution is to:~~\n\n~~1. Change `new Buffer(number)` to return safe, zeroed-out memory~~\n\n~~2. Create a new API for creating uninitialized Buffers. We propose: `Buffer.allocUnsafe(number)`~~\n\n#### Update\n\nWe now support adding three new APIs:\n\n- `Buffer.from(value)` - convert from any type to a buffer\n- `Buffer.alloc(size)` - create a zero-filled buffer\n- `Buffer.allocUnsafe(size)` - create an uninitialized buffer with given size\n\nThis solves the core problem that affected `ws` and `bittorrent-dht` which is\n`Buffer(variable)` getting tricked into taking a number argument.\n\nThis way, existing code continues working and the impact on the npm ecosystem will be\nminimal. Over time, npm maintainers can migrate performance-critical code to use\n`Buffer.allocUnsafe(number)` instead of `new Buffer(number)`.\n\n\n### Conclusion\n\nWe think there's a serious design issue with the `Buffer` API as it exists today. It\npromotes insecure software by putting high-risk functionality into a convenient API\nwith friendly \"developer ergonomics\".\n\nThis wasn't merely a theoretical exercise because we found the issue in some of the\nmost popular npm packages.\n\nFortunately, there's an easy fix that can be applied today. Use `safe-buffer` in place of\n`buffer`.\n\n```js\nvar Buffer = require('safe-buffer').Buffer\n```\n\nEventually, we hope that node.js core can switch to this new, safer behavior. We believe\nthe impact on the ecosystem would be minimal since it's not a breaking change.\nWell-maintained, popular packages would be updated to use `Buffer.alloc` quickly, while\nolder, insecure packages would magically become safe from this attack vector.\n\n\n## links\n\n- [Node.js PR: buffer: throw if both length and enc are passed](https://github.com/nodejs/node/pull/4514)\n- [Node Security Project disclosure for `ws`](https://nodesecurity.io/advisories/67)\n- [Node Security Project disclosure for`bittorrent-dht`](https://nodesecurity.io/advisories/68)\n\n\n## credit\n\nThe original issues in `bittorrent-dht`\n([disclosure](https://nodesecurity.io/advisories/68)) and\n`ws` ([disclosure](https://nodesecurity.io/advisories/67)) were discovered by\n[Mathias Buus](https://github.com/mafintosh) and\n[Feross Aboukhadijeh](http://feross.org/).\n\nThanks to [Adam Baldwin](https://github.com/evilpacket) for helping disclose these issues\nand for his work running the [Node Security Project](https://nodesecurity.io/).\n\nThanks to [John Hiesey](https://github.com/jhiesey) for proofreading this README and\nauditing the code.\n\n\n## license\n\nMIT. Copyright (C) [Feross Aboukhadijeh](http://feross.org)\n",
  "readmeFilename": "README.md",
  "_id": "safe-buffer@5.0.1",
  "_shasum": "d263ca54696cd8a306b5ca6551e92de57918fbe7",
  "_from": "safe-buffer@^5.0.1",
  "_resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.0.1.tgz"
}
