diff options
author | Lars Müller <34514239+appgurueu@users.noreply.github.com> | 2021-05-30 20:23:12 +0200 |
---|---|---|
committer | GitHub <noreply@github.com> | 2021-05-30 20:23:12 +0200 |
commit | 89f3991351185b365ccd10525e74d35d7bb2da46 (patch) | |
tree | e82a77c9f34bd9e34adfe16c6d1a1fbffd289c5f /src/util/base64.cpp | |
parent | 1bc753f655db4c7de030f2700361011e1c0278a5 (diff) | |
download | minetest-89f3991351185b365ccd10525e74d35d7bb2da46.tar.gz minetest-89f3991351185b365ccd10525e74d35d7bb2da46.tar.bz2 minetest-89f3991351185b365ccd10525e74d35d7bb2da46.zip |
Fix base64 validation and add unittests (#10515)
Implement proper padding character checks
Diffstat (limited to 'src/util/base64.cpp')
-rw-r--r-- | src/util/base64.cpp | 29 |
1 files changed, 25 insertions, 4 deletions
diff --git a/src/util/base64.cpp b/src/util/base64.cpp index 6e1584410..0c2455222 100644 --- a/src/util/base64.cpp +++ b/src/util/base64.cpp @@ -33,18 +33,39 @@ static const std::string base64_chars = "abcdefghijklmnopqrstuvwxyz" "0123456789+/"; +static const std::string base64_chars_padding_1 = "AEIMQUYcgkosw048"; +static const std::string base64_chars_padding_2 = "AQgw"; static inline bool is_base64(unsigned char c) { - return isalnum(c) || c == '+' || c == '/' || c == '='; + return (c >= '0' && c <= '9') + || (c >= 'A' && c <= 'Z') + || (c >= 'a' && c <= 'z') + || c == '+' || c == '/'; } bool base64_is_valid(std::string const& s) { - for (char i : s) - if (!is_base64(i)) + size_t i = 0; + for (; i < s.size(); ++i) + if (!is_base64(s[i])) + break; + unsigned char padding = 3 - ((i + 3) % 4); + if ((padding == 1 && base64_chars_padding_1.find(s[i - 1]) == std::string::npos) + || (padding == 2 && base64_chars_padding_2.find(s[i - 1]) == std::string::npos) + || padding == 3) + return false; + int actual_padding = s.size() - i; + // omission of padding characters is allowed + if (actual_padding == 0) + return true; + + // remaining characters (max. 2) may only be padding + for (; i < s.size(); ++i) + if (s[i] != '=') return false; - return true; + // number of padding characters needs to match + return padding == actual_padding; } std::string base64_encode(unsigned char const* bytes_to_encode, unsigned int in_len) { |