Skip to content

Commit

Permalink
Throwing error when insecure rng is used
Browse files Browse the repository at this point in the history
- New option for v1 and v4: allowInsecureRng
  - Require to be `true` if `rng.insecure == true`

Closes uuidjs#173
  • Loading branch information
uri committed Oct 4, 2018
1 parent 36a5f18 commit c5e439b
Show file tree
Hide file tree
Showing 4 changed files with 14 additions and 2 deletions.
8 changes: 6 additions & 2 deletions lib/rng-browser.js
Expand Up @@ -23,12 +23,16 @@ if (getRandomValues) {
// quality.
var rnds = new Array(16);

module.exports = function mathRNG() {
function mathRNG() {
for (var i = 0, r; i < 16; i++) {
if ((i & 0x03) === 0) r = Math.random() * 0x100000000;
rnds[i] = r >>> ((i & 0x03) << 3) & 0xff;
}

return rnds;
};
}
mathRNG.insecure = true;
mathRNG.insecureMessage = 'No CSPRNG provided. Provide a cryptographically secure rng' +
' via `rng` option or set `allowInsecureRNG` to true';
module.exports = mathRNG;
}
2 changes: 2 additions & 0 deletions test/test.js
Expand Up @@ -64,6 +64,8 @@ test('mathRNG', function() {
var rng = require('../lib/rng-browser');
assert.equal(rng.name, 'mathRNG');

assert.equal(rng.insecure, true)

var bytes = rng();
assert.equal(bytes.length, 16);

Expand Down
3 changes: 3 additions & 0 deletions v1.js
Expand Up @@ -22,6 +22,9 @@ function v1(options, buf, offset) {
var node = options.node || _nodeId;
var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq;

if (rng.insecure && !options.allowInsecureRNG)
throw new Error(rng.insecureMessage);

// node and clockseq need to be initialized to random values if they're not
// specified. We do this lazily to minimize issues related to insufficient
// system entropy. See #189
Expand Down
3 changes: 3 additions & 0 deletions v4.js
Expand Up @@ -12,6 +12,9 @@ function v4(options, buf, offset) {

var rnds = options.random || (options.rng || rng)();

if (rng.insecure && !options.allowInsecureRNG)
throw new Error(rng.insecureMessage);

// Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
rnds[6] = (rnds[6] & 0x0f) | 0x40;
rnds[8] = (rnds[8] & 0x3f) | 0x80;
Expand Down

0 comments on commit c5e439b

Please sign in to comment.