add sanitize_for_logging() to stringfunc
authorGerd von Egidy <gerd.von.egidy@intra2net.com>
Wed, 16 Dec 2015 09:57:43 +0000 (10:57 +0100)
committerGerd von Egidy <gerd.von.egidy@intra2net.com>
Wed, 16 Dec 2015 09:57:43 +0000 (10:57 +0100)
src/stringfunc.cpp
src/stringfunc.hxx
test/stringfunc.cpp

index 6bfd860..338e3b1 100644 (file)
@@ -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)
 {
index b91a18f..4b33b6a 100644 (file)
@@ -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);
index f1404a6..62c9eb3 100644 (file)
@@ -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()