mirror of
https://github.com/luanti-org/luanti.git
synced 2025-08-01 17:38:41 +00:00
Sanitize formspec fields server-side (#14878)
This commit is contained in:
parent
ab7af5d15a
commit
c6ef5ab259
5 changed files with 99 additions and 5 deletions
|
@ -950,6 +950,53 @@ std::string sanitizeDirName(std::string_view str, std::string_view optional_pref
|
|||
return wide_to_utf8(safe_name);
|
||||
}
|
||||
|
||||
template <class F>
|
||||
void remove_indexed(std::string &s, F pred)
|
||||
{
|
||||
size_t j = 0;
|
||||
for (size_t i = 0; i < s.length();) {
|
||||
if (pred(s, i++))
|
||||
j++;
|
||||
if (i != j)
|
||||
s[j] = s[i];
|
||||
}
|
||||
s.resize(j);
|
||||
}
|
||||
|
||||
std::string sanitize_untrusted(std::string_view str, bool keep_escapes)
|
||||
{
|
||||
// truncate on NULL
|
||||
std::string s{str.substr(0, str.find('\0'))};
|
||||
|
||||
// remove control characters except tab, feed and escape
|
||||
s.erase(std::remove_if(s.begin(), s.end(), [] (unsigned char c) {
|
||||
return c < 9 || (c >= 13 && c < 27) || (c >= 28 && c < 32);
|
||||
}), s.end());
|
||||
|
||||
if (!keep_escapes) {
|
||||
s.erase(std::remove(s.begin(), s.end(), '\x1b'), s.end());
|
||||
return s;
|
||||
}
|
||||
// Note: Minetest escapes generally just look like \x1b# or \x1b(###)
|
||||
// where # is a single character and ### any number of characters.
|
||||
// Here we additionally assume that the first character in the sequence
|
||||
// is [A-Za-z], to enable us to filter foreign types of escapes that might
|
||||
// be unsafe e.g. ANSI escapes in a terminal.
|
||||
const auto &check = [] (char c) {
|
||||
return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z');
|
||||
};
|
||||
remove_indexed(s, [&check] (const std::string &s, size_t i) {
|
||||
if (s[i] != '\x1b')
|
||||
return true;
|
||||
if (i+1 >= s.length())
|
||||
return false;
|
||||
if (s[i+1] == '(')
|
||||
return i+2 < s.length() && check(s[i+2]); // long-form escape
|
||||
else
|
||||
return check(s[i+1]); // short-form escape
|
||||
});
|
||||
return s;
|
||||
}
|
||||
|
||||
void safe_print_string(std::ostream &os, std::string_view str)
|
||||
{
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue