From: Gerd von Egidy Date: Wed, 16 Dec 2015 09:57:43 +0000 (+0100) Subject: add sanitize_for_logging() to stringfunc X-Git-Tag: v2.8~20 X-Git-Url: http://developer.intra2net.com/git/?a=commitdiff_plain;h=b953bf36f2b33f7b9a3e937a86a8ad2375755dbb;p=libi2ncommon add sanitize_for_logging() to stringfunc --- diff --git a/src/stringfunc.cpp b/src/stringfunc.cpp index 6bfd860..338e3b1 100644 --- a/src/stringfunc.cpp +++ b/src/stringfunc.cpp @@ -909,6 +909,28 @@ bool replace_all(string &base, const string &ist, const string &soll) return found_ist; } +/** + * @brief replaces all characters that could be problematic or impose a security risk when being logged + * @param str the original string + * @param replace_with the character to replace the unsafe chars with + * @return a string that is safe to send to syslog or other logfiles + * + * All chars between 0x20 (space) and 0x7E (~) (including) are considered safe for logging. + * See e.g. RFC 5424, section 8.2 or the posix character class "printable". + * This eliminates all possible problems with NUL, control characters, 8 bit chars, UTF8. + * + */ +std::string sanitize_for_logging(const std::string &str, const char replace_with) +{ + std::string output=str; + + for (std::string::size_type p=0; p < output.size(); p++) + if (output[p] < 0x20 || output[p] > 0x7E) + output[p]=replace_with; + + return output; +} + #if 0 string to_lower(const string &src) { diff --git a/src/stringfunc.hxx b/src/stringfunc.hxx index b91a18f..4b33b6a 100644 --- a/src/stringfunc.hxx +++ b/src/stringfunc.hxx @@ -243,6 +243,8 @@ std::string smart_html_entities(const std::string &input); std::string html_entities(std::string str); std::string html_entities_to_console(std::string str); +std::string sanitize_for_logging(const std::string &str, const char replace_with='?'); + std::string escape(const std::string &s); std::string descape(const std::string &s, int startpos, int &endpos); diff --git a/test/stringfunc.cpp b/test/stringfunc.cpp index f1404a6..62c9eb3 100644 --- a/test/stringfunc.cpp +++ b/test/stringfunc.cpp @@ -580,4 +580,29 @@ BOOST_AUTO_TEST_CASE(HexConversion) BOOST_REQUIRE_THROW( convert_hex_to_binary("01 kein hex"), std::runtime_error); } // eo HexConversion() +BOOST_AUTO_TEST_CASE(sanitize_for_logging1) +{ + string output = sanitize_for_logging("normaler string ohne aerger"); + + BOOST_CHECK_EQUAL(string("normaler string ohne aerger"), output); +} + +BOOST_AUTO_TEST_CASE(sanitize_for_logging2) +{ + string to_test="fiese"; + to_test.push_back(0); + to_test+="null"; + + string output = sanitize_for_logging(to_test); + + BOOST_CHECK_EQUAL(string("fiese?null"), output); +} + +BOOST_AUTO_TEST_CASE(sanitize_for_logging3) +{ + string output = sanitize_for_logging("läuter ümlaute utf8"); + + BOOST_CHECK_EQUAL(string("l??uter ??mlaute utf8"), output); +} + BOOST_AUTO_TEST_SUITE_END()