Skip to content

Commit 5a29ee6

Browse files
committed
[squash] buffer: add "strict" harden mode (default)
1 parent cebb1d5 commit 5a29ee6

1 file changed

Lines changed: 20 additions & 7 deletions

File tree

lib/buffer.js

Lines changed: 20 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -113,7 +113,12 @@ const zeroFill = bindingZeroFill || [0];
113113
// Hardening Buffer enables Buffer constructor runtime deprecation,
114114
// disables pooling, and enables mandratory zero-fill. This is more secure, but
115115
// has potential performance impact, depending on the usecase.
116-
let hardened = false;
116+
const harden = {
117+
NONE: 0, // falsy
118+
STRICT: 1,
119+
LAX: 2,
120+
};
121+
let hardened = harden.NONE;
117122

118123
function createUnsafeBuffer(size) {
119124
zeroFill[0] = hardened ? 1 : 0;
@@ -147,10 +152,13 @@ const bufferWarning = 'Buffer() is deprecated due to security and usability ' +
147152

148153
function showFlaggedDeprecation() {
149154
if (hardened) {
155+
if (hardened !== harden.LAX) {
156+
throw new ERR_ASSERTION(
157+
'Unsafe Buffer() API is forbidden by Buffer strict hardening opt-in.'
158+
);
159+
}
150160
if (bufferWarningAlreadyEmitted) return;
151-
process.emitWarning(
152-
bufferWarning + ' Buffer() will soon throw in hardened mode.',
153-
'DeprecationWarning', 'DEP0XXX');
161+
process.emitWarning(bufferWarning, 'DeprecationWarning', 'DEP0005');
154162
bufferWarningAlreadyEmitted = true;
155163
return;
156164
}
@@ -173,15 +181,20 @@ function showFlaggedDeprecation() {
173181
}
174182

175183
// Calling this method does not affect existing buffers, only new ones.
176-
Buffer.harden = function() {
177-
if (hardened) return;
184+
Buffer.harden = function({ strict = true } = {}) {
185+
if (hardened) {
186+
// So that params are not changed afterwards
187+
throw new ERR_ASSERTION(
188+
'Buffer.harden can be called only once'
189+
);
190+
}
178191
if (isInsideNodeModules()) {
179192
throw new ERR_ASSERTION(
180193
'Buffer.harden() should be called only from the top-level module. ' +
181194
'Calling Buffer.harden() from dependencies is not supported.'
182195
);
183196
}
184-
hardened = true;
197+
hardened = strict ? harden.STRICT : harden.LAX;
185198
Object.defineProperty(Buffer, 'poolSize', {
186199
enumerable: true,
187200
get: () => 0,

0 commit comments

Comments
 (0)