From daa5eb6340183c971297aa1d91c2e092c34067ae Mon Sep 17 00:00:00 2001
From: Brad Jorsch <bjorsch@wikimedia.org>
Date: Mon, 18 Jan 2016 12:00:41 -0500
Subject: [PATCH] SECURITY: Improve cross-domain-policy mangling

Take into account that the tag might have parameters.

Bug: T123653
Change-Id: Ie9799f5ea45badfb4e7b4be7e7fbc1c35cc86f26
---
 includes/OutputHandler.php     | 4 ++--
 includes/api/ApiFormatJson.php | 4 ++--
 includes/api/ApiFormatPhp.php  | 2 +-
 3 files changed, 5 insertions(+), 5 deletions(-)

diff --git a/includes/OutputHandler.php b/includes/OutputHandler.php
index 65bb86e..7546579 100644
--- a/includes/OutputHandler.php
+++ b/includes/OutputHandler.php
@@ -153,8 +153,8 @@ function wfGzipHandler( $s ) {
  */
 function wfMangleFlashPolicy( $s ) {
 	# Avoid weird excessive memory usage in PCRE on big articles
-	if ( preg_match( '/\<\s*cross-domain-policy\s*\>/i', $s ) ) {
-		return preg_replace( '/\<\s*cross-domain-policy\s*\>/i', '<NOT-cross-domain-policy>', $s );
+	if ( preg_match( '/\<\s*cross-domain-policy(?=\s|\>)/i', $s ) ) {
+		return preg_replace( '/\<(\s*)(cross-domain-policy(?=\s|\>))/i', '<$1NOT-$2', $s );
 	} else {
 		return $s;
 	}
diff --git a/includes/api/ApiFormatJson.php b/includes/api/ApiFormatJson.php
index b222f74..b0be2fd 100644
--- a/includes/api/ApiFormatJson.php
+++ b/includes/api/ApiFormatJson.php
@@ -67,9 +67,9 @@ class ApiFormatJson extends ApiFormatBase {
 		// Bug 66776: wfMangleFlashPolicy() is needed to avoid a nasty bug in
 		// Flash, but what it does isn't friendly for the API, so we need to
 		// work around it.
-		if ( preg_match( '/\<\s*cross-domain-policy\s*\>/i', $json ) ) {
+		if ( preg_match( '/\<\s*cross-domain-policy(?=\s|\>)/i', $json ) ) {
 			$json = preg_replace(
-				'/\<(\s*cross-domain-policy\s*)\>/i', '\\u003C$1\\u003E', $json
+				'/\<(\s*cross-domain-policy(?=\s|\>))/i', '\\u003C$1', $json
 			);
 		}
 
diff --git a/includes/api/ApiFormatPhp.php b/includes/api/ApiFormatPhp.php
index 73ce80e..fd6a310 100644
--- a/includes/api/ApiFormatPhp.php
+++ b/includes/api/ApiFormatPhp.php
@@ -43,7 +43,7 @@ class ApiFormatPhp extends ApiFormatBase {
 		// just be broken in a useful manner.
 		if ( $this->getConfig()->get( 'MangleFlashPolicy' ) &&
 			in_array( 'wfOutputHandler', ob_list_handlers(), true ) &&
-			preg_match( '/\<\s*cross-domain-policy\s*\>/i', $text )
+			preg_match( '/\<\s*cross-domain-policy(?=\s|\>)/i', $text )
 		) {
 			$this->dieUsage(
 				'This response cannot be represented using format=php. See https://bugzilla.wikimedia.org/show_bug.cgi?id=66776',
-- 
2.8.1

