Skip to content

Commit

Permalink
buffer: fix atob input validation
Browse files Browse the repository at this point in the history
Fixes: #42530

PR-URL: #42539
Reviewed-By: Michaël Zasso <targos@protonmail.com>
Reviewed-By: Rich Trott <rtrott@gmail.com>
Reviewed-By: Mestery <mestery@protonmail.com>
Reviewed-By: Akhil Marsonya <akhil.marsonya27@gmail.com>
  • Loading branch information
aduh95 authored and targos committed Jul 11, 2022
1 parent 5688f8c commit 806d87a
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 3 deletions.
26 changes: 23 additions & 3 deletions lib/buffer.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,10 @@

const {
Array,
ArrayFrom,
ArrayIsArray,
ArrayPrototypeForEach,
ArrayPrototypeIncludes,
MathFloor,
MathMin,
MathTrunc,
Expand Down Expand Up @@ -1231,8 +1233,25 @@ function btoa(input) {
return buf.toString('base64');
}

const kBase64Digits =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
// Refs: https://infra.spec.whatwg.org/#forgiving-base64-decode
const kForgivingBase64AllowedChars = [
// ASCII whitespace
// Refs: https://infra.spec.whatwg.org/#ascii-whitespace
0x09, 0x0A, 0x0C, 0x0D, 0x20,

// Uppercase letters
...ArrayFrom({ length: 26 }, (_, i) => StringPrototypeCharCodeAt('A') + i),

// Lowercase letters
...ArrayFrom({ length: 26 }, (_, i) => StringPrototypeCharCodeAt('a') + i),

// Decimal digits
...ArrayFrom({ length: 10 }, (_, i) => StringPrototypeCharCodeAt('0') + i),

0x2B, // +
0x2F, // /
0x3D, // =
];

function atob(input) {
// The implementation here has not been performance optimized in any way and
Expand All @@ -1243,7 +1262,8 @@ function atob(input) {
}
input = `${input}`;
for (let n = 0; n < input.length; n++) {
if (!kBase64Digits.includes(input[n]))
if (!ArrayPrototypeIncludes(kForgivingBase64AllowedChars,
StringPrototypeCharCodeAt(input, n)))
throw lazyDOMException('Invalid character', 'InvalidCharacterError');
}
return Buffer.from(input, 'base64').toString('latin1');
Expand Down
3 changes: 3 additions & 0 deletions test/parallel/test-btoa-atob.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,6 @@ strictEqual(globalThis.btoa, buffer.btoa);
// Throws type error on no argument passed
throws(() => buffer.atob(), /TypeError/);
throws(() => buffer.btoa(), /TypeError/);

strictEqual(atob(' '), '');
strictEqual(atob(' YW\tJ\njZA=\r= '), 'abcd');

0 comments on commit 806d87a

Please sign in to comment.