# PHP: find, fix and verify
English | [Русский](php-RU.md)
[Catalog](README.md) · [Scanner](../offline-scanner.md) · [Patch verification](../patch-validation.md)
23 sections. Each follows **Search → Vulnerable example → Fix → Verification**.
Run `rg` from a local service checkout; searches only read files. Derive the actor/owner from a verified session, not request data. Adapt examples to the actual API and contract.
## Contents
- [PHP-SQL — Dynamic PHP SQL](#php-sql)
- [PHP-OBJECT — Untrusted PHP unserialize](#php-object)
- [PHP-SHELL — PHP code or shell execution](#php-shell)
- [PHP-INCLUDE — Client-selected include path](#php-include)
- [PHP-PREFIX-MAC — Hash concatenation instead of MAC](#php-prefix-mac)
- [PHP-PARSE-STR — parse_str key normalization](#php-parse-str)
- [PHP-LOOSE-COMPARE — Loose comparison of token or signature](#php-loose-compare)
- [PHP-UPLOAD — Moving an uploaded file](#php-upload)
- [PHP-DISPLAY-ERRORS — PHP displays errors to clients](#php-display-errors)
- [PHP-XSS — Raw data reaches HTML, attributes or JavaScript](#php-xss)
- [PHP-SESSION — Session fixation, strict mode and stale state](#php-session)
- [PHP-WRAPPERS — Filesystem APIs accept URLs or wrappers](#php-wrappers)
- [PHP-EXTRACT — extract overwrites local variables](#php-extract)
- [PHP-SERIALIZE-MAGIC — Magic methods and trust in stored data](#php-serialize-magic)
- [PHP-CSRF — Cookies authorize mutations without CSRF protection](#php-csrf)
- [PHP-REGEX-ERROR — preg_match errors become permission](#php-regex-error)
- [PHP-XML-FLAGS — XML entity substitution or DTD enabled](#php-xml-flags)
- [PHP-TEMPLATE — Template built from dynamic text](#php-template)
- [PHP-CURL-TLS — cURL certificate or hostname checks disabled](#php-curl-tls)
- [PHP-URL-INCLUDE — Remote resource inclusion enabled](#php-url-include)
- [PHP-SESSION-CONFIG — Weakened PHP session configuration](#php-session-config)
- [PHP-MASS-ASSIGN — Array keys choose columns and privileges](#php-mass-assign)
- [PHP-LDAP-FILTER — LDAP filter concatenates a PHP variable](#php-ldap-filter)
## PHP-SQL. Dynamic PHP SQL
**Search:** scanner rule PHP-SQL. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain PHP-SQL` for details. Regex: query/exec/prepare with concatenation, double-quoted interpolation and mysqli_query/pg_query with an ordinary connection argument. Escaping, other interpolation and SQL variables are not fully parsed.
**Vulnerable example:**
~~~php
$db->query("SELECT id FROM notes WHERE name=" . $name);
~~~
**Fix:** Use driver-supported prepared statements and bound values; allowlist identifiers.
~~~php
$stmt = $db->prepare("SELECT id FROM notes WHERE name = ?");
$stmt->execute([$name]);
~~~
**Verification:** Quotes stay data and ownership conditions remain.
Expanded example and limitations
```php
// Vulnerable: client input is interpolated into SQL.
$row = $pdo->query("SELECT body FROM notes WHERE id = '" . $_GET['id'] . "'")->fetch();
```
**PDO patch for a private note:**
```php
function readPrivateNote(PDO $pdo, ?int $userId, int $noteId): ?string {
if ($userId === null) {
throw new RuntimeException('authentication required');
}
$stmt = $pdo->prepare('SELECT body FROM notes WHERE id = :id AND owner_id = :owner');
$stmt->bindValue(':id', $noteId, PDO::PARAM_INT);
$stmt->bindValue(':owner', $userId, PDO::PARAM_INT);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
return $row === false ? null : $row['body'];
}
```
Validate the numeric ID first: `(int) $_GET['id']` silently converts some invalid strings. Configure PDO error handling and do not return SQL exceptions to clients. Placeholders represent values, not table/column names. Native prepares may be appropriate for supported drivers, but do not change application-wide settings blindly; driver behavior differs.
**Check:** Owner, other user, no session, missing record, invalid ID and another searchable text field containing an apostrophe. Preserve intended sharing.
## PHP-OBJECT. Untrusted PHP unserialize
**Search:** scanner rule PHP-OBJECT. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain PHP-OBJECT` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.
**Vulnerable example:**
~~~php
$value = unserialize($data);
~~~
**Fix:** Prefer schema-validated JSON; migrate trusted legacy records separately. allowed_classes alone is not a complete input policy.
~~~php
$value = json_decode($data, true, 32, JSON_THROW_ON_ERROR); // validate schema
~~~
**Verification:** Unexpected object types fail without construction; valid records stay readable.
Expanded example and limitations
```php
// Vulnerable with untrusted input: object restoration has side effects.
$profile = unserialize($_COOKIE['profile']);
```
**Patch for a simple profile when the protocol supports JSON:**
```php
function decodeProfile(string $raw): array {
$value = json_decode($raw, false, 32, JSON_THROW_ON_ERROR);
if (!($value instanceof stdClass)) {
throw new InvalidArgumentException('object required');
}
$fields = get_object_vars($value);
if (array_keys($fields) !== ['display_name'] || !is_string($fields['display_name'])) {
throw new InvalidArgumentException('unexpected profile fields');
}
return ['display_name' => $fields['display_name']];
}
```
Depth 32 is an example bound, not a competition requirement; bound body size before parsing according to contract. Role and owner come from the server. PHP warns against untrusted unserialize even with allowed_classes: that flag alone is not a complete fix.
**Check:** Valid profile, unknown field, array instead of object, wrong type and malformed JSON. Format migration must support old clients/data; never retain unserialize fallback for client strings.
## PHP-SHELL. PHP code or shell execution
**Search:** scanner rule PHP-SHELL. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain PHP-SHELL` for details. Regex: eval/shell_exec/system/passthru/popen/exec and string/variable proc_open. Literal argv arrays in proc_open's first argument (including PHP 8 command:) are excluded unless explicitly launching shell; arrays require PHP 7.4+. Review executable/options, reordered named arguments, backticks, variable functions, wrappers and runtime version. Custom same-named functions/comments may match.
**Vulnerable example:**
~~~php
shell_exec($command);
~~~
**Fix:** Prefer a library operation; otherwise use a fixed executable and validated argv without a shell.
~~~php
$size = filesize($checkedPath);
~~~
**Verification:** Metacharacters and dangerous options cannot change the operation.
proc_open accepts argv arrays from PHP 7.4; the named command argument requires PHP 8.0. Arrays pass arguments without an implicit shell. A genuinely required utility can run without shell, for example on PHP 8+:
~~~php
$process = proc_open(
command: ['/usr/bin/file', '--', $checkedName],
descriptor_spec: $descriptors,
pipes: $pipes
);
~~~
The executable is fixed; $checkedName still needs authorization and path checks. `--` is valid only for utilities supporting that separator. `command: array('/usr/bin/file', '--', $checkedName)` also avoids PHP-SHELL. The exclusion covers only a literal-array first argument; reordered named arguments and variable arrays remain review signals. [proc_open arrays and Windows limitations](https://github.com/php/doc-en/blob/master/reference/exec/functions/proc-open.xml#L68), [PHP 8 named arguments](https://www.php.net/manual/en/migration80.new-features.php#migration80.new-features.core.named-arguments), [PHP 8.0 proc_open signature](https://github.com/php/php-src/blob/php-8.0.0/ext/standard/basic_functions.stub.php#L1156).
Explicit shell execution remains risky and still signals even with an array:
~~~php
$process = proc_open(command: ['sh', '-c', $command], descriptor_spec: $descriptors, pipes: $pipes);
~~~
Do not convert a pipeline to argv by simply splitting text: move operations to a library or connect processes explicitly. Review executable, options, PATH, cwd and environment. On Windows array escaping assumes VC-runtime-compatible command-line parsing; other parsers may differ. Close pipes/processes and check errors, runtime/output limits and the old result format.
~~~bash
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'proc_open|proc_close|proc_terminate|shell_exec|descriptor_spec|bypass_shell' .
~~~
After a match trace actual argv and every argument's origin. In an authorized test environment check spaces, quotes, leading dashes, normal files and process failure. Absence of PHP-SHELL does not prove argument safety. This catalog review checked source and scanner behavior; it did not run PHP or the discovered commands.
## PHP-INCLUDE. Client-selected include path
**Search:** scanner rule PHP-INCLUDE. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain PHP-INCLUDE` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.
**Vulnerable example:**
~~~php
include $_GET['page'];
~~~
**Fix:** Select server-owned include paths from a closed allowlist, never client paths/URLs.
~~~php
$pages = ['home' => __DIR__ . '/pages/home.php'];
if (!isset($pages[$page])) { throw new Exception('bad page'); }
include $pages[$page];
~~~
**Verification:** Only approved pages load; traversal and remote schemes fail.
Expanded example and limitations
```php
// Vulnerable: the client controls the executable PHP file path.
include $_GET['page'];
```
**Patch when the contract selects one of several known pages:**
```php
$pages = [
'help' => __DIR__ . '/pages/help.php',
'profile' => __DIR__ . '/pages/profile.php',
];
$page = $_GET['page'] ?? 'help';
if (!is_string($page) || !array_key_exists($page, $pages)) {
http_response_code(404);
exit;
}
require $pages[$page];
```
The server defines paths. The profile page still requires authorization before private data is returned. basename() neither restricts selection to the intended pages nor checks access. If the feature displays user-uploaded files, include must not implement that display.
**Check:** Both normal pages, unknown names and an array in place of page; anonymous callers cannot open private pages; only permitted selection changes.
## PHP-PREFIX-MAC. Hash concatenation instead of MAC
**Search:** scanner rule PHP-PREFIX-MAC. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain PHP-PREFIX-MAC` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.
**Vulnerable example:**
~~~php
$tag = sha1($key . $payload);
~~~
**Fix:** Use HMAC rather than a hash of secret concatenated with data, compare with hash_equals and migrate/version old formats.
~~~php
$tag = hash_hmac('sha256', $payload, $key);
~~~
**Verification:** Changed/appended data fails; tags bind purpose and all authentication fields.
**A/D variant:** Secret-prefix hash mislabeled HMAC. **ECSC / Diese, author and source.** Signatures used SHA1(secret || data). **Patch:** Real HMAC, token versioning and safe migration of existing signatures. **Test:** Changed/added fields fail validation. **Search:** PHP-PREFIX-MAC; a function named hmac guarantees nothing.
[source/write-up 1](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/Diese/README.md); [source/write-up 2](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/Diese/webapp/src/classes/Utils.class.php); [source/write-up 3](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/Diese/hsm/src/msg.c).
## PHP-PARSE-STR. parse_str key normalization
**Search:** scanner rule PHP-PARSE-STR. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain PHP-PARSE-STR` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.
**Vulnerable example:**
~~~php
parse_str($token_data, $params);
~~~
**Fix:** Use identical schemas before signing/after parsing; account for dots/spaces becoming underscores, arrays and duplicate keys.
~~~php
$params = parse_and_validate_canonical_share_dto($token_data); // one schema, duplicate policy, server-owned fields
~~~
**Verification:** Alternate spellings cannot change owner/document; signer and verifier agree.
**A/D variant:** Parameter-key normalization after signing. **ECSC / Diese, author and source.** parse_str merges certain distinct names and changes field meaning. **Patch:** An allowlist and one canonical signer/verifier DTO schema; reject ambiguous duplicates. **Test:** Dots, spaces, underscores and arrays. **Search:** PHP-PARSE-STR; the call itself need not be vulnerable.
[source/write-up 1](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/Diese/README.md); [source/write-up 2](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/Diese/webapp/src/classes/Utils.class.php); [source/write-up 3](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/Diese/hsm/src/msg.c).
## PHP-LOOSE-COMPARE. Loose comparison of token or signature
**Search:** scanner rule PHP-LOOSE-COMPARE. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain PHP-LOOSE-COMPARE` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.
**Vulnerable example:**
~~~php
$ok = $token == $provided;
~~~
**Fix:** Validate types; use hash_equals for tags, === for ordinary values and password_verify for passwords. Numeric-string semantics depend on version/operands.
~~~php
$ok = is_string($provided) && hash_equals($token, $provided);
~~~
**Verification:** Numbers, arrays and numeric strings cannot grant access; valid values work.
**Reference:** [primary source](https://www.php.net/manual/en/language.operators.comparison.php).
## PHP-UPLOAD. Moving an uploaded file
**Search:** scanner rule PHP-UPLOAD. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain PHP-UPLOAD` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.
**Vulnerable example:**
~~~php
move_uploaded_file($tmp, $webroot . $name);
~~~
**Fix:** Check upload error/size/type; use non-overwriting server-generated names outside executable web roots and authorize downloads.
~~~php
move_uploaded_file($validatedTmp, $serverChosenPrivatePath);
~~~
**Verification:** Test upload/download, collisions, wrong owner/type and full disk. The call remains a review signal.
**Reference:** [primary source](https://www.php.net/manual/en/features.file-upload.php).
## PHP-DISPLAY-ERRORS. PHP displays errors to clients
**Search:** scanner rule PHP-DISPLAY-ERRORS. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain PHP-DISPLAY-ERRORS` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.
**Vulnerable example:**
~~~php
display_errors = On
~~~
**Fix:** Disable client error output and retain redacted local logs; check effective php.ini/FPM and runtime ini_set.
~~~php
display_errors = Off
~~~
**Verification:** Parse/database/type errors yield expected public responses while private diagnostics remain.
**Reference:** [primary source](https://www.php.net/manual/en/errorfunc.configuration.php).
## PHP-XSS. Raw data reaches HTML, attributes or JavaScript
**Search:** manual review; no separate scanner rule.
~~~bash
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'echo|print|htmlspecialchars|json_encode|