--- a/common/json-schema-to-grammar.cpp +++ b/common/json-schema-to-grammar.cpp @@ -343,13 +343,15 @@ private: rules.push_back(visit(alt_schemas[i], name + (name.empty() ? "alternative-" : "-") + std::to_string(i))); } return string_join(rules, " | "); } std::string _visit_pattern(const std::string & pattern, const std::string & name) { - if (!(pattern.front() == '^' && pattern.back() == '$')) { + // RADIANCE: front()/back() on an empty string is UB, and `pattern` is client data straight + // off the wire. The size test has to come first. + if (pattern.size() < 2 || !(pattern.front() == '^' && pattern.back() == '$')) { _errors.push_back("Pattern must start with '^' and end with '$'"); return ""; } std::string sub_pattern = pattern.substr(1, pattern.length() - 2); std::unordered_map sub_rule_ids; @@ -407,12 +409,18 @@ private: results.push_back(to_rule(item)); } return std::make_pair(string_join(results, " "), false); }; while (i < length) { + // RADIANCE: every arm below must consume at least one byte. The literal arm does not when + // it meets a byte that is in NON_LITERAL_SET but that no arm above claims -- a + // stray ']' or '}' -- so it breaks out with `literal` empty, nothing is pushed, + // and the loop reconsiders the same byte forever. `pattern` is client data, so + // that is a one-string denial of service. Checked at the bottom of the body. + const size_t progress_at = i; char c = sub_pattern[i]; if (c == '.') { seq.emplace_back(get_dot(), false); i++; } else if (c == '(') { i++; @@ -462,12 +470,17 @@ private: i++; seq.emplace_back(square_brackets, false); } else if (c == '|') { seq.emplace_back("|", false); i++; } else if (c == '*' || c == '+' || c == '?') { + if (seq.empty()) { + // RADIANCE: a leading quantifier, "^*$". back() on an empty vector is UB. + _errors.push_back("Quantifier with nothing to repeat"); + break; + } seq.back() = std::make_pair(to_rule(seq.back()) + c, false); i++; } else if (c == '{') { std::string curly_brackets = std::string(1, c); i++; while (i < length && sub_pattern[i] != '}') { @@ -496,12 +509,17 @@ private: } } } catch (const std::invalid_argument & e) { _errors.push_back("Invalid number in curly brackets"); return std::make_pair("", false); } + if (seq.empty()) { + // RADIANCE: a leading "{n,m}" has nothing before it to repeat; back() would be UB. + _errors.push_back("Quantifier with nothing to repeat"); + break; + } auto &last = seq.back(); auto &sub = last.first; auto sub_is_literal = last.second; if (!sub_is_literal) { std::string & sub_id = sub_rule_ids[sub]; @@ -545,12 +563,16 @@ private: } } if (!literal.empty()) { seq.emplace_back(literal, true); } } + if (i == progress_at) { + _errors.push_back("Unsupported pattern syntax"); + break; + } } return join_seq(); }; return _add_rule(name, "\"\\\"\" (" + to_rule(transform()) + ") \"\\\"\" space"); }