keypair is a a RSA PEM key generator written in javascript. keypair implements a lot of cryptographic primitives on its own or by borrowing…
GitHub_M·CWE-335·Published 2021-10-11
keypair is a a RSA PEM key generator written in javascript. keypair implements a lot of cryptographic primitives on its own or by borrowing from other libraries where possible, including node-forge. An issue was discovered where this library was generating identical RSA keys used in SSH. This would mean that the library is generating identical P, Q (and thus N) values which, in practical terms, is impossible with RSA-2048 keys. Generating identical values, repeatedly, usually indicates an issue with poor random number generation, or, poor handling of CSPRNG output. Issue 1: Poor random number generation (`GHSL-2021-1012`). The library does not rely entirely on a platform provided CSPRNG, rather, it uses it's own counter-based CMAC approach. Where things go wrong is seeding the CMAC implementation with "true" random data in the function `defaultSeedFile`. In order to seed the AES-CMAC generator, the library will take two different approaches depending on the JavaScript execution environment. In a browser, the library will use [`window.crypto.getRandomValues()`](https://github.com/juliangruber/keypair/blob/87c62f255baa12c1ec4f98a91600f82af80be6db/index.js#L971). However, in a nodeJS execution environment, the `window` object is not defined, so it goes down a much less secure solution, also of which has a bug in it. It does look like the library tries to use node's CSPRNG when possible unfortunately, it looks like the `crypto` object is null because a variable was declared with the same name, and set to `null`. So the node CSPRNG path is never taken. However, when `window.crypto.getRandomValues()` is not available, a Lehmer LCG random number generator is used to seed the CMAC counter, and the LCG is seeded with `Math.random`. While this is poor and would likely qualify in a security bug in itself, it does not explain the extreme frequency in which duplicate keys occur. The main flaw: The output from the Lehmer LCG is encoded incorrectly. The specific [line][https://github.com/juliangruber/keypair/blob/87c62f255baa12c1ec4f98a91600f82af80be6db/index.js#L1008] with the flaw is: `b.putByte(String.fromCharCode(next & 0xFF))` The [definition](https://github.com/juliangruber/keypair/blob/87c62f255baa12c1ec4f98a91600f82af80be6db/index.js#L350-L352) of `putByte` is `util.ByteBuffer.prototype.putByte = function(b) {this.data += String.fromCharCode(b);};`. Simplified, this is `String.fromCharCode(String.fromCharCode(next & 0xFF))`. The double `String.fromCharCode` is almost certainly unintentional and the source of weak seeding. Unfortunately, this does not result in an error. Rather, it results most of the buffer containing zeros. Since we are masking with 0xFF, we can determine that 97% of the output from the LCG are converted to zeros. The only outputs that result in meaningful values are outputs 48 through 57, inclusive. The impact is that each byte in the RNG seed has a 97% chance of being 0 due to incorrect conversion. When it is not, the bytes are 0 through 9. In summary, there are three immediate concerns: 1. The library has an insecure random number fallback path. Ideally the library would require a strong CSPRNG instead of attempting to use a LCG and `Math.random`. 2. The library does not correctly use a strong random number generator when run in NodeJS, even though a strong CSPRNG is available. 3. The fallback path has an issue in the implementation where a majority of the seed data is going to effectively be zero. Due to the poor random number generation, keypair generates RSA keys that are relatively easy to guess. This could enable an attacker to decrypt confidential messages or gain authorized access to an account belonging to the victim.
keypair is a a RSA PEM key generator written in javascript. keypair implements a lot of cryptographic primitives on its own or by borrowing from other libraries where possible, including node-forge. An issue was discovered where this library was generating identical RSA keys used in SSH. This would mean that the library is generating identical P, Q (and thus N) values which, in practical terms, is impossible with RSA-2048 keys. Generating identical values, repeatedly, usually indicates an issue with poor random number generation, or, poor handling of CSPRNG output. Issue 1: Poor random number generation (`GHSL-2021-1012`). The library does not rely entirely on a platform provided CSPRNG, rather, it uses it's own counter-based CMAC approach. Where things go wrong is seeding the CMAC implementation with "true" random data in the function `defaultSeedFile`. In order to seed the AES-CMAC generator, the library will take two different approaches depending on the JavaScript execution environment. In a browser, the library will use [`window.crypto.getRandomValues()`](https://github.com/juliangruber/keypair/blob/87c62f255baa12c1ec4f98a91600f82af80be6db/index.js#L971). However, in a nodeJS execution environment, the `window` object is not defined, so it goes down a much less secure solution, also of which has a bug in it. It does look like the library tries to use node's CSPRNG when possible unfortunately, it looks like the `crypto` object is null because a variable was declared with the same name, and set to `null`. So the node CSPRNG path is never taken. However, when `window.crypto.getRandomValues()` is not available, a Lehmer LCG random number generator is used to seed the CMAC counter, and the LCG is seeded with `Math.random`. While this is poor and would likely qualify in a security bug in itself, it does not explain the extreme frequency in which duplicate keys occur. The main flaw: The output from the Lehmer LCG is encoded incorrectly. The specific [line][https://github.com/juliangruber/keypair/blob/87c62f255baa12c1ec4f98a91600f82af80be6db/index.js#L1008] with the flaw is: `b.putByte(String.fromCharCode(next & 0xFF))` The [definition](https://github.com/juliangruber/keypair/blob/87c62f255baa12c1ec4f98a91600f82af80be6db/index.js#L350-L352) of `putByte` is `util.ByteBuffer.prototype.putByte = function(b) {this.data += String.fromCharCode(b);};`. Simplified, this is `String.fromCharCode(String.fromCharCode(next & 0xFF))`. The double `String.fromCharCode` is almost certainly unintentional and the source of weak seeding. Unfortunately, this does not result in an error. Rather, it results most of the buffer containing zeros. Since we are masking with 0xFF, we can determine that 97% of the output from the LCG are converted to zeros. The only outputs that result in meaningful values are outputs 48 through 57, inclusive. The impact is that each byte in the RNG seed has a 97% chance of being 0 due to incorrect conversion. When it is not, the bytes are 0 through 9. In summary, there are three immediate concerns: 1. The library has an insecure random number fallback path. Ideally the library would require a strong CSPRNG instead of attempting to use a LCG and `Math.random`. 2. The library does not correctly use a strong random number generator when run in NodeJS, even though a strong CSPRNG is available. 3. The fallback path has an issue in the implementation where a majority of the seed data is going to effectively be zero. Due to the poor random number generation, keypair generates RSA keys that are relatively easy to guess. This could enable an attacker to decrypt confidential messages or gain authorized access to an account belonging to the victim.
## Description and Impact A bug in the pseudo-random number generator used by [keypair](https://github.com/juliangruber/keypair) versions up to and including 1.0.3 could allow for weak RSA key generation. This could enable an attacker to decrypt confidential messages or gain authorized access to an account belonging to the victim. We recommend replacing any RSA keys that were generated using keypair version 1.0.3 or earlier. ## Fix * The [bug](https://github.com/juliangruber/keypair/blob/87c62f255baa12c1ec4f98a91600f82af80be6db/index.js#L1008) in the pseudo-random number generator is fixed in commit [`9596418`](https://github.com/juliangruber/keypair/commit/9596418d3363d3e757676c0b6a8f2d35a9d1cb18). * If the crypto module is available, it is used instead of the pseudo-random number generator. Also fixed in [`9596418`](https://github.com/juliangruber/keypair/commit/9596418d3363d3e757676c0b6a8f2d35a9d1cb18) ## Additional Details The specific [line](https://github.com/juliangruber/keypair/blob/87c62f255baa12c1ec4f98a91600f82af80be6db/index.js#L1008) with the flaw is: ```javascript b.putByte(String.fromCharCode(next & 0xFF)) ``` The [definition](https://github.com/juliangruber/keypair/blob/87c62f255baa12c1ec4f98a91600f82af80be6db/index.js#L350-L352) of `putByte` is ```javascript util.ByteBuffer.prototype.putByte = function(b) { this.data += String.fromCharCode(b); }; ``` Simplified, this is `String.fromCharCode(String.fromCharCode(next & 0xFF))`. This results in most of the buffer containing zeros. An example generated buffer: (Note: truncated for brevity) ``` \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00 \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00 \x00\x00\x00\x00\x04\x00\x00\x00....\x00\x00\x00\x00\x00\x00\x00\x00\x00 \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00 \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00 ``` Since it is masking with 0xFF, approximately 97% of the bytes are converted to zeros. The impact is that each byte in the RNG seed has a 97% chance of being 0 due to incorrect conversion. ## Credit This issue was reported to GitHub Security Lab by Ross Wheeler of Axosoft. It was discovered by Axosoft engineer Dan Suceava, who noticed that [keypair](https://github.com/juliangruber/keypair) was regularly generating duplicate RSA keys. GitHub security engineer [@vcsjones (Kevin Jones)](https://github.com/vcsjones) independently investigated the problem and identified the cause and source code location of the bug.
## Description and Impact A bug in the pseudo-random number generator used by [keypair](https://github.com/juliangruber/keypair) versions up to and including 1.0.3 could allow for weak RSA key generation. This could enable an attacker to decrypt confidential messages or gain authorized access to an account belonging to the victim. We recommend replacing any RSA keys that were generated using keypair version 1.0.3 or earlier. ## Fix * The [bug](https://github.com/juliangruber/keypair/blob/87c62f255baa12c1ec4f98a91600f82af80be6db/index.js#L1008) in the pseudo-random number generator is fixed in commit [`9596418`](https://github.com/juliangruber/keypair/commit/9596418d3363d3e757676c0b6a8f2d35a9d1cb18). * If the crypto module is available, it is used instead of the pseudo-random number generator. Also fixed in [`9596418`](https://github.com/juliangruber/keypair/commit/9596418d3363d3e757676c0b6a8f2d35a9d1cb18) ## Additional Details The specific [line](https://github.com/juliangruber/keypair/blob/87c62f255baa12c1ec4f98a91600f82af80be6db/index.js#L1008) with the flaw is: ```javascript b.putByte(String.fromCharCode(next & 0xFF)) ``` The [definition](https://github.com/juliangruber/keypair/blob/87c62f255baa12c1ec4f98a91600f82af80be6db/index.js#L350-L352) of `putByte` is ```javascript util.ByteBuffer.prototype.putByte = function(b) { this.data += String.fromCharCode(b); }; ``` Simplified, this is `String.fromCharCode(String.fromCharCode(next & 0xFF))`. This results in most of the buffer containing zeros. An example generated buffer: (Note: truncated for brevity) ``` \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00 \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00 \x00\x00\x00\x00\x04\x00\x00\x00....\x00\x00\x00\x00\x00\x00\x00\x00\x00 \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00 \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00 ``` Since it is masking with 0xFF, approximately 97% of the bytes are converted to zeros. The impact is that each byte in the RNG seed has a 97% chance of being 0 due to incorrect conversion. ## Credit This issue was reported to GitHub Security Lab by Ross Wheeler of Axosoft. It was discovered by Axosoft engineer Dan Suceava, who noticed that [keypair](https://github.com/juliangruber/keypair) was regularly generating duplicate RSA keys. GitHub security engineer [@vcsjones (Kevin Jones)](https://github.com/vcsjones) independently investigated the problem and identified the cause and source code location of the bug.
keypair es un generador de claves RSA PEM escrito en javascript. keypair implementa un montón de primitivas criptográficas por sí mismo o tomando prestado de otras bibliotecas cuando es posible, incluyendo node-forge. Se detectó un problema en el que esta biblioteca genera claves RSA idénticas a las usadas en SSH. Esto significa que la biblioteca está generando valores P, Q (y por lo tanto N) idénticos, lo cual, en términos prácticos, es imposible con claves RSA-2048. Generar valores idénticos, repetidamente, indica un problema de generación de números aleatorios pobre, o, un manejo inapropiado de la salida del CSPRNG. Problema 1: Generación inapropiada de números aleatorios ("GHSL-2021-1012"). La biblioteca no se basa completamente en un CSPRNG proporcionado por la plataforma, sino que usa su propio enfoque CMAC basado en contadores. Donde las cosas van inapropiadamente es al sembrar la implementación de CMAC con datos aleatorios "true" en la función "defaultSeedFile". Para sembrar el generador de AES-CMAC, la biblioteca toma dos enfoques diferentes dependiendo del entorno de ejecución de JavaScript. En un navegador, la biblioteca usa ["window.crypto.getRandomValues()"](https://github.com/juliangruber/keypair/blob/87c62f255baa12c1ec4f98a91600f82af80be6db/index.js#L971). Sin embargo, en un entorno de ejecución nodeJS, el objeto "window" no está definido, por lo que se recurre a una solución mucho menos segura, que presenta un bug. Parece que la librería intenta usar el CSPRNG de node cuando es posible, desafortunadamente, parece que el objeto "crypto" es nulo porque se declaró una variable con el mismo nombre, y se estableció como "null". La ruta del CSPRNG del nodo nunca se toma. Sin embargo, cuando "window.crypto.getRandomValues()" no está disponible, se usa un generador de números aleatorios LCG de Lehmer para sembrar el contador CMAC, y el LCG es sembrado con "Math.random". Mientras que esto es pobre y probablemente calificaría en un fallo de seguridad en sí mismo, no explica la extrema frecuencia en la que se producen claves duplicadas. El principal fallo: la salida del LCG de Lehmer está codificada incorrectamente. La [línea][https://github.com/juliangruber/keypair/blob/87c62f255baa12c1ec4f98a91600f82af80be6db/index.js#L1008] específica con el fallo es: "b.putByte(String.fromCharCode(next & 0xFF))" La [definición](https://github.com/juliangruber/keypair/blob/87c62f255baa12c1ec4f98a91600f82af80be6db/index.js#L350-L352) de "putByte" es "util.ByteBuffer.prototype.putByte = function(b) {this.data += String.fromCharCode(b);};". Simplificado, esto es "String.fromCharCode(String.fromCharCode(next & 0xFF))". El doble "String.fromCharCode" es casi seguro que no es intencionado y es el origen de una semilla débil. Esto no resulta en un error. Hace que la mayor parte del buffer contenga ceros. Al estar enmascarando con 0xFF, podemos determinar que el 97% de las salidas del LCG se convierten en ceros. Las únicas salidas que resultan en valores significativos son las salidas 48 a 57, inclusive. El impacto es que cada byte en la semilla RNG presenta un 97% de posibilidades de ser 0 debido a una conversión incorrecta. Cuando no lo es, los bytes son del 0 al 9. En resumen, hay tres preocupaciones inmediatas: 1. La biblioteca presenta una ruta de retorno de números aleatorios no segura. Lo ideal es que la biblioteca requiriera un CSPRNG fuerte en lugar de intentar usar un LCG y "Math.random". 2. La librería no usa correctamente un generador de números aleatorios fuerte cuando se ejecuta en NodeJS, incluso cuando un CSPRNG fuerte está disponible. 3. La ruta de retorno tiene un problema en la implementación donde la mayoría de los datos de la semilla serán efectivamente cero. Debido a la pobre generación de números aleatorios, keypair genera claves RSA que son relativamente fáciles de adivinar. Esto podría permitir a un atacante descifrar mensajes confidenciales o conseguir acceso autorizado a una cuenta perteneciente a la víctima
| Version | Type | Source | Base | Exp | Impact | Vector |
|---|---|---|---|---|---|---|
| 2.0 | Primary | NVD | 6.4 | 10.0 | 4.9 | AV:N/AC:L/Au:N/C:P/I:P/A:N |
| 3.1 | Primary | NVD | 9.1 | 3.9 | 5.2 | CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:N |
| 3.1 | Primary | cve.org | 8.7 | — | — | CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:C/C:H/I:H/A:N |
| 3.1 | Primary | cve.org | 8.7 | — | — | CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:C/C:H/I:H/A:N |
| 3.1 | Secondary | NVD | 8.7 | 2.2 | 5.8 | CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:C/C:H/I:H/A:N |
| 3.1 | Secondary | GHSA | 8.7 | — | — | CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:C/C:H/I:H/A:N |