img_auth.php 7.5 KB

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