Passed
Push — master ( d60172...75f17b )
by Joas
16:26 queued 12s
created

CORSMiddleware   A

Complexity

Total Complexity 24

Size/Duplication

Total Lines 139
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 47
dl 0
loc 139
rs 10
c 0
b 0
f 0
wmc 24

5 Methods

Rating   Name   Duplication   Size   Complexity  
A afterController() 0 22 6
A hasAnnotationOrAttribute() 0 11 3
A afterException() 0 12 3
B beforeController() 0 21 11
A __construct() 0 8 1
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 korelstar <[email protected]>
8
 * @author Lukas Reschke <[email protected]>
9
 * @author Morris Jobke <[email protected]>
10
 * @author Stefan Weil <[email protected]>
11
 *
12
 * @license AGPL-3.0
13
 *
14
 * This code is free software: you can redistribute it and/or modify
15
 * it under the terms of the GNU Affero General Public License, version 3,
16
 * as published by the Free Software Foundation.
17
 *
18
 * This program is distributed in the hope that it will be useful,
19
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21
 * GNU Affero General Public License for more details.
22
 *
23
 * You should have received a copy of the GNU Affero General Public License, version 3,
24
 * along with this program. If not, see <http://www.gnu.org/licenses/>
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\Attribute\CORS;
37
use OCP\AppFramework\Http\Attribute\PublicPage;
38
use OCP\AppFramework\Http\JSONResponse;
39
use OCP\AppFramework\Http\Response;
40
use OCP\AppFramework\Middleware;
41
use OCP\IRequest;
42
use ReflectionMethod;
43
44
/**
45
 * This middleware sets the correct CORS headers on a response if the
46
 * controller has the @CORS annotation. This is needed for webapps that want
47
 * to access an API and don't run on the same domain, see
48
 * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
49
 */
50
class CORSMiddleware extends Middleware {
51
	/** @var IRequest  */
52
	private $request;
53
	/** @var ControllerMethodReflector */
54
	private $reflector;
55
	/** @var Session */
56
	private $session;
57
	/** @var Throttler */
58
	private $throttler;
59
60
	/**
61
	 * @param IRequest $request
62
	 * @param ControllerMethodReflector $reflector
63
	 * @param Session $session
64
	 * @param Throttler $throttler
65
	 */
66
	public function __construct(IRequest $request,
67
								ControllerMethodReflector $reflector,
68
								Session $session,
69
								Throttler $throttler) {
70
		$this->request = $request;
71
		$this->reflector = $reflector;
72
		$this->session = $session;
73
		$this->throttler = $throttler;
74
	}
75
76
	/**
77
	 * This is being run in normal order before the controller is being
78
	 * called which allows several modifications and checks
79
	 *
80
	 * @param Controller $controller the controller that is being called
81
	 * @param string $methodName the name of the method that will be called on
82
	 *                           the controller
83
	 * @throws SecurityException
84
	 * @since 6.0.0
85
	 */
86
	public function beforeController($controller, $methodName) {
87
		$reflectionMethod = new ReflectionMethod($controller, $methodName);
88
89
		// ensure that @CORS annotated API routes are not used in conjunction
90
		// with session authentication since this enables CSRF attack vectors
91
		if ($this->hasAnnotationOrAttribute($reflectionMethod, 'CORS', CORS::class) &&
92
			(!$this->hasAnnotationOrAttribute($reflectionMethod, 'PublicPage', PublicPage::class) || $this->session->isLoggedIn())) {
93
			$user = array_key_exists('PHP_AUTH_USER', $this->request->server) ? $this->request->server['PHP_AUTH_USER'] : null;
94
			$pass = array_key_exists('PHP_AUTH_PW', $this->request->server) ? $this->request->server['PHP_AUTH_PW'] : null;
95
96
			// Allow to use the current session if a CSRF token is provided
97
			if ($this->request->passesCSRFCheck()) {
98
				return;
99
			}
100
			$this->session->logout();
101
			try {
102
				if ($user === null || $pass === null || !$this->session->logClientIn($user, $pass, $this->request, $this->throttler)) {
103
					throw new SecurityException('CORS requires basic auth', Http::STATUS_UNAUTHORIZED);
104
				}
105
			} catch (PasswordLoginForbiddenException $ex) {
106
				throw new SecurityException('Password login forbidden, use token instead', Http::STATUS_UNAUTHORIZED);
107
			}
108
		}
109
	}
110
111
	/**
112
	 * @template T
113
	 *
114
	 * @param ReflectionMethod $reflectionMethod
115
	 * @param string $annotationName
116
	 * @param class-string<T> $attributeClass
0 ignored issues
show
Documentation Bug introduced by
The doc comment class-string<T> at position 0 could not be parsed: Unknown type name 'class-string' at position 0 in class-string<T>.
Loading history...
117
	 * @return boolean
118
	 */
119
	protected function hasAnnotationOrAttribute(ReflectionMethod $reflectionMethod, string $annotationName, string $attributeClass): bool {
120
		if ($this->reflector->hasAnnotation($annotationName)) {
121
			return true;
122
		}
123
124
125
		if (!empty($reflectionMethod->getAttributes($attributeClass))) {
126
			return true;
127
		}
128
129
		return false;
130
	}
131
132
	/**
133
	 * This is being run after a successful controller method call and allows
134
	 * the manipulation of a Response object. The middleware is run in reverse order
135
	 *
136
	 * @param Controller $controller the controller that is being called
137
	 * @param string $methodName the name of the method that will be called on
138
	 *                           the controller
139
	 * @param Response $response the generated response from the controller
140
	 * @return Response a Response object
141
	 * @throws SecurityException
142
	 */
143
	public function afterController($controller, $methodName, Response $response) {
144
		// only react if it's a CORS request and if the request sends origin and
145
146
		if (isset($this->request->server['HTTP_ORIGIN'])) {
147
			$reflectionMethod = new ReflectionMethod($controller, $methodName);
148
			if ($this->hasAnnotationOrAttribute($reflectionMethod, 'CORS', CORS::class)) {
149
				// allow credentials headers must not be true or CSRF is possible
150
				// otherwise
151
				foreach ($response->getHeaders() as $header => $value) {
152
					if (strtolower($header) === 'access-control-allow-credentials' &&
153
					   strtolower(trim($value)) === 'true') {
154
						$msg = 'Access-Control-Allow-Credentials must not be '.
155
							   'set to true in order to prevent CSRF';
156
						throw new SecurityException($msg);
157
					}
158
				}
159
160
				$origin = $this->request->server['HTTP_ORIGIN'];
161
				$response->addHeader('Access-Control-Allow-Origin', $origin);
162
			}
163
		}
164
		return $response;
165
	}
166
167
	/**
168
	 * If an SecurityException is being caught return a JSON error response
169
	 *
170
	 * @param Controller $controller the controller that is being called
171
	 * @param string $methodName the name of the method that will be called on
172
	 *                           the controller
173
	 * @param \Exception $exception the thrown exception
174
	 * @throws \Exception the passed in exception if it can't handle it
175
	 * @return Response a Response object or null in case that the exception could not be handled
176
	 */
177
	public function afterException($controller, $methodName, \Exception $exception) {
178
		if ($exception instanceof SecurityException) {
179
			$response = new JSONResponse(['message' => $exception->getMessage()]);
180
			if ($exception->getCode() !== 0) {
181
				$response->setStatus($exception->getCode());
182
			} else {
183
				$response->setStatus(Http::STATUS_INTERNAL_SERVER_ERROR);
184
			}
185
			return $response;
186
		}
187
188
		throw $exception;
189
	}
190
}
191