Skip to content

Commit c7306d1

Browse files
committed
Extend utils::string::toHexIfNeeded() to encode '"' and '\' characters optionally
1 parent 3b7ca3e commit c7306d1

File tree

2 files changed

+8
-25
lines changed

2 files changed

+8
-25
lines changed

src/utils/string.cc

Lines changed: 7 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -135,13 +135,18 @@ std::string string_to_hex(const std::string& input) {
135135
return output;
136136
}
137137

138-
139138
std::string toHexIfNeeded(const std::string &str) {
139+
return toHexIfNeeded(str, false);
140+
}
141+
142+
std::string toHexIfNeeded(const std::string &str, bool escape_spec) {
143+
// escape_spec: escape special chars or not
144+
// spec chars: '"' (quotation mark, ascii 34), '\' (backslash, ascii 92)
140145
std::stringstream res;
141146

142147
for (int i = 0; i < str.size(); i++) {
143148
int c = (unsigned char)str.at(i);
144-
if (c < 32 || c > 126) {
149+
if (c < 32 || c > 126 || (escape_spec == true && (c == 34 || c == 92))) {
145150
res << "\\x" << std::setw(2) << std::setfill('0') << std::hex << c;
146151
} else {
147152
res << str.at(i);
@@ -267,29 +272,6 @@ void replaceAll(std::string *str, const std::string& from,
267272
}
268273
}
269274

270-
std::string log_escape_hex(std::string s) {
271-
272-
std::string ret = "";
273-
char tchar[2];
274-
275-
for (std::string::size_type i = 0; i < s.size(); i++) {
276-
if ( (s[i] == '"')
277-
||(s[i] == '\\')
278-
||(s[i] <= 0x1f)
279-
||(s[i] >= 0x7f))
280-
{
281-
ret.append("\\x");
282-
c2x(s[i], (unsigned char*)tchar);
283-
ret.push_back(tchar[0]);
284-
ret.push_back(tchar[1]);
285-
}
286-
else {
287-
ret.push_back(s[i]);
288-
}
289-
}
290-
return ret;
291-
}
292-
293275
} // namespace string
294276
} // namespace utils
295277
} // namespace modsecurity

src/utils/string.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,7 @@ std::string limitTo(int amount, const std::string &str);
6262
std::string removeBracketsIfNeeded(std::string a);
6363
std::string string_to_hex(const std::string& input);
6464
std::string toHexIfNeeded(const std::string &str);
65+
std::string toHexIfNeeded(const std::string &str, bool escape_spec);
6566
std::string tolower(std::string str);
6667
std::string toupper(std::string str);
6768
std::vector<std::string> ssplit(std::string str, char delimiter);

0 commit comments

Comments
 (0)