fix(base64): properly handle embedded NULLs when decoding (#28349)

This commit is contained in:
Gregory Anders
2024-04-15 11:06:54 -05:00
committed by GitHub
parent 57adf8c6e0
commit 533e01a75b
3 changed files with 15 additions and 5 deletions

View File

@ -132,12 +132,18 @@ char *base64_encode(const char *src, size_t src_len)
/// Decode a Base64 encoded string. /// Decode a Base64 encoded string.
/// ///
/// The returned string is NOT null-terminated, because the decoded string may
/// contain embedded NULLs. Use the output parameter out_lenp to determine the
/// length of the returned string.
///
/// @param src Base64 encoded string /// @param src Base64 encoded string
/// @param src_len Length of {src} /// @param src_len Length of {src}
/// @param [out] out_lenp Returns the length of the decoded string
/// @return Decoded string /// @return Decoded string
char *base64_decode(const char *src, size_t src_len) char *base64_decode(const char *src, size_t src_len, size_t *out_lenp)
{ {
assert(src != NULL); assert(src != NULL);
assert(out_lenp != NULL);
char *dest = NULL; char *dest = NULL;
@ -155,7 +161,7 @@ char *base64_decode(const char *src, size_t src_len)
const uint8_t *s = (const uint8_t *)src; const uint8_t *s = (const uint8_t *)src;
dest = xmalloc(out_len + 1); dest = xmalloc(out_len);
int acc = 0; int acc = 0;
int acc_len = 0; int acc_len = 0;
@ -203,7 +209,7 @@ char *base64_decode(const char *src, size_t src_len)
} }
} }
dest[out_len] = '\0'; *out_lenp = out_len;
return dest; return dest;
@ -212,5 +218,7 @@ invalid:
xfree((void *)dest); xfree((void *)dest);
} }
*out_lenp = 0;
return NULL; return NULL;
} }

View File

@ -45,12 +45,13 @@ static int nlua_base64_decode(lua_State *L)
size_t src_len = 0; size_t src_len = 0;
const char *src = lua_tolstring(L, 1, &src_len); const char *src = lua_tolstring(L, 1, &src_len);
const char *ret = base64_decode(src, src_len); size_t out_len = 0;
const char *ret = base64_decode(src, src_len, &out_len);
if (ret == NULL) { if (ret == NULL) {
return luaL_error(L, "Invalid input"); return luaL_error(L, "Invalid input");
} }
lua_pushstring(L, ret); lua_pushlstring(L, ret, out_len);
xfree((void *)ret); xfree((void *)ret);
return 1; return 1;

View File

@ -42,6 +42,7 @@ describe('vim.base64', function()
̦H̬̤̗̤͝e͜ ̜̥̝̻͍̟́w̕h̖̯͓o̝͙̖͎̱̮ ҉̺̙̞̟͈W̷̼̭a̺̪͍į͈͕̭͙̯̜t̶̼̮s̘͙͖̕ ̠̫̠B̻͍͙͉̳ͅe̵h̵̬͇̫͙i̹͓̳̳̮͎̫̕n͟d̴̪̜̖ ̰͉̩͇͙̲͞ͅT͖̼͓̪͢h͏͓̮̻e̬̝̟ͅ ̤̹̝W͙̞̝͔͇͝ͅa͏͓͔̹̼̣l̴͔̰̤̟͔ḽ̫.͕ ̦H̬̤̗̤͝e͜ ̜̥̝̻͍̟́w̕h̖̯͓o̝͙̖͎̱̮ ҉̺̙̞̟͈W̷̼̭a̺̪͍į͈͕̭͙̯̜t̶̼̮s̘͙͖̕ ̠̫̠B̻͍͙͉̳ͅe̵h̵̬͇̫͙i̹͓̳̳̮͎̫̕n͟d̴̪̜̖ ̰͉̩͇͙̲͞ͅT͖̼͓̪͢h͏͓̮̻e̬̝̟ͅ ̤̹̝W͙̞̝͔͇͝ͅa͏͓͔̹̼̣l̴͔̰̤̟͔ḽ̫.͕
Z̮̞̠͙͔ͅḀ̗̞͈̻̗Ḷ͙͎̯̹̞͓G̻O̭̗̮ Z̮̞̠͙͔ͅḀ̗̞͈̻̗Ḷ͙͎̯̹̞͓G̻O̭̗̮
]], ]],
'Hello\0world',
} }
for _, v in ipairs(values) do for _, v in ipairs(values) do