From d945c6f5e6f61b6e289ac7da6834c18f1b677b0f Mon Sep 17 00:00:00 2001 From: practicalswift Date: Wed, 11 Dec 2019 11:00:52 +0000 Subject: util: Don't allow base58-decoding of std::string:s containing non-base58 characters --- src/base58.cpp | 7 +++++++ src/util/strencodings.cpp | 3 ++- src/util/string.h | 11 +++++++++++ 3 files changed, 20 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/base58.cpp b/src/base58.cpp index a0149fb641..17d3f86ba8 100644 --- a/src/base58.cpp +++ b/src/base58.cpp @@ -7,6 +7,7 @@ #include #include #include +#include #include #include @@ -130,6 +131,9 @@ std::string EncodeBase58(const std::vector& vch) bool DecodeBase58(const std::string& str, std::vector& vchRet, int max_ret_len) { + if (!ValidAsCString(str)) { + return false; + } return DecodeBase58(str.c_str(), vchRet, max_ret_len); } @@ -161,5 +165,8 @@ bool DecodeBase58Check(const char* psz, std::vector& vchRet, int bool DecodeBase58Check(const std::string& str, std::vector& vchRet, int max_ret) { + if (!ValidAsCString(str)) { + return false; + } return DecodeBase58Check(str.c_str(), vchRet, max_ret); } diff --git a/src/util/strencodings.cpp b/src/util/strencodings.cpp index 46042f5634..8f2d05f03b 100644 --- a/src/util/strencodings.cpp +++ b/src/util/strencodings.cpp @@ -4,6 +4,7 @@ // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include +#include #include @@ -269,7 +270,7 @@ NODISCARD static bool ParsePrechecks(const std::string& str) return false; if (str.size() >= 1 && (IsSpace(str[0]) || IsSpace(str[str.size()-1]))) // No padding allowed return false; - if (str.size() != strlen(str.c_str())) // No embedded NUL characters allowed + if (!ValidAsCString(str)) // No embedded NUL characters allowed return false; return true; } diff --git a/src/util/string.h b/src/util/string.h index 76a83a4949..c6fa08e5b3 100644 --- a/src/util/string.h +++ b/src/util/string.h @@ -5,6 +5,9 @@ #ifndef BITCOIN_UTIL_STRING_H #define BITCOIN_UTIL_STRING_H +#include + +#include #include #include @@ -31,4 +34,12 @@ inline std::string Join(const std::vector& list, const std::string& return Join(list, separator, [](const std::string& i) { return i; }); } +/** + * Check if a string does not contain any embedded NUL (\0) characters + */ +NODISCARD inline bool ValidAsCString(const std::string& str) noexcept +{ + return str.size() == strlen(str.c_str()); +} + #endif // BITCOIN_UTIL_STRENCODINGS_H -- cgit v1.2.3