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