Extend utils::string::toHexIfNeeded() to encode '"' and '\' characters optionally

This commit is contained in:
Ervin Hegedüs 2023-01-17 20:57:03 +01:00
parent 3b7ca3e44c
commit c7306d174a
2 changed files with 8 additions and 25 deletions

View File

@ -135,13 +135,18 @@ std::string string_to_hex(const std::string& input) {
return output;
}
std::string toHexIfNeeded(const std::string &str) {
return toHexIfNeeded(str, false);
}
std::string toHexIfNeeded(const std::string &str, bool escape_spec) {
// escape_spec: escape special chars or not
// spec chars: '"' (quotation mark, ascii 34), '\' (backslash, ascii 92)
std::stringstream res;
for (int i = 0; i < str.size(); i++) {
int c = (unsigned char)str.at(i);
if (c < 32 || c > 126) {
if (c < 32 || c > 126 || (escape_spec == true && (c == 34 || c == 92))) {
res << "\\x" << std::setw(2) << std::setfill('0') << std::hex << c;
} else {
res << str.at(i);
@ -267,29 +272,6 @@ void replaceAll(std::string *str, const std::string& from,
}
}
std::string log_escape_hex(std::string s) {
std::string ret = "";
char tchar[2];
for (std::string::size_type i = 0; i < s.size(); i++) {
if ( (s[i] == '"')
||(s[i] == '\\')
||(s[i] <= 0x1f)
||(s[i] >= 0x7f))
{
ret.append("\\x");
c2x(s[i], (unsigned char*)tchar);
ret.push_back(tchar[0]);
ret.push_back(tchar[1]);
}
else {
ret.push_back(s[i]);
}
}
return ret;
}
} // namespace string
} // namespace utils
} // namespace modsecurity

View File

@ -62,6 +62,7 @@ std::string limitTo(int amount, const std::string &str);
std::string removeBracketsIfNeeded(std::string a);
std::string string_to_hex(const std::string& input);
std::string toHexIfNeeded(const std::string &str);
std::string toHexIfNeeded(const std::string &str, bool escape_spec);
std::string tolower(std::string str);
std::string toupper(std::string str);
std::vector<std::string> ssplit(std::string str, char delimiter);