{"action":"created","issue":{"url":"https://api.github.com/repos/nodejs/node/issues/4660","labels_url":"https://api.github.com/repos/nodejs/node/issues/4660/labels{/name}","comments_url":"https://api.github.com/repos/nodejs/node/issues/4660/comments","events_url":"https://api.github.com/repos/nodejs/node/issues/4660/events","html_url":"https://github.com/nodejs/node/issues/4660","id":126343377,"number":4660,"title":"Buffer(number) is unsafe","user":{"login":"feross","id":121766,"avatar_url":"https://avatars.githubusercontent.com/u/121766?v=3","gravatar_id":"","url":"https://api.github.com/users/feross","html_url":"https://github.com/feross","followers_url":"https://api.github.com/users/feross/followers","following_url":"https://api.github.com/users/feross/following{/other_user}","gists_url":"https://api.github.com/users/feross/gists{/gist_id}","starred_url":"https://api.github.com/users/feross/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/feross/subscriptions","organizations_url":"https://api.github.com/users/feross/orgs","repos_url":"https://api.github.com/users/feross/repos","events_url":"https://api.github.com/users/feross/events{/privacy}","received_events_url":"https://api.github.com/users/feross/received_events","type":"User","site_admin":false},"labels":[{"url":"https://api.github.com/repos/nodejs/node/labels/buffer","name":"buffer","color":"f7c6c7"},{"url":"https://api.github.com/repos/nodejs/node/labels/ctc-agenda","name":"ctc-agenda","color":"5319e7"},{"url":"https://api.github.com/repos/nodejs/node/labels/discuss","name":"discuss","color":"02d7e1"},{"url":"https://api.github.com/repos/nodejs/node/labels/security","name":"security","color":"bb3344"}],"state":"open","locked":false,"assignee":null,"milestone":null,"comments":58,"created_at":"2016-01-13T05:19:14Z","updated_at":"2016-01-14T02:58:45Z","closed_at":null,"body":"### tl;dr\r\n\r\nThis issue proposes:\r\n\r\n1. Change `new Buffer(number)` to return safe, zeroed-out memory\r\n\r\n2. Create a new API for creating uninitialized Buffers, `Buffer.alloc(number)`\r\n\r\n### Why is `Buffer` unsafe?\r\n\r\nToday, the node.js `Buffer` constructor is overloaded to handle many different argument types like `String`, `Array`, `Object`, `TypedArrayView` (`Uint8Array`, etc.), `ArrayBuffer`, and also `Number`.\r\n\r\nThe API is optimized for convenience: you can throw any type at it, and it will try to do what you want.\r\n\r\nBecause the Buffer constructor is so powerful, you often see code like this:\r\n\r\n```js\r\n// Convert UTF-8 strings to hex\r\nfunction toHex (str) {\r\n  return new Buffer(str).toString('hex')\r\n}\r\n```\r\n\r\n***But what happens if `toHex` is called with a `Number` argument?***\r\n\r\n### Remote Memory Disclosure\r\n\r\nIf 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.\r\n\r\nWhen 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.\r\n\r\n\r\n### Would this ever be a problem in real code?\r\n\r\nYes. It's surprisingly common to forget to check the type of your variables in a dynamically-typed language like JavaScript.\r\n\r\nUsually the consequences of assuming the wrong type is that your program crashes with an uncaught exception. But the failure mode for forgetting to check the type of arguments to the `Buffer` constructor is more catastrophic.\r\n\r\nHere's an example of a vulnerable service that takes a JSON payload and converts it to hex:\r\n\r\n```js\r\n// Take a JSON payload {str: \"some string\"} and convert it to hex\r\nvar server = http.createServer(function (req, res) {\r\n  var data = ''\r\n  req.setEncoding('utf8')\r\n  req.on('data', function (chunk) {\r\n    data += chunk\r\n  })\r\n  req.on('end', function () {\r\n    var body = JSON.parse(data)\r\n    res.end(new Buffer(body.str).toString('hex'))\r\n  })\r\n})\r\n\r\nserver.listen(8080)\r\n```\r\n\r\nIn this example, an http client just has to send:\r\n\r\n```json\r\n{\r\n  \"str\": 1000\r\n}\r\n```\r\n\r\nand it will get back 1,000 bytes of uninitialized memory from the server.\r\n\r\nThis is a very serious bug. It's similar in severity to the [the Heartbleed bug](http://heartbleed.com/) that allowed disclosure of OpenSSL process memory by remote attackers.\r\n\r\n\r\n### Which real-world packages were vulnerable?\r\n\r\n#### [`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht)\r\n\r\n@mafintosh and I found this issue in one of our own packages, [`bittorrent-dht`](https://www.npmjs.com/package/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.\r\n\r\nHere's [the commit](https://github.com/feross/bittorrent-dht/commit/6c7da04025d5633699800a99ec3fbadf70ad35b8) that fixed it. We released a new fixed version, created a [Node Security Project disclosure](https://nodesecurity.io/advisories/68), and deprecated all vulnerable versions on npm so users will get a warning to upgrade to a newer version.\r\n\r\n#### [`ws`](https://www.npmjs.com/package/ws)\r\n\r\nThat got us wondering if there were other vulnerable packages. Sure enough, within a short period of time, we found the same issue in [`ws`](https://www.npmjs.com/package/ws), the most popular WebSocket implementation in node.js.\r\n\r\nIf certain APIs were called with `Number` parameters instead of `String` or `Buffer` as expected, then uninitialized server memory would be disclosed to the remote peer.\r\n\r\nThese were the vulnerable methods:\r\n\r\n```js\r\nsocket.send(number)\r\nsocket.ping(number)\r\nsocket.pong(number)\r\n```\r\n\r\nHere's a vulnerable socket server with some echo functionality:\r\n\r\n```js\r\nserver.on('connection', function (socket) {\r\n  socket.on('message', function (message) {\r\n    message = JSON.parse(message)\r\n    if (message.type === 'echo') {\r\n      socket.send(message.data) // send back the user's message\r\n    }\r\n  })\r\n})\r\n```\r\n\r\n`socket.send(number)` called on the server, will disclose server memory.\r\n\r\nHere's [the release](https://github.com/websockets/ws/releases/tag/1.0.1) where the issue was fixed, with a more detailed explanation. Props to @3rd-Eden for the quick fix. Here's the [Node Security Project disclosure](https://nodesecurity.io/advisories/67).\r\n\r\n\r\n### What's the solution?\r\n\r\nIt's important that node.js offers a fast way to get memory otherwise performance-critical applications would needlessly get a lot slower.\r\n\r\nBut we need a better way to *signal our intent* as programmers. **When we want uninitialized memory, we should request it explicitly.**\r\n\r\nSensitive functionality should not be packed into a developer-friendly API that loosely accepts many different types. This type of API encourages the lazy practice of passing variables in without checking the type very carefully.\r\n\r\n#### `Buffer.alloc(number)`\r\n\r\nThe functionality of creating buffers with uninitialized memory should be part of another API. We propose `Buffer.alloc(number)`. This way, it's not part of an API that frequently gets user input of all sorts of different types passed into it.\r\n\r\n```js\r\nvar buf = Buffer.alloc(16) // careful, uninitialized memory!\r\n\r\n// Immediately overwrite the uninitialized buffer with data from another buffer\r\nfor (var i = 0; i < buf.length; i++) {\r\n  buf[i] = otherBuf[i]\r\n}\r\n```\r\n\r\n\r\n### How do we fix node.js core?\r\n\r\nWe sent [a PR](https://github.com/nodejs/node/pull/4514) (merged as `semver-major`) which defends against one case:\r\n\r\n```js\r\nvar str = 16\r\nnew Buffer(str, 'utf8')\r\n```\r\n\r\nIn this situation, it's implied that the programmer intended the first argument to be a string, since they passed an encoding as a second argument. Today, node.js will allocate uninitialized memory in the case of `new Buffer(number, encoding)`, which is probably not what the programmer intended.\r\n\r\nBut this is only a partial solution, since if the programmer does `new Buffer(variable)` (without an `encoding` parameter) there's no way to know what they intended. If `variable` is sometimes a number, then uninitialized memory will sometimes be returned.\r\n\r\n### What's the real long-term fix?\r\n\r\nWe could deprecate and remove `new Buffer(number)` and use `Buffer.alloc(number)` when we need uninitialized memory. But that would break 1000s of packages. So that's a no-go.\r\n\r\nInstead, we believe the best solution is to:\r\n\r\n1. Change `new Buffer(number)` to return safe, zeroed-out memory\r\n\r\n2. Create a new API for creating uninitialized Buffers. We propose: `Buffer.alloc(number)`\r\n\r\nThis way, existing code continues working and the impact on the npm ecosystem will be minimal. Over time, npm maintainers can migrate performance-critical code to use `Buffer.alloc(number)` instead of `new Buffer(number)`.\r\n\r\n\r\n### Conclusion\r\n\r\nWe 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\".\r\n\r\nThis wasn't merely a theoretical exercise because we found the issue in some of the most popular npm packages.\r\n\r\nEventually, 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."},"comment":{"url":"https://api.github.com/repos/nodejs/node/issues/comments/171515865","html_url":"https://github.com/nodejs/node/issues/4660#issuecomment-171515865","issue_url":"https://api.github.com/repos/nodejs/node/issues/4660","id":171515865,"user":{"login":"tqbf","id":13419,"avatar_url":"https://avatars.githubusercontent.com/u/13419?v=3","gravatar_id":"","url":"https://api.github.com/users/tqbf","html_url":"https://github.com/tqbf","followers_url":"https://api.github.com/users/tqbf/followers","following_url":"https://api.github.com/users/tqbf/following{/other_user}","gists_url":"https://api.github.com/users/tqbf/gists{/gist_id}","starred_url":"https://api.github.com/users/tqbf/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/tqbf/subscriptions","organizations_url":"https://api.github.com/users/tqbf/orgs","repos_url":"https://api.github.com/users/tqbf/repos","events_url":"https://api.github.com/users/tqbf/events{/privacy}","received_events_url":"https://api.github.com/users/tqbf/received_events","type":"User","site_admin":false},"created_at":"2016-01-14T02:58:45Z","updated_at":"2016-01-14T02:58:45Z","body":"You will perish in flames."}}