Repository navigation
Description
PHP Version
8.4
CodeIgniter4 Version
4.7.7-dev (commit 08039be). I also checked 4.7.6 and the same code is there.
CodeIgniter4 Installation Method
Git
Which operating systems have you tested for this bug?
Linux
Which server did you use?
cli
Environment
development
Database
Not required for the CLI reproduction. I used MySQLi only for an optional app-level check. The issue is in helper output and does not depend on the database.
What happened?
parse_form_attributes() only escapes the value attribute. All other attribute values supplied through an associative array, such as class, style, id, name, or data-*, are concatenated into the tag without escaping. form_label() does the same with its id and attributes, and form_datalist() does it with the name and option values.
The form helper docs say associative array values are escaped automatically, so this looks like a mismatch between the docs and the code.
Example:
$payload = 'x" onmouseover="alert(document.domain)" data-x="';
echo form_input(['name' => 'q', 'class' => $payload, 'value' => $payload]);
Output:
The value attribute is escaped, but class is not. I got the same result from form_hidden(), form_button(), form_textarea(), form_dropdown(), and form_datalist().
Steps to Reproduce
I left a runnable script at bug-reports/poc/f01-form-helper-attribute-injection.php. It loads the real helper and stubs the few framework functions it needs, so no Composer install is required.
From the project root:
php bug-reports/poc/f01-form-helper-attribute-injection.php
The key calls are:
$payload = 'x" onmouseover="alert(document.domain)" data-x="';
echo form_input(['name' => 'q', 'class' => $payload, 'value' => $payload]);
echo form_label('Label', 'foo', ['class' => $payload]);
To check it in a browser, save the output to /tmp/f01.html and open it. Hover the label or the input.
Expected Output
LabelNo literal onmouseover="..." attribute should appear.
Anything else?
The fix is to escape every non-boolean value in parse_form_attributes():
foreach ($default as $key => $val) {
if (! is_bool($val)) {
if ($key === 'name' && $default['name'] === '') {
continue;
}
$att .= $key . '="' . esc($val) . '"'
. ($key === array_key_last($default) ? '' : ' ');
} else {
$att .= $key . ' ';
}
}
form_label() and form_datalist() need the same treatment:
if ($id !== '') {
$label .= ' for="' . esc($id) . '"';
}
foreach ($attributes as $key => $val) {
$label .= ' ' . $key . '="' . esc($val) . '"';
}
$out .= '';
foreach ($options as $option) {
$out .= '' . "\n";
}
A regression test in tests/system/Helpers/FormHelperTest.php would cover it. I can provide a patch.
Activity