From d7820a1250070f3640246ae497e049bee0b3516f Mon Sep 17 00:00:00 2001 From: "Wladimir J. van der Laan" Date: Thu, 10 Oct 2019 13:25:08 +0200 Subject: util: Filter control characters out of log messages Belts and suspenders: make sure outgoing log messages don't contain potentially suspicious characters, such as terminal control codes. This escapes control characters except newline ('\n') in C syntax. It escapes instead of removes them to still allow for troubleshooting issues where they accidentally end up in strings. --- src/logging.cpp | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) (limited to 'src/logging.cpp') diff --git a/src/logging.cpp b/src/logging.cpp index dc2d130a2a..60ab486198 100644 --- a/src/logging.cpp +++ b/src/logging.cpp @@ -224,10 +224,32 @@ std::string BCLog::Logger::LogTimestampStr(const std::string& str) return strStamped; } +namespace BCLog { + /** Belts and suspenders: make sure outgoing log messages don't contain + * potentially suspicious characters, such as terminal control codes. + * + * This escapes control characters except newline ('\n') in C syntax. + * It escapes instead of removes them to still allow for troubleshooting + * issues where they accidentally end up in strings. + */ + std::string LogEscapeMessage(const std::string& str) { + std::string ret; + for (char ch_in : str) { + uint8_t ch = (uint8_t)ch_in; + if ((ch >= 32 || ch == '\n') && ch != '\x7f') { + ret += ch_in; + } else { + ret += strprintf("\\x%02x", ch); + } + } + return ret; + } +} + void BCLog::Logger::LogPrintStr(const std::string& str) { std::lock_guard scoped_lock(m_cs); - std::string str_prefixed = str; + std::string str_prefixed = LogEscapeMessage(str); if (m_log_threadnames && m_started_new_line) { str_prefixed.insert(0, "[" + util::ThreadGetInternalName() + "] "); -- cgit v1.2.3