Passed
Push — master ( aa785d...4a0272 )
by Joas
19:11 queued 16s
created

CORSMiddleware::beforeController()   B

Complexity

Conditions 9
Paths 13

Size

Total Lines 14
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
cc 9
eloc 9
c 1
b 1
f 0
nc 13
nop 2
dl 0
loc 14
rs 8.0555
1
<?php
2
/**
3
 * @copyright Copyright (c) 2016, ownCloud, Inc.
4
 *
5
 * @author Bernhard Posselt <[email protected]>
6
 * @author Christoph Wurst <[email protected]>
7
 * @author Lukas Reschke <[email protected]>
8
 * @author Morris Jobke <[email protected]>
9
 * @author Stefan Weil <[email protected]>
10
 *
11
 * @license AGPL-3.0
12
 *
13
 * This code is free software: you can redistribute it and/or modify
14
 * it under the terms of the GNU Affero General Public License, version 3,
15
 * as published by the Free Software Foundation.
16
 *
17
 * This program is distributed in the hope that it will be useful,
18
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20
 * GNU Affero General Public License for more details.
21
 *
22
 * You should have received a copy of the GNU Affero General Public License, version 3,
23
 * along with this program. If not, see <http://www.gnu.org/licenses/>
24
 *
25
 */
26
27
namespace OC\AppFramework\Middleware\Security;
28
29
use OC\AppFramework\Middleware\Security\Exceptions\SecurityException;
30
use OC\AppFramework\Utility\ControllerMethodReflector;
31
use OC\Authentication\Exceptions\PasswordLoginForbiddenException;
32
use OC\Security\Bruteforce\Throttler;
33
use OC\User\Session;
34
use OCP\AppFramework\Controller;
35
use OCP\AppFramework\Http;
36
use OCP\AppFramework\Http\JSONResponse;
37
use OCP\AppFramework\Http\Response;
38
use OCP\AppFramework\Middleware;
39
use OCP\IRequest;
40
41
/**
42
 * This middleware sets the correct CORS headers on a response if the
43
 * controller has the @CORS annotation. This is needed for webapps that want
44
 * to access an API and don't run on the same domain, see
45
 * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
46
 */
47
class CORSMiddleware extends Middleware {
48
	/** @var IRequest  */
49
	private $request;
50
	/** @var ControllerMethodReflector */
51
	private $reflector;
52
	/** @var Session */
53
	private $session;
54
	/** @var Throttler */
55
	private $throttler;
56
57
	/**
58
	 * @param IRequest $request
59
	 * @param ControllerMethodReflector $reflector
60
	 * @param Session $session
61
	 * @param Throttler $throttler
62
	 */
63
	public function __construct(IRequest $request,
64
								ControllerMethodReflector $reflector,
65
								Session $session,
66
								Throttler $throttler) {
67
		$this->request = $request;
68
		$this->reflector = $reflector;
69
		$this->session = $session;
70
		$this->throttler = $throttler;
71
	}
72
73
	/**
74
	 * This is being run in normal order before the controller is being
75
	 * called which allows several modifications and checks
76
	 *
77
	 * @param Controller $controller the controller that is being called
78
	 * @param string $methodName the name of the method that will be called on
79
	 *                           the controller
80
	 * @throws SecurityException
81
	 * @since 6.0.0
82
	 */
83
	public function beforeController($controller, $methodName) {
84
		// ensure that @CORS annotated API routes are not used in conjunction
85
		// with session authentication since this enables CSRF attack vectors
86
		if ($this->reflector->hasAnnotation('CORS') && !$this->reflector->hasAnnotation('PublicPage')) {
87
			$user = array_key_exists('PHP_AUTH_USER', $this->request->server) ? $this->request->server['PHP_AUTH_USER'] : null;
88
			$pass = array_key_exists('PHP_AUTH_PW', $this->request->server) ? $this->request->server['PHP_AUTH_PW'] : null;
89
90
			$this->session->logout();
91
			try {
92
				if ($user === null || $pass === null || !$this->session->logClientIn($user, $pass, $this->request, $this->throttler)) {
93
					throw new SecurityException('CORS requires basic auth', Http::STATUS_UNAUTHORIZED);
94
				}
95
			} catch (PasswordLoginForbiddenException $ex) {
96
				throw new SecurityException('Password login forbidden, use token instead', Http::STATUS_UNAUTHORIZED);
97
			}
98
		}
99
	}
100
101
	/**
102
	 * This is being run after a successful controllermethod call and allows
103
	 * the manipulation of a Response object. The middleware is run in reverse order
104
	 *
105
	 * @param Controller $controller the controller that is being called
106
	 * @param string $methodName the name of the method that will be called on
107
	 *                           the controller
108
	 * @param Response $response the generated response from the controller
109
	 * @return Response a Response object
110
	 * @throws SecurityException
111
	 */
112
	public function afterController($controller, $methodName, Response $response) {
113
		// only react if its a CORS request and if the request sends origin and
114
115
		if (isset($this->request->server['HTTP_ORIGIN']) &&
116
			$this->reflector->hasAnnotation('CORS')) {
117
118
			// allow credentials headers must not be true or CSRF is possible
119
			// otherwise
120
			foreach ($response->getHeaders() as $header => $value) {
121
				if (strtolower($header) === 'access-control-allow-credentials' &&
122
				   strtolower(trim($value)) === 'true') {
123
					$msg = 'Access-Control-Allow-Credentials must not be '.
124
						   'set to true in order to prevent CSRF';
125
					throw new SecurityException($msg);
126
				}
127
			}
128
129
			$origin = $this->request->server['HTTP_ORIGIN'];
130
			$response->addHeader('Access-Control-Allow-Origin', $origin);
131
		}
132
		return $response;
133
	}
134
135
	/**
136
	 * If an SecurityException is being caught return a JSON error response
137
	 *
138
	 * @param Controller $controller the controller that is being called
139
	 * @param string $methodName the name of the method that will be called on
140
	 *                           the controller
141
	 * @param \Exception $exception the thrown exception
142
	 * @throws \Exception the passed in exception if it can't handle it
143
	 * @return Response a Response object or null in case that the exception could not be handled
144
	 */
145
	public function afterException($controller, $methodName, \Exception $exception) {
146
		if ($exception instanceof SecurityException) {
147
			$response = new JSONResponse(['message' => $exception->getMessage()]);
148
			if ($exception->getCode() !== 0) {
149
				$response->setStatus($exception->getCode());
150
			} else {
151
				$response->setStatus(Http::STATUS_INTERNAL_SERVER_ERROR);
152
			}
153
			return $response;
154
		}
155
156
		throw $exception;
157
	}
158
}
159