Skip to content

Commit

Permalink
util: Don't allow base58-decoding of std::string:s containing non-bas…
Browse files Browse the repository at this point in the history
…e58 characters
  • Loading branch information
practicalswift authored and furszy committed Jun 28, 2021
1 parent 70c480c commit 0247f6f
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 1 deletion.
7 changes: 7 additions & 0 deletions src/base58.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
#include "base58.h"

#include "hash.h"
#include "util/string.h"

#include "uint256.h"

Expand Down Expand Up @@ -131,6 +132,9 @@ std::string EncodeBase58(const std::vector<unsigned char>& vch)

bool DecodeBase58(const std::string& str, std::vector<unsigned char>& vchRet, int max_ret_len)
{
if (!ValidAsCString(str)) {
return false;
}
return DecodeBase58(str.c_str(), vchRet, max_ret_len);
}

Expand Down Expand Up @@ -162,5 +166,8 @@ bool DecodeBase58Check(const char* psz, std::vector<unsigned char>& vchRet, int

bool DecodeBase58Check(const std::string& str, std::vector<unsigned char>& vchRet, int max_ret)
{
if (!ValidAsCString(str)) {
return false;
}
return DecodeBase58Check(str.c_str(), vchRet, max_ret);
}
9 changes: 9 additions & 0 deletions src/util/string.h
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
#ifndef BITCOIN_UTIL_STRING_H
#define BITCOIN_UTIL_STRING_H

#include <cstring>
#include <functional>
#include <string>
#include <vector>
Expand Down Expand Up @@ -32,4 +33,12 @@ inline std::string Join(const std::vector<std::string>& 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
*/
inline bool ValidAsCString(const std::string& str) noexcept
{
return str.size() == strlen(str.c_str());
}

#endif // BITCOIN_UTIL_STRENCODINGS_H
3 changes: 2 additions & 1 deletion src/utilstrencodings.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "utilstrencodings.h"
#include "util/string.h"

#include "tinyformat.h"

Expand Down Expand Up @@ -266,7 +267,7 @@ 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;
}
Expand Down

0 comments on commit 0247f6f

Please sign in to comment.