Skip to content

Commit 4e7a31b

Browse files
Trottitaloacasas
authored andcommitted
crypto,tls: fix mutability of return values
If you alter the array returned by `tls.getCiphers()`, `crypto.getCiphers()`, `crypto.getHashes()`, or `crypto.getCurves()`, it will alter subsequent return values from those functions. ```js 'use strict'; const crypto = require('crypto'); var hashes = crypto.getHashes(); hashes.splice(0, hashes.length); hashes.push('some-arbitrary-value'); console.log(crypto.getHashes()); // "['some-arbitrary-value']" ``` This is surprising. Change functions to return copy of array instead. PR-URL: #10795 Reviewed-By: Anna Henningsen <[email protected]> Reviewed-By: Сковорода Никита Андреевич <[email protected]> Reviewed-By: Sakthipriyan Vairamani <[email protected]> Reviewed-By: James M Snell <[email protected]> Reviewed-By: Sam Roberts <[email protected]>
1 parent 7165f1d commit 4e7a31b

File tree

3 files changed

+18
-4
lines changed

3 files changed

+18
-4
lines changed

lib/internal/util.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -158,7 +158,7 @@ exports.cachedResult = function cachedResult(fn) {
158158
return () => {
159159
if (result === undefined)
160160
result = fn();
161-
return result;
161+
return result.slice();
162162
};
163163
};
164164

lib/tls.js

+3-3
Original file line numberDiff line numberDiff line change
@@ -22,9 +22,9 @@ exports.DEFAULT_CIPHERS =
2222

2323
exports.DEFAULT_ECDH_CURVE = 'prime256v1';
2424

25-
exports.getCiphers = internalUtil.cachedResult(() => {
26-
return internalUtil.filterDuplicateStrings(binding.getSSLCiphers(), true);
27-
});
25+
exports.getCiphers = internalUtil.cachedResult(
26+
() => internalUtil.filterDuplicateStrings(binding.getSSLCiphers(), true)
27+
);
2828

2929
// Convert protocols array into valid OpenSSL protocols list
3030
// ("\x06spdy/2\x08http/1.1\x08http/1.0")

test/parallel/test-crypto.js

+14
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,20 @@ assert(crypto.getCurves().includes('secp384r1'));
9797
assert(!crypto.getCurves().includes('SECP384R1'));
9898
validateList(crypto.getCurves());
9999

100+
// Modifying return value from get* functions should not mutate subsequent
101+
// return values.
102+
function testImmutability(fn) {
103+
const list = fn();
104+
const copy = [...list];
105+
list.push('some-arbitrary-value');
106+
assert.deepStrictEqual(fn(), copy);
107+
}
108+
109+
testImmutability(crypto.getCiphers);
110+
testImmutability(tls.getCiphers);
111+
testImmutability(crypto.getHashes);
112+
testImmutability(crypto.getCurves);
113+
100114
// Regression tests for #5725: hex input that's not a power of two should
101115
// throw, not assert in C++ land.
102116
assert.throws(function() {

0 commit comments

Comments
 (0)