Fix std/base64.decode out of bounds read (#23526)

inputLen may end up as 0 in the loop if the input string only includes
trailing characters. e.g. without the patch, decode(" ") would panic.

(cherry picked from commit 30cf570af9)
This commit is contained in:
bptato
2024-04-22 09:44:33 +02:00
committed by narimiran
parent 33817f2c30
commit 494b5486ba
2 changed files with 3 additions and 1 deletions

View File

@@ -244,7 +244,7 @@ proc decode*(s: string): string =
inputLen = s.len
inputEnds = 0
# strip trailing characters
while s[inputLen - 1] in {'\n', '\r', ' ', '='}:
while inputLen > 0 and s[inputLen - 1] in {'\n', '\r', ' ', '='}:
dec inputLen
# hot loop: read 4 characters at at time
inputEnds = inputLen - 4

View File

@@ -18,6 +18,8 @@ template main() =
doAssert encode("") == ""
doAssert decode("") == ""
doAssert decode(" ") == ""
const testInputExpandsTo76 = "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
const testInputExpands = "++++++++++++++++++++++++++++++"
const longText = """Man is distinguished, not only by his reason, but by this