img_auth.php 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. <?php
  2. /**
  3. * Image authorisation script
  4. *
  5. * To use this, see https://www.mediawiki.org/wiki/Manual:Image_Authorization
  6. *
  7. * - Set $wgUploadDirectory to a non-public directory (not web accessible)
  8. * - Set $wgUploadPath to point to this file
  9. *
  10. * Optional Parameters
  11. *
  12. * - Set $wgImgAuthDetails = true if you want the reason the access was denied messages to
  13. * be displayed instead of just the 403 error (doesn't work on IE anyway),
  14. * otherwise it will only appear in error logs
  15. *
  16. * For security reasons, you usually don't want your user to know *why* access was denied,
  17. * just that it was. If you want to change this, you can set $wgImgAuthDetails to 'true'
  18. * in localsettings.php and it will give the user the reason why access was denied.
  19. *
  20. * Your server needs to support REQUEST_URI or PATH_INFO; CGI-based
  21. * configurations sometimes don't.
  22. *
  23. * This program is free software; you can redistribute it and/or modify
  24. * it under the terms of the GNU General Public License as published by
  25. * the Free Software Foundation; either version 2 of the License, or
  26. * (at your option) any later version.
  27. *
  28. * This program is distributed in the hope that it will be useful,
  29. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  30. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  31. * GNU General Public License for more details.
  32. *
  33. * You should have received a copy of the GNU General Public License along
  34. * with this program; if not, write to the Free Software Foundation, Inc.,
  35. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  36. * http://www.gnu.org/copyleft/gpl.html
  37. *
  38. * @file
  39. */
  40. define( 'MW_NO_OUTPUT_COMPRESSION', 1 );
  41. define( 'MW_ENTRY_POINT', 'img_auth' );
  42. require __DIR__ . '/includes/WebStart.php';
  43. # Set action base paths so that WebRequest::getPathInfo()
  44. # recognizes the "X" as the 'title' in ../img_auth.php/X urls.
  45. $wgArticlePath = false; # Don't let a "/*" article path clober our action path
  46. $wgActionPaths = [ "$wgUploadPath/" ];
  47. wfImageAuthMain();
  48. $mediawiki = new MediaWiki();
  49. $mediawiki->doPostOutputShutdown( 'fast' );
  50. function wfImageAuthMain() {
  51. global $wgImgAuthUrlPathMap;
  52. $permissionManager = \MediaWiki\MediaWikiServices::getInstance()->getPermissionManager();
  53. $request = RequestContext::getMain()->getRequest();
  54. $publicWiki = in_array( 'read', $permissionManager->getGroupPermissions( [ '*' ] ), true );
  55. // Get the requested file path (source file or thumbnail)
  56. $matches = WebRequest::getPathInfo();
  57. if ( !isset( $matches['title'] ) ) {
  58. wfForbidden( 'img-auth-accessdenied', 'img-auth-nopathinfo' );
  59. return;
  60. }
  61. $path = $matches['title'];
  62. if ( $path && $path[0] !== '/' ) {
  63. // Make sure $path has a leading /
  64. $path = "/" . $path;
  65. }
  66. // Check for T30235: QUERY_STRING overriding the correct extension
  67. $whitelist = [];
  68. $extension = FileBackend::extensionFromPath( $path, 'rawcase' );
  69. if ( $extension != '' ) {
  70. $whitelist[] = $extension;
  71. }
  72. if ( !$request->checkUrlExtension( $whitelist ) ) {
  73. return;
  74. }
  75. $user = RequestContext::getMain()->getUser();
  76. // Various extensions may have their own backends that need access.
  77. // Check if there is a special backend and storage base path for this file.
  78. foreach ( $wgImgAuthUrlPathMap as $prefix => $storageDir ) {
  79. $prefix = rtrim( $prefix, '/' ) . '/'; // implicit trailing slash
  80. if ( strpos( $path, $prefix ) === 0 ) {
  81. $be = FileBackendGroup::singleton()->backendFromPath( $storageDir );
  82. $filename = $storageDir . substr( $path, strlen( $prefix ) ); // strip prefix
  83. // Check basic user authorization
  84. if ( !$user->isAllowed( 'read' ) ) {
  85. wfForbidden( 'img-auth-accessdenied', 'img-auth-noread', $path );
  86. return;
  87. }
  88. if ( $be->fileExists( [ 'src' => $filename ] ) ) {
  89. wfDebugLog( 'img_auth', "Streaming `" . $filename . "`." );
  90. $be->streamFile( [ 'src' => $filename ],
  91. [ 'Cache-Control: private', 'Vary: Cookie' ] );
  92. } else {
  93. wfForbidden( 'img-auth-accessdenied', 'img-auth-nofile', $path );
  94. }
  95. return;
  96. }
  97. }
  98. // Get the local file repository
  99. $repo = RepoGroup::singleton()->getRepo( 'local' );
  100. $zone = strstr( ltrim( $path, '/' ), '/', true );
  101. // Get the full file storage path and extract the source file name.
  102. // (e.g. 120px-Foo.png => Foo.png or page2-120px-Foo.png => Foo.png).
  103. // This only applies to thumbnails/transcoded, and each of them should
  104. // be under a folder that has the source file name.
  105. if ( $zone === 'thumb' || $zone === 'transcoded' ) {
  106. $name = wfBaseName( dirname( $path ) );
  107. $filename = $repo->getZonePath( $zone ) . substr( $path, strlen( "/" . $zone ) );
  108. // Check to see if the file exists
  109. if ( !$repo->fileExists( $filename ) ) {
  110. wfForbidden( 'img-auth-accessdenied', 'img-auth-nofile', $filename );
  111. return;
  112. }
  113. } else {
  114. $name = wfBaseName( $path ); // file is a source file
  115. $filename = $repo->getZonePath( 'public' ) . $path;
  116. // Check to see if the file exists and is not deleted
  117. $bits = explode( '!', $name, 2 );
  118. if ( substr( $path, 0, 9 ) === '/archive/' && count( $bits ) == 2 ) {
  119. $file = $repo->newFromArchiveName( $bits[1], $name );
  120. } else {
  121. $file = $repo->newFile( $name );
  122. }
  123. if ( !$file->exists() || $file->isDeleted( File::DELETED_FILE ) ) {
  124. wfForbidden( 'img-auth-accessdenied', 'img-auth-nofile', $filename );
  125. return;
  126. }
  127. }
  128. $headers = []; // extra HTTP headers to send
  129. $title = Title::makeTitleSafe( NS_FILE, $name );
  130. if ( !$publicWiki ) {
  131. // For private wikis, run extra auth checks and set cache control headers
  132. $headers['Cache-Control'] = 'private';
  133. $headers['Vary'] = 'Cookie';
  134. if ( !$title instanceof Title ) { // files have valid titles
  135. wfForbidden( 'img-auth-accessdenied', 'img-auth-badtitle', $name );
  136. return;
  137. }
  138. // Run hook for extension authorization plugins
  139. /** @var array $result */
  140. $result = null;
  141. if ( !Hooks::run( 'ImgAuthBeforeStream', [ &$title, &$path, &$name, &$result ] ) ) {
  142. wfForbidden( $result[0], $result[1], array_slice( $result, 2 ) );
  143. return;
  144. }
  145. // Check user authorization for this title
  146. // Checks Whitelist too
  147. if ( !$permissionManager->userCan( 'read', $user, $title ) ) {
  148. wfForbidden( 'img-auth-accessdenied', 'img-auth-noread', $name );
  149. return;
  150. }
  151. }
  152. if ( isset( $_SERVER['HTTP_RANGE'] ) ) {
  153. $headers['Range'] = $_SERVER['HTTP_RANGE'];
  154. }
  155. if ( isset( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
  156. $headers['If-Modified-Since'] = $_SERVER['HTTP_IF_MODIFIED_SINCE'];
  157. }
  158. if ( $request->getCheck( 'download' ) ) {
  159. $headers['Content-Disposition'] = 'attachment';
  160. }
  161. // Allow modification of headers before streaming a file
  162. Hooks::run( 'ImgAuthModifyHeaders', [ $title->getTitleValue(), &$headers ] );
  163. // Stream the requested file
  164. list( $headers, $options ) = HTTPFileStreamer::preprocessHeaders( $headers );
  165. wfDebugLog( 'img_auth', "Streaming `" . $filename . "`." );
  166. $repo->streamFileWithStatus( $filename, $headers, $options );
  167. }
  168. /**
  169. * Issue a standard HTTP 403 Forbidden header ($msg1-a message index, not a message) and an
  170. * error message ($msg2, also a message index), (both required) then end the script
  171. * subsequent arguments to $msg2 will be passed as parameters only for replacing in $msg2
  172. * @param string $msg1
  173. * @param string $msg2
  174. * @param mixed ...$args To pass as params to wfMessage() with $msg2. Either variadic, or a single
  175. * array argument.
  176. */
  177. function wfForbidden( $msg1, $msg2, ...$args ) {
  178. global $wgImgAuthDetails;
  179. $args = ( isset( $args[0] ) && is_array( $args[0] ) ) ? $args[0] : $args;
  180. $msgHdr = wfMessage( $msg1 )->escaped();
  181. $detailMsgKey = $wgImgAuthDetails ? $msg2 : 'badaccess-group0';
  182. $detailMsg = wfMessage( $detailMsgKey, $args )->escaped();
  183. wfDebugLog( 'img_auth',
  184. "wfForbidden Hdr: " . wfMessage( $msg1 )->inLanguage( 'en' )->text() . " Msg: " .
  185. wfMessage( $msg2, $args )->inLanguage( 'en' )->text()
  186. );
  187. HttpStatus::header( 403 );
  188. header( 'Cache-Control: no-cache' );
  189. header( 'Content-Type: text/html; charset=utf-8' );
  190. echo <<<ENDS
  191. <!DOCTYPE html>
  192. <html>
  193. <head>
  194. <meta charset="UTF-8" />
  195. <title>$msgHdr</title>
  196. </head>
  197. <body>
  198. <h1>$msgHdr</h1>
  199. <p>$detailMsg</p>
  200. </body>
  201. </html>
  202. ENDS;
  203. }