Skip to content

Commit d945c6f

Browse files
util: Don't allow base58-decoding of std::string:s containing non-base58 characters
1 parent ff7a999 commit d945c6f

File tree

3 files changed

+20
-1
lines changed

3 files changed

+20
-1
lines changed

src/base58.cpp

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
#include <hash.h>
88
#include <uint256.h>
99
#include <util/strencodings.h>
10+
#include <util/string.h>
1011

1112
#include <assert.h>
1213
#include <string.h>
@@ -130,6 +131,9 @@ std::string EncodeBase58(const std::vector<unsigned char>& vch)
130131

131132
bool DecodeBase58(const std::string& str, std::vector<unsigned char>& vchRet, int max_ret_len)
132133
{
134+
if (!ValidAsCString(str)) {
135+
return false;
136+
}
133137
return DecodeBase58(str.c_str(), vchRet, max_ret_len);
134138
}
135139

@@ -161,5 +165,8 @@ bool DecodeBase58Check(const char* psz, std::vector<unsigned char>& vchRet, int
161165

162166
bool DecodeBase58Check(const std::string& str, std::vector<unsigned char>& vchRet, int max_ret)
163167
{
168+
if (!ValidAsCString(str)) {
169+
return false;
170+
}
164171
return DecodeBase58Check(str.c_str(), vchRet, max_ret);
165172
}

src/util/strencodings.cpp

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
55

66
#include <util/strencodings.h>
7+
#include <util/string.h>
78

89
#include <tinyformat.h>
910

@@ -269,7 +270,7 @@ NODISCARD static bool ParsePrechecks(const std::string& str)
269270
return false;
270271
if (str.size() >= 1 && (IsSpace(str[0]) || IsSpace(str[str.size()-1]))) // No padding allowed
271272
return false;
272-
if (str.size() != strlen(str.c_str())) // No embedded NUL characters allowed
273+
if (!ValidAsCString(str)) // No embedded NUL characters allowed
273274
return false;
274275
return true;
275276
}

src/util/string.h

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,9 @@
55
#ifndef BITCOIN_UTIL_STRING_H
66
#define BITCOIN_UTIL_STRING_H
77

8+
#include <attributes.h>
9+
10+
#include <cstring>
811
#include <string>
912
#include <vector>
1013

@@ -31,4 +34,12 @@ inline std::string Join(const std::vector<std::string>& list, const std::string&
3134
return Join(list, separator, [](const std::string& i) { return i; });
3235
}
3336

37+
/**
38+
* Check if a string does not contain any embedded NUL (\0) characters
39+
*/
40+
NODISCARD inline bool ValidAsCString(const std::string& str) noexcept
41+
{
42+
return str.size() == strlen(str.c_str());
43+
}
44+
3445
#endif // BITCOIN_UTIL_STRENCODINGS_H

0 commit comments

Comments
 (0)