Regular expression
datafield_regex
Adds a "Regex" field type to the Moodle Database (mod_data) activity. It works like a short-text field but validates submitted values against a teacher-defined regular expression, with case-sensitivity, partial-match, and custom (multilang) error-message options, before an entry is accepted.
The plugin's own attack surface is small and handled correctly: it defines no standalone endpoints and relies on mod/data/field.php and edit.php for require_login(), require_capability('mod/data:managetemplates') and confirm_sesskey(). Output is consistently escaped (p()/s()), the teacher-set error message is rendered through format_string(), advanced-search SQL is parameterised, and the Privacy API is implemented following the same pattern as core datafield plugins.
No finding is exploitable by a student or unauthenticated user, and no finding causes data loss or cross-user data exposure. The most notable item is that install/upgrade attempts to write the field icon into the Moodle code directory (dirroot) with no uninstall cleanup — an architectural violation, but one with a deterministic path, no user input, an admin-only trigger and graceful failure on production, so it is low severity. The remaining items are a masked =/== logic bug, an inaccurate case-sensitivity value in the privacy export, misleading copy-pasted SQL identifiers, and an informational ReDoS note that is well mitigated by PHP's PCRE backtracking limits and the teacher-level privilege required to author a pattern. With only low and informational findings and no security vulnerabilities, the code quality is high; the handful of low-severity nits keep it just short of exemplary.
Summary
datafield_regex adds a Regex field type to the Moodle Database (mod_data) activity. It behaves like a short-text field but validates each submitted value against a teacher-defined regular expression, with options for case-sensitivity, partial vs. whole-string matching, and a custom (multilang) error message.
Overall this is a well-written, well-maintained plugin. It correctly delegates authentication, capability enforcement (mod/data:managetemplates) and CSRF protection to core's mod/data/field.php and edit.php; escapes all output via p()/s()/format_string(); parameterises its advanced-search SQL; and implements the Privacy API in the same dual null_provider + datafield_provider pattern as core's datafield_text. It ships PHPUnit and Behat tests and a broad CI matrix.
Findings
No security vulnerabilities were found that are exploitable by students or unauthenticated users. The issues are low-severity code-quality/compliance items plus one informational note:
- Install/upgrade writes an icon into the core code tree (
dirroot) viasymlink()/copy(), with nodb/uninstall.phpcleanup. Deterministic path, admin-only, fails safely on production — a code-hygiene defect, not an exploit. =used instead of==in the constructor's guard, silently mutating$field->dataid; harmless in context but a real logic error.- Privacy export reads case-sensitivity from
param1(obsolete autolink) instead ofparam2, so the GDPR export always shows No. - Leftover
df_email_naming copied from the email datafield plugin (maintainability only). - Informational: teacher-supplied patterns run against user input (ReDoS), bounded by PHP's PCRE limits.
Findings
On every install and upgrade, the plugin calls \datafield_regex\install::copyicon(), which attempts to create a symlink (falling back to a copy) of the plugin's pix/icon.svg at mod/data/pix/field/icon.svg — a path inside $CFG->dirroot, the Moodle code directory.
Plugins must not write into the core code tree. The concerns here are:
- Architectural violation — the code directory is meant to be read-only and is not a place for a subplugin to deposit files. On a correctly configured production server the web/CLI user cannot write there, so the operation fails and the code prints a manual-copy instruction to the upgrade output.
- Orphaned artifact / no uninstall — when the write does succeed (developer installs, or any environment where
dirrootis writable), a symlink or file is left inmod/data/pix/field/that lives outside the plugin directory. There is nodb/uninstall.php, so removing the plugin leaves a dangling symlink or stale copy behind in core. - Unnecessary — the icon can be served directly from the plugin's own
pix/folder. The Create a field action bar in core already renders the type icon withimage_icon('icon', $fieldtype, 'datafield_'.$fieldtype), which resolves tomod/data/field/regex/pix/icon.svgwithout any copying.
Low risk. This is an architectural/code-quality violation rather than an exploitable vulnerability. There is no user-controlled input in the path, so there is no traversal or symlink-swap vector, and the operation only runs during admin install/upgrade. On production the write is denied by filesystem permissions and fails gracefully with an on-screen instruction. The realistic negative impacts are the orphaned symlink/copy left in the core tree (aggravated by the absence of db/uninstall.php) and reliance on a non-standard, fragile install step that is not needed once the icon is referenced from the plugin's own pix/ directory.
copyicon() is invoked from both xmldb_datafield_regex_install() (db/install.php) and xmldb_datafield_regex_upgrade() (db/upgrade.php), i.e. during admin-triggered plugin install/upgrade. Both the source ($target) and destination ($link) paths are derived exclusively from __DIR__; there is no request or user data anywhere in the path construction.
$link = implode(DIRECTORY_SEPARATOR, [__DIR__, '..', '..', '..', 'pix', 'field', 'icon.svg']);
if (!file_exists($link)) {
$target = implode(DIRECTORY_SEPARATOR, [__DIR__, '..', 'pix', 'icon.svg']);
echo 'Create symlink for regex icon... ';
if (!\symlink($target, $link)) {
echo 'failed' . PHP_EOL . 'Copy regex icon... ';
if (!\copy($target, $link)) {
Drop the copyicon() mechanism entirely and serve the icon from the plugin's own pix/ directory. The overridden image() in field.class.php currently asks for a pix named regex ($OUTPUT->pix_icon('regex', 'regex', 'datafield_regex')), which does not exist in the plugin (pix/icon.svg/pix/icon.png). Reference the bundled icon by its real name and component instead:
public function image() {
global $OUTPUT;
return $OUTPUT->pix_icon('icon', get_string('pluginname', 'datafield_regex'), 'datafield_regex');
}
Then remove the copyicon() calls from db/install.php and db/upgrade.php. If any file must ever be created outside the plugin directory, add a db/uninstall.php that removes it.
\datafield_regex\install::copyicon();
Remove this call once the icon is served from the plugin's own pix/ directory.
\datafield_regex\install::copyicon();
Remove this call once the icon is served from the plugin's own pix/ directory.
The constructor's guard, meant to confirm the field being built matches the fid/d request parameters before pre-filling the form with submitted values, ends in $field->dataid = $dataid — a single = assignment, not the intended == comparison.
Because assignment has lower precedence than &&, PHP parses the last term as ... && ($field->dataid = $dataid); the file loads without error (verified), but two things happen:
- The
dataidhalf of the guard is never actually checked — the assignment result is simply the value of$dataid, which is truthy wheneverd > 0. $field->dataidis overwritten with the raw request parameterdon the in-memory field object.
This is a clear defect. It does not have a security impact in practice (see risk assessment), but a guard that silently mutates the object it is guarding is fragile and should be corrected.
Low risk. No security impact. Reaching this code requires the mod/data:managetemplates capability (teacher/manager), the capability check is bound to the context derived from d, and core independently constrains the loaded field to that database — so the defeated dataid check cannot be used to touch a field in another database or course. The bug is masked today by those surrounding invariants, but it is a genuine logic error that could surface if the calling code changes, and it should be fixed.
The prefill block only runs from mod/data/field.php, which enforces require_login(), require_capability('mod/data:managetemplates', $context) and confirm_sesskey() before any field object is built. Core loads the field with data_get_field_from_id($fid, $data), which fetches the row with both id = $fid and dataid = $data->id, so the field is already guaranteed to belong to the database identified by d. The overwritten dataid is therefore set to the same value it already held, and the pre-filled param*/name/description values are only used to re-render the edit form; the actual save path re-reads and re-validates data_submitted() independently.
if (
$fieldid > 0 && $dataid > 0
&& is_object($field)
&& $field->id == $fieldid && $field->dataid = $dataid
) {
Use the equality operator so the guard compares instead of assigns:
&& $field->id == $fieldid && $field->dataid == $dataid
In the Privacy API export, the exported case-sensitive flag is read from $fieldobj->param1, but param1 is the obsolete "autolink" parameter (removed from the UI and always 0). The case-sensitive setting is stored in param2. As a result, the GDPR data export always reports case-sensitivity as No, regardless of the field's real configuration.
Additionally, the user's stored answer ($contentobj->content) is re-labelled as regex in the export output, which is misleading — the value is the data subject's submitted content, not the regular expression (the pattern lives in the field's param3).
Low risk. This is a correctness defect in a GDPR subject-access export, not a data-leak or access issue: all of the data still belongs to the requesting subject and no extra data is exposed. The only consequence is that the exported metadata is inaccurate (case-sensitivity always shown as No) and the answer is labelled confusingly. Worth fixing for export fidelity.
Core's mod_data privacy provider builds a $defaultvalue object (with a field array holding name, description, type, required, and the content value) and invokes each datafield subplugin's export_data_content() so the subplugin can enrich it. This plugin adds a casesensitive entry to that array. The field parameters are: param1 = autolink (obsolete), param2 = case-sensitive, param3 = the regex, param4 = partial match, param5 = custom error message.
public static function export_data_content($context, $recordobj, $fieldobj, $contentobj, $defaultvalue) {
$defaultvalue->field['casesensitive'] = transform::yesno($fieldobj->param1);
$defaultvalue->regex = $contentobj->content;
unset($defaultvalue->content);
writer::with_context($context)->export_data([$recordobj->id, $contentobj->id], $defaultvalue);
}
Read the case-sensitivity flag from param2, and keep the user's answer under a clearly named key (or leave it as content):
$defaultvalue->field['casesensitive'] = transform::yesno($fieldobj->param2);
generate_sql() — and its docblock — are clearly copied from the datafield_email plugin and were not renamed. The SQL placeholder is built as df_email_$i and the method comment refers to "when in advanced search the email field is filled", in a plugin that has nothing to do with email.
The query itself is safe: the value is bound through a named placeholder via $DB->sql_like(), and {$this->field->id} is an integer primary key. The issue is maintainability/readability. There is also a theoretical placeholder-name overlap with datafield_email (both emit df_email_1, df_email_2, … from independent static counters), though core processes each search field as an independent nested subquery with its own parameter scope, so this is unlikely to manifest as a functional bug.
Low risk. No security impact — the search term is parameterised and the interpolated field id is an integer. This is a code-quality/maintainability finding: misleading identifiers and comments inherited from a copied source, with only a remote and largely core-isolated chance of a placeholder collision.
generate_sql() is called from mod/data/locallib.php during advanced search with a per-field table alias ('c'.$field->id). Each field's SQL fragment and parameters are stored separately in $searcharray[$field->id] and later assembled into per-field nested subqueries, each merged with its own record-id parameters.
static $i = 0;
$i++;
$name = "df_email_$i";
return [
" ({$tablealias}.fieldid = {$this->field->id} AND "
. $DB->sql_like("{$tablealias}.content", ":$name", false)
. ') ',
[$name => "%$value%"],
];
Rename the placeholder (and fix the docblock) to reflect this plugin, ideally including the field id so the name is unambiguous across field types and fields:
static $i = 0;
$i++;
$name = "df_regex_{$this->field->id}_{$i}";
Every submitted entry value is matched against the field's stored pattern with preg_match($this->get_pattern($this->field->param3), $val). Because the pattern is authored by a user with the mod/data:managetemplates capability, a pathological pattern combined with a crafted input can trigger catastrophic backtracking (ReDoS), consuming CPU on the request that submits the entry.
This is an inherent property of a regular-expression field and is well mitigated in practice:
- PHP bounds backtracking via
pcre.backtrack_limit(default 1,000,000). When the limit is hit,preg_match()returnsfalserather than hanging indefinitely; the plugin's!preg_match(...)then simply treats the value as non-matching and rejects it (fail-closed). - Authoring a pattern requires teacher/manager privilege, and patterns are validated at creation time (
validate()rejects patterns that fail to compile).
Recorded here as an awareness note rather than a live vulnerability.
Informational. Not a practical vulnerability in a standard configuration. The regex author must hold mod/data:managetemplates (teacher/manager), and PHP's pcre.backtrack_limit/pcre.recursion_limit cap worst-case matching so there is no unbounded hang — the failure mode is bounded CPU followed by input rejection. Raised so the maintainer is aware that arbitrary teacher-supplied patterns run against user input.
field_validation() is called from core's data_process_submission() when a user adds or edits a database entry. The pattern comes from the field's param3, set by a teacher/manager via mod/data/field.php; the value being matched is the submitting user's input.
A teacher creates a regex field with pattern (a+)+ and Only partial match unchecked, so get_pattern() produces ~^(a+)+$~i. A user then submits a value such as aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa! (a long run of a ending in a non-matching character). The engine backtracks heavily until pcre.backtrack_limit is reached, preg_match() returns false, and the input is rejected — after burning CPU up to the configured limit.
if ($val !== '' && !preg_match($this->get_pattern($this->field->param3), $val)) {
No code change is strictly required given PHP's PCRE limits. Optionally, document that the backtrack limit governs worst-case matching cost, and consider distinguishing a genuine preg_match(...) === false (engine error / limit exceeded) from a normal non-match so operators can spot problematic patterns.
Access control and CSRF are correctly delegated to core. The plugin ships no pages or endpoints of its own. Field creation/editing (where mod.html, validate() and define_field() run) is driven by mod/data/field.php, which enforces require_login(), require_capability('mod/data:managetemplates', $context) and confirm_sesskey(); entry submission runs through mod/data/edit.php and data_process_submission(). There are consequently no missing capability or sesskey checks in the plugin's own code.
Output encoding is handled correctly. mod.html prints every field value through p() (which applies s()), the advanced-search field uses s($value), and the teacher-defined custom error message (param5) is emitted through format_string() — the sanctioned path, which runs the multilang filter and clean_text() so a teacher cannot inject script into the message shown to students. Field parameters are read with optional_param()/PARAM_*; no PHP superglobals are used.
Data access uses the framework APIs. Field storage goes through mod_data's data_field_base (insert_field()/update_field()), and the advanced-search query uses a bound placeholder via $DB->sql_like(). There is no raw database driver usage, no schema modification outside db/, and no reads/writes to the Moodle file store outside the File API (the only filesystem write is the install-time icon issue in finding 1).
Good test and CI coverage. The plugin includes PHPUnit tests for both entry validation and field definition, two Behat features, and a CI matrix spanning PHP 8.0–8.4, Moodle 4.02–5.02 and both PostgreSQL and MariaDB, running the Moodle code checker, phpdoc checker, validate and savepoint checks.
Minor cosmetic note (not a finding): the db/upgrade.php docblock is copied from the install file and mislabels the upgrade routine as "Post install". No thirdpartylibs.xml is required — the only bundled non-code asset is the SVG icon (CC BY 4.0), which is attributed in README.md; no third-party code libraries are shipped.