From 901d91508a70e3b9bdfc45688ea07bb4e1b8210d Mon Sep 17 00:00:00 2001 From: Richard Barnes Date: Wed, 8 Feb 2023 08:28:24 -0500 Subject: [PATCH] Merge pull request from GHSA-5h4j-qrvg-9xhw --- lib/deps/ecc/math.js | 1 + lib/deps/forge.js | 9 +++++++++ test/algorithms/ecc-test.js | 29 +++++++++++++++++++++++++++++ 3 files changed, 39 insertions(+) create mode 100644 test/algorithms/ecc-test.js diff --git a/lib/deps/ecc/math.js b/lib/deps/ecc/math.js index df9575c1..15ec91c8 100644 --- a/lib/deps/ecc/math.js +++ b/lib/deps/ecc/math.js @@ -46,6 +46,7 @@ function barrettRevert(x) { return x; } // x = x mod m (HAC 14.42) function barrettReduce(x) { + if (x.s < 0) { throw Error("Barrett reduction on negative input"); } x.drShiftTo(this.m.t-1,this.r2); if(x.t > this.m.t+1) { x.t = this.m.t+1; x.clamp(); } this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3); diff --git a/lib/deps/forge.js b/lib/deps/forge.js index 5a7abdee..3e898f5c 100644 --- a/lib/deps/forge.js +++ b/lib/deps/forge.js @@ -88,4 +88,13 @@ modeRaw.prototype.decrypt = function(input, output, finish) { forge.cipher.registerAlgorithm(name, factory); })(); +// Ensure that the jsbn modInverse function always returns a positive result +const originalModInverse = forge.jsbn.BigInteger.prototype.modInverse; +const positiveModInverse = function(m) { + const inv = originalModInverse.apply(this, [m]); + return inv.mod(m); +} + +forge.jsbn.BigInteger.prototype.modInverse = positiveModInverse; + module.exports = forge; diff --git a/test/algorithms/ecc-test.js b/test/algorithms/ecc-test.js new file mode 100644 index 00000000..18a99cee --- /dev/null +++ b/test/algorithms/ecc-test.js @@ -0,0 +1,29 @@ +/*! + * + * Copyright (c) 2015 Cisco Systems, Inc. See LICENSE file. + */ +"use strict"; + +var assert = require("chai").assert; + +const CURVES = require('../../lib/deps/ecc/curves.js'); +const BigInteger = require('../../lib/deps/forge').jsbn.BigInteger; + +describe("ecc/positive", function() { + const negativeModInverseCases = [ + '101067240514044546216936289506154965497874315269115226505131909313278720169941', + '47260992668897782856940293132731814279826643476197468731642996160637470667669', + ] + + const p = CURVES["P-256"].curve.p; + + const runner = () => { + for (const kStr of negativeModInverseCases) { + const k = new BigInteger(kStr); + const kinv = k.modInverse(p); + assert.isAtLeast(kinv.s, 0, "Negative mod inverse"); + } + }; + + it('normalizes negative modular inverses', runner); +})