\label{_overview}%
 \hypertarget{md_sfcode_node_modules_safer_buffer_Porting_Buffer_autotoc_md26084}{}\doxysection{Overview}\label{md_sfcode_node_modules_safer_buffer_Porting_Buffer_autotoc_md26084}

\begin{DoxyItemize}
\item \href{\#variant-1}{\texttt{ Variant 1\+: Drop support for Node.\+js ≤ 4.\+4.\+x and 5.\+0.\+0 — 5.\+9.\+x.}} ({\itshape recommended})
\item \href{\#variant-2}{\texttt{ Variant 2\+: Use a polyfill}}
\item \href{\#variant-3}{\texttt{ Variant 3\+: manual detection, with safeguards}}
\end{DoxyItemize}\hypertarget{md_sfcode_node_modules_safer_buffer_Porting_Buffer_autotoc_md26085}{}\doxysubsection{Finding problematic bits of code using grep}\label{md_sfcode_node_modules_safer_buffer_Porting_Buffer_autotoc_md26085}
Just run `grep -\/nrE '\mbox{[}$^\wedge$a-\/z\+A-\/Z\mbox{]}(Slow)?Buffer\textbackslash{}s$\ast$(\textquotesingle{} --exclude-\/dir node\+\_\+modules\`{}.

It will find all the potentially unsafe places in your own code (with some considerably unlikely exceptions).\hypertarget{md_sfcode_node_modules_safer_buffer_Porting_Buffer_autotoc_md26086}{}\doxysubsection{Finding problematic bits of code using Node.\+js 8}\label{md_sfcode_node_modules_safer_buffer_Porting_Buffer_autotoc_md26086}
If you’re using Node.\+js ≥ 8.\+0.\+0 (which is recommended), Node.\+js exposes multiple options that help with finding the relevant pieces of code\+:


\begin{DoxyItemize}
\item {\ttfamily -\/-\/trace-\/warnings} will make Node.\+js show a stack trace for this warning and other warnings that are printed by Node.\+js.
\item {\ttfamily -\/-\/trace-\/deprecation} does the same thing, but only for deprecation warnings.
\item {\ttfamily -\/-\/pending-\/deprecation} will show more types of deprecation warnings. In particular, it will show the {\ttfamily Buffer()} deprecation warning, even on Node.\+js 8.
\end{DoxyItemize}

You can set these flags using an environment variable\+:


\begin{DoxyCode}{0}
\DoxyCodeLine{\$ export NODE\_OPTIONS='-\/-\/trace-\/warnings -\/-\/pending-\/deprecation'}
\DoxyCodeLine{\$ cat example.js}
\DoxyCodeLine{'use strict';}
\DoxyCodeLine{const foo = new Buffer('foo');}
\DoxyCodeLine{\$ node example.js}
\DoxyCodeLine{(node:7147) [DEP0005] DeprecationWarning: The Buffer() and new Buffer() constructors are not recommended for use due to security and usability concerns. Please use the new Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() construction methods instead.}
\DoxyCodeLine{    at showFlaggedDeprecation (buffer.js:127:13)}
\DoxyCodeLine{    at new Buffer (buffer.js:148:3)}
\DoxyCodeLine{    at Object.<anonymous> (/path/to/example.js:2:13)}
\DoxyCodeLine{    [... more stack trace lines ...] }

\end{DoxyCode}
\hypertarget{md_sfcode_node_modules_safer_buffer_Porting_Buffer_autotoc_md26087}{}\doxysubsection{Finding problematic bits of code using linters}\label{md_sfcode_node_modules_safer_buffer_Porting_Buffer_autotoc_md26087}
Eslint rules \href{https://eslint.org/docs/rules/no-buffer-constructor}{\texttt{ no-\/buffer-\/constructor}} or \href{https://github.com/mysticatea/eslint-plugin-node/blob/master/docs/rules/no-deprecated-api.md}{\texttt{ node/no-\/deprecated-\/api}} also find calls to deprecated {\ttfamily Buffer()} API. Those rules are included in some pre-\/sets.

There is a drawback, though, that it doesn\textquotesingle{}t always \href{https://github.com/chalker/safer-buffer\#why-not-safe-buffer}{\texttt{ work correctly}} when {\ttfamily Buffer} is overriden e.\+g. with a polyfill, so recommended is a combination of this and some other method described above.

\label{_variant-1}%
 \hypertarget{md_sfcode_node_modules_safer_buffer_Porting_Buffer_autotoc_md26088}{}\doxysection{Variant 1\+: Drop support for Node.\+js ≤ 4.\+4.\+x and 5.\+0.\+0 — 5.\+9.\+x.}\label{md_sfcode_node_modules_safer_buffer_Porting_Buffer_autotoc_md26088}
This is the recommended solution nowadays that would imply only minimal overhead.

The Node.\+js 5.\+x release line has been unsupported since July 2016, and the Node.\+js 4.\+x release line reaches its End of Life in April 2018 (→ \href{https://github.com/nodejs/Release\#release-schedule}{\texttt{ Schedule}}). This means that these versions of Node.\+js will {\itshape not} receive any updates, even in case of security issues, so using these release lines should be avoided, if at all possible.

What you would do in this case is to convert all {\ttfamily new Buffer()} or {\ttfamily Buffer()} calls to use {\ttfamily Buffer.\+alloc()} or {\ttfamily Buffer.\+from()}, in the following way\+:


\begin{DoxyItemize}
\item For {\ttfamily new Buffer(number)}, replace it with {\ttfamily Buffer.\+alloc(number)}.
\item For {\ttfamily new Buffer(string)} (or {\ttfamily new Buffer(string, encoding)}), replace it with {\ttfamily Buffer.\+from(string)} (or {\ttfamily Buffer.\+from(string, encoding)}).
\item For all other combinations of arguments (these are much rarer), also replace {\ttfamily new Buffer(...\+arguments)} with {\ttfamily Buffer.\+from(...\+arguments)}.
\end{DoxyItemize}

Note that {\ttfamily Buffer.\+alloc()} is also {\itshape faster} on the current Node.\+js versions than {\ttfamily new Buffer(size).fill(0)}, which is what you would otherwise need to ensure zero-\/filling.

Enabling eslint rule \href{https://eslint.org/docs/rules/no-buffer-constructor}{\texttt{ no-\/buffer-\/constructor}} or \href{https://github.com/mysticatea/eslint-plugin-node/blob/master/docs/rules/no-deprecated-api.md}{\texttt{ node/no-\/deprecated-\/api}} is recommended to avoid accidential unsafe Buffer API usage.

There is also a \href{https://github.com/joyeecheung/node-dep-codemod\#dep005}{\texttt{ JSCodeshift codemod}} for automatically migrating Buffer constructors to {\ttfamily Buffer.\+alloc()} or {\ttfamily Buffer.\+from()}. Note that it currently only works with cases where the arguments are literals or where the constructor is invoked with two arguments.

{\itshape If you currently support those older Node.\+js versions and dropping them would be a semver-\/major change for you, or if you support older branches of your packages, consider using \href{\#variant-2}{\texttt{ Variant 2}} or \href{\#variant-3}{\texttt{ Variant 3}} on older branches, so people using those older branches will also receive the fix. That way, you will eradicate potential issues caused by unguarded Buffer API usage and your users will not observe a runtime deprecation warning when running your code on Node.\+js 10.}

\label{_variant-2}%
 \hypertarget{md_sfcode_node_modules_safer_buffer_Porting_Buffer_autotoc_md26089}{}\doxysection{Variant 2\+: Use a polyfill}\label{md_sfcode_node_modules_safer_buffer_Porting_Buffer_autotoc_md26089}
Utilize \href{https://www.npmjs.com/package/safer-buffer}{\texttt{ safer-\/buffer}} as a polyfill to support older Node.\+js versions.

You would take exacly the same steps as in \href{\#variant-1}{\texttt{ Variant 1}}, but with a polyfill `const Buffer = require(\textquotesingle{}safer-\/buffer').Buffer{\ttfamily in all files where you use the new}Buffer\`{} api.

Make sure that you do not use old {\ttfamily new Buffer} API — in any files where the line above is added, using old {\ttfamily new Buffer()} API will {\itshape throw}. It will be easy to notice that in CI, though.

Alternatively, you could use \href{https://www.npmjs.com/package/buffer-from}{\texttt{ buffer-\/from}} and/or \href{https://www.npmjs.com/package/buffer-alloc}{\texttt{ buffer-\/alloc}} \href{https://ponyfill.com/}{\texttt{ ponyfills}} — those are great, the only downsides being 4 deps in the tree and slightly more code changes to migrate off them (as you would be using e.\+g. {\ttfamily Buffer.\+from} under a different name). If you need only {\ttfamily Buffer.\+from} polyfilled — {\ttfamily buffer-\/from} alone which comes with no extra dependencies.

{\itshape Alternatively, you could use \href{https://www.npmjs.com/package/safe-buffer}{\texttt{ safe-\/buffer}} — it also provides a polyfill, but takes a different approach which has \href{https://github.com/chalker/safer-buffer\#why-not-safe-buffer}{\texttt{ it\textquotesingle{}s drawbacks}}. It will allow you to also use the older {\ttfamily new Buffer()} API in your code, though — but that\textquotesingle{}s arguably a benefit, as it is problematic, can cause issues in your code, and will start emitting runtime deprecation warnings starting with Node.\+js 10.}

Note that in either case, it is important that you also remove all calls to the old Buffer API manually — just throwing in {\ttfamily safe-\/buffer} doesn\textquotesingle{}t fix the problem by itself, it just provides a polyfill for the new API. I have seen people doing that mistake.

Enabling eslint rule \href{https://eslint.org/docs/rules/no-buffer-constructor}{\texttt{ no-\/buffer-\/constructor}} or \href{https://github.com/mysticatea/eslint-plugin-node/blob/master/docs/rules/no-deprecated-api.md}{\texttt{ node/no-\/deprecated-\/api}} is recommended.

{\itshape Don\textquotesingle{}t forget to drop the polyfill usage once you drop support for Node.\+js $<$ 4.\+5.\+0.}

\label{_variant-3}%
 \hypertarget{md_sfcode_node_modules_safer_buffer_Porting_Buffer_autotoc_md26090}{}\doxysection{Variant 3 — manual detection, with safeguards}\label{md_sfcode_node_modules_safer_buffer_Porting_Buffer_autotoc_md26090}
This is useful if you create Buffer instances in only a few places (e.\+g. one), or you have your own wrapper around them.\hypertarget{md_sfcode_node_modules_safer_buffer_Porting_Buffer_autotoc_md26091}{}\doxysubsection{Buffer(0)}\label{md_sfcode_node_modules_safer_buffer_Porting_Buffer_autotoc_md26091}
This special case for creating empty buffers can be safely replaced with {\ttfamily Buffer.\+concat(\mbox{[}$\,$\mbox{]})}, which returns the same result all the way down to Node.\+js 0.\+8.\+x.\hypertarget{md_sfcode_node_modules_safer_buffer_Porting_Buffer_autotoc_md26092}{}\doxysubsection{Buffer(not\+Number)}\label{md_sfcode_node_modules_safer_buffer_Porting_Buffer_autotoc_md26092}
Before\+:


\begin{DoxyCode}{0}
\DoxyCodeLine{var buf = new Buffer(notNumber, encoding); }

\end{DoxyCode}


After\+:


\begin{DoxyCode}{0}
\DoxyCodeLine{var buf;}
\DoxyCodeLine{if (Buffer.from \&\& Buffer.from !== Uint8Array.from) \{}
\DoxyCodeLine{  buf = Buffer.from(notNumber, encoding);}
\DoxyCodeLine{\} else \{}
\DoxyCodeLine{  if (typeof notNumber === 'number')}
\DoxyCodeLine{    throw new Error('The "{}size"{} argument must be of type number.');}
\DoxyCodeLine{  buf = new Buffer(notNumber, encoding);}
\DoxyCodeLine{\} }

\end{DoxyCode}


{\ttfamily encoding} is optional.

Note that the {\ttfamily typeof not\+Number} before {\ttfamily new Buffer} is required (for cases when {\ttfamily not\+Number} argument is not hard-\/coded) and {\itshape is not caused by the deprecation of Buffer constructor} — it\textquotesingle{}s exactly {\itshape why} the Buffer constructor is deprecated. Ecosystem packages lacking this type-\/check caused numereous security issues — situations when unsanitized user input could end up in the {\ttfamily Buffer(arg)} create problems ranging from DoS to leaking sensitive information to the attacker from the process memory.

When {\ttfamily not\+Number} argument is hardcoded (e.\+g. literal {\ttfamily \char`\"{}abc\char`\"{}} or {\ttfamily \mbox{[}0,1,2\mbox{]}}), the {\ttfamily typeof} check can be omitted.

Also note that using Type\+Script does not fix this problem for you — when libs written in {\ttfamily Type\+Script} are used from JS, or when user input ends up there — it behaves exactly as pure JS, as all type checks are translation-\/time only and are not present in the actual JS code which TS compiles to.\hypertarget{md_sfcode_node_modules_safer_buffer_Porting_Buffer_autotoc_md26093}{}\doxysubsection{Buffer(number)}\label{md_sfcode_node_modules_safer_buffer_Porting_Buffer_autotoc_md26093}
For Node.\+js 0.\+10.\+x (and below) support\+:


\begin{DoxyCode}{0}
\DoxyCodeLine{var buf;}
\DoxyCodeLine{if (Buffer.alloc) \{}
\DoxyCodeLine{  buf = Buffer.alloc(number);}
\DoxyCodeLine{\} else \{}
\DoxyCodeLine{  buf = new Buffer(number);}
\DoxyCodeLine{  buf.fill(0);}
\DoxyCodeLine{\} }

\end{DoxyCode}


Otherwise (Node.\+js ≥ 0.\+12.\+x)\+:


\begin{DoxyCode}{0}
\DoxyCodeLine{const buf = Buffer.alloc ? Buffer.alloc(number) : new Buffer(number).fill(0); }

\end{DoxyCode}
\hypertarget{md_sfcode_node_modules_safer_buffer_Porting_Buffer_autotoc_md26094}{}\doxysection{Regarding Buffer.\+alloc\+Unsafe}\label{md_sfcode_node_modules_safer_buffer_Porting_Buffer_autotoc_md26094}
Be extra cautious when using {\ttfamily Buffer.\+alloc\+Unsafe}\+:
\begin{DoxyItemize}
\item Don\textquotesingle{}t use it if you don\textquotesingle{}t have a good reason to
\begin{DoxyItemize}
\item e.\+g. you probably won\textquotesingle{}t ever see a performance difference for small buffers, in fact, those might be even faster with {\ttfamily Buffer.\+alloc()},
\item if your code is not in the hot code path — you also probably won\textquotesingle{}t notice a difference,
\item keep in mind that zero-\/filling minimizes the potential risks.
\end{DoxyItemize}
\item If you use it, make sure that you never return the buffer in a partially-\/filled state,
\begin{DoxyItemize}
\item if you are writing to it sequentially — always truncate it to the actuall written length
\end{DoxyItemize}
\end{DoxyItemize}

Errors in handling buffers allocated with {\ttfamily Buffer.\+alloc\+Unsafe} could result in various issues, ranged from undefined behaviour of your code to sensitive data (user input, passwords, certs) leaking to the remote attacker.

{\itshape Note that the same applies to {\ttfamily new Buffer} usage without zero-\/filling, depending on the Node.\+js version (and lacking type checks also adds DoS to the list of potential problems).}

\label{_faq}%
 \hypertarget{md_sfcode_node_modules_safer_buffer_Porting_Buffer_autotoc_md26095}{}\doxysection{FAQ}\label{md_sfcode_node_modules_safer_buffer_Porting_Buffer_autotoc_md26095}
\label{_design-flaws}%
 \hypertarget{md_sfcode_node_modules_safer_buffer_Porting_Buffer_autotoc_md26096}{}\doxysubsection{What is wrong with the $<$tt$>$\+Buffer$<$/tt$>$ constructor?}\label{md_sfcode_node_modules_safer_buffer_Porting_Buffer_autotoc_md26096}
The {\ttfamily Buffer} constructor could be used to create a buffer in many different ways\+:


\begin{DoxyItemize}
\item {\ttfamily new Buffer(42)} creates a {\ttfamily Buffer} of 42 bytes. Before Node.\+js 8, this buffer contained {\itshape arbitrary memory} for performance reasons, which could include anything ranging from program source code to passwords and encryption keys.
\item `new Buffer(\textquotesingle{}abc'){\ttfamily creates a}Buffer{\ttfamily that contains the UTF-\/8-\/encoded version of the string}\textquotesingle{}abc\textquotesingle{}{\ttfamily . A second argument could specify another encoding\+: For example, }new Buffer(string, \textquotesingle{}base64\textquotesingle{})\`{} could be used to convert a Base64 string into the original sequence of bytes that it represents.
\item There are several other combinations of arguments.
\end{DoxyItemize}

This meant that, in code like {\ttfamily var buffer = new Buffer(foo);}, {\itshape it is not possible to tell what exactly the contents of the generated buffer are} without knowing the type of {\ttfamily foo}.

Sometimes, the value of {\ttfamily foo} comes from an external source. For example, this function could be exposed as a service on a web server, converting a UTF-\/8 string into its Base64 form\+:


\begin{DoxyCode}{0}
\DoxyCodeLine{function stringToBase64(req, res) \{}
\DoxyCodeLine{  // The request body should have the format of `\{ string: 'foobar' \}`}
\DoxyCodeLine{  const rawBytes = new Buffer(req.body.string)}
\DoxyCodeLine{  const encoded = rawBytes.toString('base64')}
\DoxyCodeLine{  res.end(\{ encoded: encoded \})}
\DoxyCodeLine{\} }

\end{DoxyCode}


Note that this code does {\itshape not} validate the type of {\ttfamily req.\+body.\+string}\+:


\begin{DoxyItemize}
\item {\ttfamily req.\+body.\+string} is expected to be a string. If this is the case, all goes well.
\item {\ttfamily req.\+body.\+string} is controlled by the client that sends the request.
\item If {\ttfamily req.\+body.\+string} is the {\itshape number} {\ttfamily 50}, the {\ttfamily raw\+Bytes} would be 50 bytes\+:
\begin{DoxyItemize}
\item Before Node.\+js 8, the content would be uninitialized
\item After Node.\+js 8, the content would be {\ttfamily 50} bytes with the value {\ttfamily 0}
\end{DoxyItemize}
\end{DoxyItemize}

Because of the missing type check, an attacker could intentionally send a number as part of the request. Using this, they can either\+:


\begin{DoxyItemize}
\item Read uninitialized memory. This {\bfseries{will}} leak passwords, encryption keys and other kinds of sensitive information. (Information leak)
\item Force the program to allocate a large amount of memory. For example, when specifying {\ttfamily 500000000} as the input value, each request will allocate 500MB of memory. This can be used to either exhaust the memory available of a program completely and make it crash, or slow it down significantly. (Denial of Service)
\end{DoxyItemize}

Both of these scenarios are considered serious security issues in a real-\/world web server context.

when using {\ttfamily Buffer.\+from(req.\+body.\+string)} instead, passing a number will always throw an exception instead, giving a controlled behaviour that can always be handled by the program.

\label{_ecosystem-usage}%
 \hypertarget{md_sfcode_node_modules_safer_buffer_Porting_Buffer_autotoc_md26097}{}\doxysubsection{The $<$tt$>$\+Buffer()$<$/tt$>$ constructor has been deprecated for a while. Is this really an issue?}\label{md_sfcode_node_modules_safer_buffer_Porting_Buffer_autotoc_md26097}
Surveys of code in the {\ttfamily npm} ecosystem have shown that the {\ttfamily Buffer()} constructor is still widely used. This includes new code, and overall usage of such code has actually been {\itshape increasing}. 