MediaWiki  1.29.1
ApiCSPReport.php
Go to the documentation of this file.
1 <?php
24 
30 class ApiCSPReport extends ApiBase {
31 
32  private $log;
33 
37  const MAX_POST_SIZE = 8192;
38 
42  public function execute() {
43  $reportOnly = $this->getParameter( 'reportonly' );
44  $logname = $reportOnly ? 'csp-report-only' : 'csp';
45  $this->log = LoggerFactory::getInstance( $logname );
46  $userAgent = $this->getRequest()->getHeader( 'user-agent' );
47 
48  $this->verifyPostBodyOk();
49  $report = $this->getReport();
50  $flags = $this->getFlags( $report );
51 
52  $warningText = $this->generateLogLine( $flags, $report );
53  $this->logReport( $flags, $warningText, [
54  // XXX Is it ok to put untrusted data into log??
55  'csp-report' => $report,
56  'method' => __METHOD__,
57  'user' => $this->getUser()->getName(),
58  'user-agent' => $userAgent,
59  'source' => $this->getParameter( 'source' ),
60  ] );
61  $this->getResult()->addValue( null, $this->getModuleName(), 'success' );
62  }
63 
70  private function logReport( $flags, $logLine, $context ) {
71  if ( in_array( 'false-positive', $flags ) ) {
72  // These reports probably don't matter much
73  $this->log->debug( $logLine, $context );
74  } else {
75  // Normal report.
76  $this->log->warning( $logLine, $context );
77  }
78  }
79 
86  private function getFlags( $report ) {
87  $reportOnly = $this->getParameter( 'reportonly' );
88  $source = $this->getParameter( 'source' );
89  $falsePositives = $this->getConfig()->get( 'CSPFalsePositiveUrls' );
90 
91  $flags = [];
92  if ( $source !== 'internal' ) {
93  $flags[] = 'source=' . $source;
94  }
95  if ( $reportOnly ) {
96  $flags[] = 'report-only';
97  }
98 
99  if (
100  ( isset( $report['blocked-uri'] ) &&
101  isset( $falsePositives[$report['blocked-uri']] ) )
102  || ( isset( $report['source-file'] ) &&
103  isset( $falsePositives[$report['source-file']] ) )
104  ) {
105  // Report caused by Ad-Ware
106  $flags[] = 'false-positive';
107  }
108  return $flags;
109  }
110 
114  private function verifyPostBodyOk() {
115  $req = $this->getRequest();
116  $contentType = $req->getHeader( 'content-type' );
117  if ( $contentType !== 'application/json'
118  && $contentType !=='application/csp-report'
119  ) {
120  $this->error( 'wrongformat', __METHOD__ );
121  }
122  if ( $req->getHeader( 'content-length' ) > self::MAX_POST_SIZE ) {
123  $this->error( 'toobig', __METHOD__ );
124  }
125  }
126 
132  private function getReport() {
133  $postBody = $this->getRequest()->getRawInput();
134  if ( strlen( $postBody ) > self::MAX_POST_SIZE ) {
135  // paranoia, already checked content-length earlier.
136  $this->error( 'toobig', __METHOD__ );
137  }
139  if ( !$status->isGood() ) {
140  $msg = $status->getErrors()[0]['message'];
141  if ( $msg instanceof Message ) {
142  $msg = $msg->getKey();
143  }
144  $this->error( $msg, __METHOD__ );
145  }
146 
147  $report = $status->getValue();
148 
149  if ( !isset( $report['csp-report'] ) ) {
150  $this->error( 'missingkey', __METHOD__ );
151  }
152  return $report['csp-report'];
153  }
154 
162  private function generateLogLine( $flags, $report ) {
163  $flagText = '';
164  if ( $flags ) {
165  $flagText = '[' . implode( $flags, ', ' ) . ']';
166  }
167 
168  $blockedFile = isset( $report['blocked-uri'] ) ? $report['blocked-uri'] : 'n/a';
169  $page = isset( $report['document-uri'] ) ? $report['document-uri'] : 'n/a';
170  $line = isset( $report['line-number'] ) ? ':' . $report['line-number'] : '';
171  $warningText = $flagText .
172  ' Received CSP report: <' . $blockedFile .
173  '> blocked from being loaded on <' . $page . '>' . $line;
174  return $warningText;
175  }
176 
184  private function error( $code, $method ) {
185  $this->log->info( 'Error reading CSP report: ' . $code, [
186  'method' => $method,
187  'user-agent' => $this->getRequest()->getHeader( 'user-agent' )
188  ] );
189  // 500 so it shows up in browser's developer console.
190  $this->dieWithError(
191  [ 'apierror-csp-report', wfEscapeWikiText( $code ) ], 'cspreport-' . $code, [], 500
192  );
193  }
194 
195  public function getAllowedParams() {
196  return [
197  'reportonly' => [
198  ApiBase::PARAM_TYPE => 'boolean',
200  ],
201  'source' => [
202  ApiBase::PARAM_TYPE => 'string',
203  ApiBase::PARAM_DFLT => 'internal',
205  ]
206  ];
207  }
208 
209  public function mustBePosted() {
210  return true;
211  }
212 
213  public function isWriteMode() {
214  return false;
215  }
216 
220  public function isInternal() {
221  return true;
222  }
223 
227  public function isReadMode() {
228  return false;
229  }
230 
236  public function shouldCheckMaxLag() {
237  return false;
238  }
239 }
ContextSource\$context
IContextSource $context
Definition: ContextSource.php:34
ContextSource\getConfig
getConfig()
Get the Config object.
Definition: ContextSource.php:68
ApiCSPReport\getAllowedParams
getAllowedParams()
Returns an array of allowed parameters (parameter name) => (default value) or (parameter name) => (ar...
Definition: ApiCSPReport.php:195
false
processing should stop and the error should be shown to the user * false
Definition: hooks.txt:189
ApiCSPReport\isWriteMode
isWriteMode()
Indicates whether this module requires write mode.
Definition: ApiCSPReport.php:213
ApiBase\PARAM_REQUIRED
const PARAM_REQUIRED
(boolean) Is the parameter required?
Definition: ApiBase.php:115
ApiBase\dieWithError
dieWithError( $msg, $code=null, $data=null, $httpCode=null)
Abort execution with an error.
Definition: ApiBase.php:1796
ApiBase\PARAM_TYPE
const PARAM_TYPE
(string|string[]) Either an array of allowed value strings, or a string type as described below.
Definition: ApiBase.php:91
ApiBase\getResult
getResult()
Get the result object.
Definition: ApiBase.php:610
$status
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist Do not use this to implement individual filters if they are compatible with the ChangesListFilter and ChangesListFilterGroup structure use sub classes of those in conjunction with the ChangesListSpecialPageStructuredFilters hook This hook can be used to implement filters that do not implement that or custom behavior that is not an individual filter e g Watchlist and Watchlist you will want to construct new ChangesListBooleanFilter or ChangesListStringOptionsFilter objects When constructing you specify which group they belong to You can reuse existing or create your you must register them with $special registerFilterGroup removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set $status
Definition: hooks.txt:1049
use
as see the revision history and available at free of to any person obtaining a copy of this software and associated documentation to deal in the Software without including without limitation the rights to use
Definition: MIT-LICENSE.txt:10
$req
this hook is for auditing only $req
Definition: hooks.txt:990
ApiCSPReport\mustBePosted
mustBePosted()
Indicates whether this module must be called with a POST request.
Definition: ApiCSPReport.php:209
ContextSource\getRequest
getRequest()
Get the WebRequest object.
Definition: ContextSource.php:78
ApiCSPReport
Api module to receive and log CSP violation reports.
Definition: ApiCSPReport.php:30
ContextSource\getUser
getUser()
Get the User object.
Definition: ContextSource.php:133
php
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
ApiBase
This abstract class implements many basic API functions, and is the base of all API classes.
Definition: ApiBase.php:41
ApiCSPReport\$log
$log
Definition: ApiCSPReport.php:32
ApiCSPReport\shouldCheckMaxLag
shouldCheckMaxLag()
Doesn't touch db, so max lag should be rather irrelavent.
Definition: ApiCSPReport.php:236
ApiCSPReport\isInternal
isInternal()
Mark as internal.
Definition: ApiCSPReport.php:220
ApiCSPReport\isReadMode
isReadMode()
Even if you don't have read rights, we still want your report.
Definition: ApiCSPReport.php:227
ApiCSPReport\getReport
getReport()
Get the report from post body and turn into associative array.
Definition: ApiCSPReport.php:132
$page
do that in ParserLimitReportFormat instead use this to modify the parameters of the image and a DIV can begin in one section and end in another Make sure your code can handle that case gracefully See the EditSectionClearerLink extension for an example zero but section is usually empty its values are the globals values before the output is cached $page
Definition: hooks.txt:2536
FormatJson\FORCE_ASSOC
const FORCE_ASSOC
If set, treat json objects '{...}' as associative arrays.
Definition: FormatJson.php:64
ApiCSPReport\logReport
logReport( $flags, $logLine, $context)
Log CSP report, with a different severity depending on $flags.
Definition: ApiCSPReport.php:70
$line
$line
Definition: cdb.php:58
ApiCSPReport\execute
execute()
Logs a content-security-policy violation report from web browser.
Definition: ApiCSPReport.php:42
ApiCSPReport\getFlags
getFlags( $report)
Get extra notes about the report.
Definition: ApiCSPReport.php:86
wfEscapeWikiText
wfEscapeWikiText( $text)
Escapes the given text so that it may be output using addWikiText() without any linking,...
Definition: GlobalFunctions.php:1657
FormatJson\parse
static parse( $value, $options=0)
Decodes a JSON string.
Definition: FormatJson.php:201
$code
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output modifiable & $code
Definition: hooks.txt:783
ApiCSPReport\verifyPostBodyOk
verifyPostBodyOk()
Output an api error if post body is obviously not OK.
Definition: ApiCSPReport.php:114
ApiBase\PARAM_DFLT
const PARAM_DFLT
(null|boolean|integer|string) Default value of the parameter.
Definition: ApiBase.php:52
ApiBase\getParameter
getParameter( $paramName, $parseLimit=true)
Get a value for the given parameter.
Definition: ApiBase.php:742
ApiBase\getModuleName
getModuleName()
Get the name of the module being executed by this instance.
Definition: ApiBase.php:490
LoggerFactory
MediaWiki Logger LoggerFactory implements a PSR[0] compatible message logging system Named Psr Log LoggerInterface instances can be obtained from the MediaWiki Logger LoggerFactory::getInstance() static method. MediaWiki\Logger\LoggerFactory expects a class implementing the MediaWiki\Logger\Spi interface to act as a factory for new Psr\Log\LoggerInterface instances. The "Spi" in MediaWiki\Logger\Spi stands for "service provider interface". An SPI is an API intended to be implemented or extended by a third party. This software design pattern is intended to enable framework extension and replaceable components. It is specifically used in the MediaWiki\Logger\LoggerFactory service to allow alternate PSR-3 logging implementations to be easily integrated with MediaWiki. The service provider interface allows the backend logging library to be implemented in multiple ways. The $wgMWLoggerDefaultSpi global provides the classname of the default MediaWiki\Logger\Spi implementation to be loaded at runtime. This can either be the name of a class implementing the MediaWiki\Logger\Spi with a zero argument const ructor or a callable that will return an MediaWiki\Logger\Spi instance. Alternately the MediaWiki\Logger\LoggerFactory MediaWiki Logger LoggerFactory
Definition: logger.txt:5
$source
$source
Definition: mwdoc-filter.php:45
ApiCSPReport\error
error( $code, $method)
Stop processing the request, and output/log an error.
Definition: ApiCSPReport.php:184
ApiCSPReport\MAX_POST_SIZE
const MAX_POST_SIZE
These reports should be small.
Definition: ApiCSPReport.php:37
ApiCSPReport\generateLogLine
generateLogLine( $flags, $report)
Get text of log line.
Definition: ApiCSPReport.php:162
$flags
it s the revision text itself In either if gzip is the revision text is gzipped $flags
Definition: hooks.txt:2749