ApiCSPReport: Log user ID instead of name, and limit urls to origin
[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, $userAgent );
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_id' => $this->getUser()->getId() || 'logged-out',
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 array $flags Flags for this report
67 * @param string $logLine text of log entry
68 * @param array $context 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 array $report The CSP report
84 * @param string $userAgent
85 * @return array
86 */
87 private function getFlags( $report, $userAgent ) {
88 $reportOnly = $this->getParameter( 'reportonly' );
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 (
102 ContentSecurityPolicy::falsePositiveBrowser( $userAgent ) &&
103 $report['blocked-uri'] === "self"
104 ) ||
105 (
106 isset( $report['blocked-uri'] ) &&
107 isset( $falsePositives[$report['blocked-uri']] )
108 ) ||
109 (
110 isset( $report['source-file'] ) &&
111 isset( $falsePositives[$report['source-file']] )
112 )
113 ) {
114 // False positive due to:
115 // https://bugzilla.mozilla.org/show_bug.cgi?id=1026520
116
117 $flags[] = 'false-positive';
118 }
119 return $flags;
120 }
121
122 /**
123 * Output an api error if post body is obviously not OK.
124 */
125 private function verifyPostBodyOk() {
126 $req = $this->getRequest();
127 $contentType = $req->getHeader( 'content-type' );
128 if ( $contentType !== 'application/json'
129 && $contentType !== 'application/csp-report'
130 ) {
131 $this->error( 'wrongformat', __METHOD__ );
132 }
133 if ( $req->getHeader( 'content-length' ) > self::MAX_POST_SIZE ) {
134 $this->error( 'toobig', __METHOD__ );
135 }
136 }
137
138 /**
139 * Get the report from post body and turn into associative array.
140 *
141 * @return array
142 */
143 private function getReport() {
144 $postBody = $this->getRequest()->getRawInput();
145 if ( strlen( $postBody ) > self::MAX_POST_SIZE ) {
146 // paranoia, already checked content-length earlier.
147 $this->error( 'toobig', __METHOD__ );
148 }
149 $status = FormatJson::parse( $postBody, FormatJson::FORCE_ASSOC );
150 if ( !$status->isGood() ) {
151 $msg = $status->getErrors()[0]['message'];
152 if ( $msg instanceof Message ) {
153 $msg = $msg->getKey();
154 }
155 $this->error( $msg, __METHOD__ );
156 }
157
158 $report = $status->getValue();
159
160 if ( !isset( $report['csp-report'] ) ) {
161 $this->error( 'missingkey', __METHOD__ );
162 }
163 return $report['csp-report'];
164 }
165
166 /**
167 * Get text of log line.
168 *
169 * @param array $flags of additional markers for this report
170 * @param array $report the csp report
171 * @return string Text to put in log
172 */
173 private function generateLogLine( $flags, $report ) {
174 $flagText = '';
175 if ( $flags ) {
176 $flagText = '[' . implode( ', ', $flags ) . ']';
177 }
178
179 $blockedOrigin = isset( $report['blocked-uri'] )
180 ? $this->originFromUrl( $report['blocked-uri'] )
181 : 'n/a';
182 $page = $report['document-uri'] ?? 'n/a';
183 $line = isset( $report['line-number'] )
184 ? ':' . $report['line-number']
185 : '';
186 $warningText = $flagText .
187 ' Received CSP report: <' . $blockedOrigin . '>' .
188 ' blocked from being loaded on <' . $page . '>' . $line;
189 return $warningText;
190 }
191
192 /**
193 * @param string $url
194 * @return string
195 */
196 private function originFromUrl( $url ) {
197 $bits = wfParseUrl( $url );
198 unset( $bits['user'], $bits['pass'], $bits['query'], $bits['fragment'] );
199 $bits['path'] = '';
200 $serverUrl = wfAssembleUrl( $bits );
201 // e.g. "https://example.org" from "https://example.org/foo/b?a#r"
202 return $serverUrl;
203 }
204
205 /**
206 * Stop processing the request, and output/log an error
207 *
208 * @param string $code error code
209 * @param string $method method that made error
210 * @throws ApiUsageException Always
211 */
212 private function error( $code, $method ) {
213 $this->log->info( 'Error reading CSP report: ' . $code, [
214 'method' => $method,
215 'user-agent' => $this->getRequest()->getHeader( 'user-agent' )
216 ] );
217 // Return 400 on error for user agents to display, e.g. to the console.
218 $this->dieWithError(
219 [ 'apierror-csp-report', wfEscapeWikiText( $code ) ], 'cspreport-' . $code, [], 400
220 );
221 }
222
223 public function getAllowedParams() {
224 return [
225 'reportonly' => [
226 ApiBase::PARAM_TYPE => 'boolean',
227 ApiBase::PARAM_DFLT => false
228 ],
229 'source' => [
230 ApiBase::PARAM_TYPE => 'string',
231 ApiBase::PARAM_DFLT => 'internal',
232 ApiBase::PARAM_REQUIRED => false
233 ]
234 ];
235 }
236
237 public function mustBePosted() {
238 return true;
239 }
240
241 public function isWriteMode() {
242 return false;
243 }
244
245 /**
246 * Mark as internal. This isn't meant to be used by normal api users
247 * @return bool
248 */
249 public function isInternal() {
250 return true;
251 }
252
253 /**
254 * Even if you don't have read rights, we still want your report.
255 * @return bool
256 */
257 public function isReadMode() {
258 return false;
259 }
260
261 /**
262 * Doesn't touch db, so max lag should be rather irrelavent.
263 *
264 * Also, this makes sure that reports aren't lost during lag events.
265 * @return bool
266 */
267 public function shouldCheckMaxLag() {
268 return false;
269 }
270 }