Replace DatabaseBase:: with Database:: and update type hints
[lhc/web/wiklou.git] / includes / api / ApiCSPReport.php
1 <?php
2 /**
3 * Copyright © 2015 Brian Wolff
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 */
22
23 use MediaWiki\Logger\LoggerFactory;
24
25 /**
26 * Api module to receive and log CSP violation reports
27 *
28 * @ingroup API
29 */
30 class ApiCSPReport extends ApiBase {
31
32 private $log;
33
34 /**
35 * These reports should be small. Ignore super big reports out of paranoia
36 */
37 const MAX_POST_SIZE = 8192;
38
39 /**
40 * Logs a content-security-policy violation report from web browser.
41 */
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
64 /**
65 * Log CSP report, with a different severity depending on $flags
66 * @param $flags Array Flags for this report
67 * @param $logLine String text of log entry
68 * @param $context Array logging context
69 */
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
80 /**
81 * Get extra notes about the report.
82 *
83 * @param $report Array The CSP report
84 * @return Array
85 */
86 private function getFlags( $report ) {
87 $reportOnly = $this->getParameter( 'reportonly' );
88 $userAgent = $this->getRequest()->getHeader( 'user-agent' );
89 $source = $this->getParameter( 'source' );
90 $falsePositives = $this->getConfig()->get( 'CSPFalsePositiveUrls' );
91
92 $flags = [];
93 if ( $source !== 'internal' ) {
94 $flags[] = 'source=' . $source;
95 }
96 if ( $reportOnly ) {
97 $flags[] = 'report-only';
98 }
99
100 if (
101 ( isset( $report['blocked-uri'] ) &&
102 isset( $falsePositives[$report['blocked-uri']] ) )
103 || ( isset( $report['source-file'] ) &&
104 isset( $falsePositives[$report['source-file']] ) )
105 ) {
106 // Report caused by Ad-Ware
107 $flags[] = 'false-positive';
108 }
109 return $flags;
110 }
111
112 /**
113 * Output an api error if post body is obviously not OK.
114 */
115 private function verifyPostBodyOk() {
116 $req = $this->getRequest();
117 $contentType = $req->getHeader( 'content-type' );
118 if ( $contentType !== 'application/json'
119 && $contentType !=='application/csp-report'
120 ) {
121 $this->error( 'wrongformat', __METHOD__ );
122 }
123 if ( $req->getHeader( 'content-length' ) > self::MAX_POST_SIZE ) {
124 $this->error( 'toobig', __METHOD__ );
125 }
126 }
127
128 /**
129 * Get the report from post body and turn into associative array.
130 *
131 * @return Array
132 */
133 private function getReport() {
134 $postBody = $this->getRequest()->getRawInput();
135 if ( strlen( $postBody ) > self::MAX_POST_SIZE ) {
136 // paranoia, already checked content-length earlier.
137 $this->error( 'toobig', __METHOD__ );
138 }
139 $status = FormatJson::parse( $postBody, FormatJson::FORCE_ASSOC );
140 if ( !$status->isGood() ) {
141 list( $code, ) = $this->getErrorFromStatus( $status );
142 $this->error( $code, __METHOD__ );
143 }
144
145 $report = $status->getValue();
146
147 if ( !isset( $report['csp-report'] ) ) {
148 $this->error( 'missingkey', __METHOD__ );
149 }
150 return $report['csp-report'];
151 }
152
153 /**
154 * Get text of log line.
155 *
156 * @param $flags Array of additional markers for this report
157 * @param $report Array the csp report
158 * @return String Text to put in log
159 */
160 private function generateLogLine( $flags, $report ) {
161 $flagText = '';
162 if ( $flags ) {
163 $flagText = '[' . implode( $flags, ', ' ) . ']';
164 }
165
166 $blockedFile = isset( $report['blocked-uri'] ) ? $report['blocked-uri'] : 'n/a';
167 $page = isset( $report['document-uri'] ) ? $report['document-uri'] : 'n/a';
168 $line = isset( $report['line-number'] ) ? ':' . $report['line-number'] : '';
169 $warningText = $flagText .
170 ' Received CSP report: <' . $blockedFile .
171 '> blocked from being loaded on <' . $page . '>' . $line;
172 return $warningText;
173 }
174
175 /**
176 * Stop processing the request, and output/log an error
177 *
178 * @param $code String error code
179 * @param $method String method that made error
180 * @throws UsageException Always
181 */
182 private function error( $code, $method ) {
183 $this->log->info( 'Error reading CSP report: ' . $code, [
184 'method' => $method,
185 'user-agent' => $this->getRequest()->getHeader( 'user-agent' )
186 ] );
187 // 500 so it shows up in browser's developer console.
188 $this->dieUsage( "Error processing CSP report: $code", 'cspreport-' . $code, 500 );
189 }
190
191 public function getAllowedParams() {
192 return [
193 'reportonly' => [
194 ApiBase::PARAM_TYPE => 'boolean',
195 ApiBase::PARAM_DFLT => false
196 ],
197 'source' => [
198 ApiBase::PARAM_TYPE => 'string',
199 ApiBase::PARAM_DFLT => 'internal',
200 ApiBase::PARAM_REQUIRED => false
201 ]
202 ];
203 }
204
205 public function mustBePosted() {
206 return true;
207 }
208
209 public function isWriteMode() {
210 return false;
211 }
212
213 /**
214 * Mark as internal. This isn't meant to be used by normal api users
215 */
216 public function isInternal() {
217 return true;
218 }
219
220 /**
221 * Even if you don't have read rights, we still want your report.
222 */
223 public function isReadMode() {
224 return false;
225 }
226
227 /**
228 * Doesn't touch db, so max lag should be rather irrelavent.
229 *
230 * Also, this makes sure that reports aren't lost during lag events.
231 */
232 public function shouldCheckMaxLag() {
233 return false;
234 }
235 }