Completed
Push — master ( 069e3f...a2db95 )
by Morris
19:57
created
lib/private/AppFramework/Middleware/Security/SecurityMiddleware.php 2 patches
Indentation   +173 added lines, -173 removed lines patch added patch discarded remove patch
@@ -66,98 +66,98 @@  discard block
 block discarded – undo
66 66
  * check fails
67 67
  */
68 68
 class SecurityMiddleware extends Middleware {
69
-	/** @var INavigationManager */
70
-	private $navigationManager;
71
-	/** @var IRequest */
72
-	private $request;
73
-	/** @var ControllerMethodReflector */
74
-	private $reflector;
75
-	/** @var string */
76
-	private $appName;
77
-	/** @var IURLGenerator */
78
-	private $urlGenerator;
79
-	/** @var ILogger */
80
-	private $logger;
81
-	/** @var bool */
82
-	private $isLoggedIn;
83
-	/** @var bool */
84
-	private $isAdminUser;
85
-	/** @var ContentSecurityPolicyManager */
86
-	private $contentSecurityPolicyManager;
87
-	/** @var CsrfTokenManager */
88
-	private $csrfTokenManager;
89
-	/** @var ContentSecurityPolicyNonceManager */
90
-	private $cspNonceManager;
91
-	/** @var IAppManager */
92
-	private $appManager;
93
-	/** @var IL10N */
94
-	private $l10n;
69
+    /** @var INavigationManager */
70
+    private $navigationManager;
71
+    /** @var IRequest */
72
+    private $request;
73
+    /** @var ControllerMethodReflector */
74
+    private $reflector;
75
+    /** @var string */
76
+    private $appName;
77
+    /** @var IURLGenerator */
78
+    private $urlGenerator;
79
+    /** @var ILogger */
80
+    private $logger;
81
+    /** @var bool */
82
+    private $isLoggedIn;
83
+    /** @var bool */
84
+    private $isAdminUser;
85
+    /** @var ContentSecurityPolicyManager */
86
+    private $contentSecurityPolicyManager;
87
+    /** @var CsrfTokenManager */
88
+    private $csrfTokenManager;
89
+    /** @var ContentSecurityPolicyNonceManager */
90
+    private $cspNonceManager;
91
+    /** @var IAppManager */
92
+    private $appManager;
93
+    /** @var IL10N */
94
+    private $l10n;
95 95
 
96
-	public function __construct(IRequest $request,
97
-								ControllerMethodReflector $reflector,
98
-								INavigationManager $navigationManager,
99
-								IURLGenerator $urlGenerator,
100
-								ILogger $logger,
101
-								string $appName,
102
-								bool $isLoggedIn,
103
-								bool $isAdminUser,
104
-								ContentSecurityPolicyManager $contentSecurityPolicyManager,
105
-								CsrfTokenManager $csrfTokenManager,
106
-								ContentSecurityPolicyNonceManager $cspNonceManager,
107
-								IAppManager $appManager,
108
-								IL10N $l10n
109
-	) {
110
-		$this->navigationManager = $navigationManager;
111
-		$this->request = $request;
112
-		$this->reflector = $reflector;
113
-		$this->appName = $appName;
114
-		$this->urlGenerator = $urlGenerator;
115
-		$this->logger = $logger;
116
-		$this->isLoggedIn = $isLoggedIn;
117
-		$this->isAdminUser = $isAdminUser;
118
-		$this->contentSecurityPolicyManager = $contentSecurityPolicyManager;
119
-		$this->csrfTokenManager = $csrfTokenManager;
120
-		$this->cspNonceManager = $cspNonceManager;
121
-		$this->appManager = $appManager;
122
-		$this->l10n = $l10n;
123
-	}
96
+    public function __construct(IRequest $request,
97
+                                ControllerMethodReflector $reflector,
98
+                                INavigationManager $navigationManager,
99
+                                IURLGenerator $urlGenerator,
100
+                                ILogger $logger,
101
+                                string $appName,
102
+                                bool $isLoggedIn,
103
+                                bool $isAdminUser,
104
+                                ContentSecurityPolicyManager $contentSecurityPolicyManager,
105
+                                CsrfTokenManager $csrfTokenManager,
106
+                                ContentSecurityPolicyNonceManager $cspNonceManager,
107
+                                IAppManager $appManager,
108
+                                IL10N $l10n
109
+    ) {
110
+        $this->navigationManager = $navigationManager;
111
+        $this->request = $request;
112
+        $this->reflector = $reflector;
113
+        $this->appName = $appName;
114
+        $this->urlGenerator = $urlGenerator;
115
+        $this->logger = $logger;
116
+        $this->isLoggedIn = $isLoggedIn;
117
+        $this->isAdminUser = $isAdminUser;
118
+        $this->contentSecurityPolicyManager = $contentSecurityPolicyManager;
119
+        $this->csrfTokenManager = $csrfTokenManager;
120
+        $this->cspNonceManager = $cspNonceManager;
121
+        $this->appManager = $appManager;
122
+        $this->l10n = $l10n;
123
+    }
124 124
 
125
-	/**
126
-	 * This runs all the security checks before a method call. The
127
-	 * security checks are determined by inspecting the controller method
128
-	 * annotations
129
-	 * @param Controller $controller the controller
130
-	 * @param string $methodName the name of the method
131
-	 * @throws SecurityException when a security check fails
132
-	 */
133
-	public function beforeController($controller, $methodName) {
125
+    /**
126
+     * This runs all the security checks before a method call. The
127
+     * security checks are determined by inspecting the controller method
128
+     * annotations
129
+     * @param Controller $controller the controller
130
+     * @param string $methodName the name of the method
131
+     * @throws SecurityException when a security check fails
132
+     */
133
+    public function beforeController($controller, $methodName) {
134 134
 
135
-		// this will set the current navigation entry of the app, use this only
136
-		// for normal HTML requests and not for AJAX requests
137
-		$this->navigationManager->setActiveEntry($this->appName);
135
+        // this will set the current navigation entry of the app, use this only
136
+        // for normal HTML requests and not for AJAX requests
137
+        $this->navigationManager->setActiveEntry($this->appName);
138 138
 
139
-		// security checks
140
-		$isPublicPage = $this->reflector->hasAnnotation('PublicPage');
141
-		if(!$isPublicPage) {
142
-			if(!$this->isLoggedIn) {
143
-				throw new NotLoggedInException();
144
-			}
139
+        // security checks
140
+        $isPublicPage = $this->reflector->hasAnnotation('PublicPage');
141
+        if(!$isPublicPage) {
142
+            if(!$this->isLoggedIn) {
143
+                throw new NotLoggedInException();
144
+            }
145 145
 
146
-			if(!$this->reflector->hasAnnotation('NoAdminRequired') && !$this->isAdminUser) {
147
-				throw new NotAdminException($this->l10n->t('Logged in user must be an admin'));
148
-			}
149
-		}
146
+            if(!$this->reflector->hasAnnotation('NoAdminRequired') && !$this->isAdminUser) {
147
+                throw new NotAdminException($this->l10n->t('Logged in user must be an admin'));
148
+            }
149
+        }
150 150
 
151
-		// Check for strict cookie requirement
152
-		if($this->reflector->hasAnnotation('StrictCookieRequired') || !$this->reflector->hasAnnotation('NoCSRFRequired')) {
153
-			if(!$this->request->passesStrictCookieCheck()) {
154
-				throw new StrictCookieMissingException();
155
-			}
156
-		}
157
-		// CSRF check - also registers the CSRF token since the session may be closed later
158
-		Util::callRegister();
159
-		if(!$this->reflector->hasAnnotation('NoCSRFRequired')) {
160
-			/*
151
+        // Check for strict cookie requirement
152
+        if($this->reflector->hasAnnotation('StrictCookieRequired') || !$this->reflector->hasAnnotation('NoCSRFRequired')) {
153
+            if(!$this->request->passesStrictCookieCheck()) {
154
+                throw new StrictCookieMissingException();
155
+            }
156
+        }
157
+        // CSRF check - also registers the CSRF token since the session may be closed later
158
+        Util::callRegister();
159
+        if(!$this->reflector->hasAnnotation('NoCSRFRequired')) {
160
+            /*
161 161
 			 * Only allow the CSRF check to fail on OCS Requests. This kind of
162 162
 			 * hacks around that we have no full token auth in place yet and we
163 163
 			 * do want to offer CSRF checks for web requests.
@@ -165,103 +165,103 @@  discard block
 block discarded – undo
165 165
 			 * Additionally we allow Bearer authenticated requests to pass on OCS routes.
166 166
 			 * This allows oauth apps (e.g. moodle) to use the OCS endpoints
167 167
 			 */
168
-			if(!$this->request->passesCSRFCheck() && !(
169
-					$controller instanceof OCSController && (
170
-						$this->request->getHeader('OCS-APIREQUEST') === 'true' ||
171
-						strpos($this->request->getHeader('Authorization'), 'Bearer ') === 0
172
-					)
173
-				)) {
174
-				throw new CrossSiteRequestForgeryException();
175
-			}
176
-		}
168
+            if(!$this->request->passesCSRFCheck() && !(
169
+                    $controller instanceof OCSController && (
170
+                        $this->request->getHeader('OCS-APIREQUEST') === 'true' ||
171
+                        strpos($this->request->getHeader('Authorization'), 'Bearer ') === 0
172
+                    )
173
+                )) {
174
+                throw new CrossSiteRequestForgeryException();
175
+            }
176
+        }
177 177
 
178
-		/**
179
-		 * Checks if app is enabled (also includes a check whether user is allowed to access the resource)
180
-		 * The getAppPath() check is here since components such as settings also use the AppFramework and
181
-		 * therefore won't pass this check.
182
-		 * If page is public, app does not need to be enabled for current user/visitor
183
-		 */
184
-		try {
185
-			$appPath = $this->appManager->getAppPath($this->appName);
186
-		} catch (AppPathNotFoundException $e) {
187
-			$appPath = false;
188
-		}
178
+        /**
179
+         * Checks if app is enabled (also includes a check whether user is allowed to access the resource)
180
+         * The getAppPath() check is here since components such as settings also use the AppFramework and
181
+         * therefore won't pass this check.
182
+         * If page is public, app does not need to be enabled for current user/visitor
183
+         */
184
+        try {
185
+            $appPath = $this->appManager->getAppPath($this->appName);
186
+        } catch (AppPathNotFoundException $e) {
187
+            $appPath = false;
188
+        }
189 189
 
190
-		if ($appPath !== false && !$isPublicPage && !$this->appManager->isEnabledForUser($this->appName)) {
191
-			throw new AppNotEnabledException();
192
-		}
193
-	}
190
+        if ($appPath !== false && !$isPublicPage && !$this->appManager->isEnabledForUser($this->appName)) {
191
+            throw new AppNotEnabledException();
192
+        }
193
+    }
194 194
 
195
-	/**
196
-	 * Performs the default CSP modifications that may be injected by other
197
-	 * applications
198
-	 *
199
-	 * @param Controller $controller
200
-	 * @param string $methodName
201
-	 * @param Response $response
202
-	 * @return Response
203
-	 */
204
-	public function afterController($controller, $methodName, Response $response): Response {
205
-		$policy = !is_null($response->getContentSecurityPolicy()) ? $response->getContentSecurityPolicy() : new ContentSecurityPolicy();
195
+    /**
196
+     * Performs the default CSP modifications that may be injected by other
197
+     * applications
198
+     *
199
+     * @param Controller $controller
200
+     * @param string $methodName
201
+     * @param Response $response
202
+     * @return Response
203
+     */
204
+    public function afterController($controller, $methodName, Response $response): Response {
205
+        $policy = !is_null($response->getContentSecurityPolicy()) ? $response->getContentSecurityPolicy() : new ContentSecurityPolicy();
206 206
 
207
-		if (get_class($policy) === EmptyContentSecurityPolicy::class) {
208
-			return $response;
209
-		}
207
+        if (get_class($policy) === EmptyContentSecurityPolicy::class) {
208
+            return $response;
209
+        }
210 210
 
211
-		$defaultPolicy = $this->contentSecurityPolicyManager->getDefaultPolicy();
212
-		$defaultPolicy = $this->contentSecurityPolicyManager->mergePolicies($defaultPolicy, $policy);
211
+        $defaultPolicy = $this->contentSecurityPolicyManager->getDefaultPolicy();
212
+        $defaultPolicy = $this->contentSecurityPolicyManager->mergePolicies($defaultPolicy, $policy);
213 213
 
214
-		if($this->cspNonceManager->browserSupportsCspV3()) {
215
-			$defaultPolicy->useJsNonce($this->csrfTokenManager->getToken()->getEncryptedValue());
216
-		}
214
+        if($this->cspNonceManager->browserSupportsCspV3()) {
215
+            $defaultPolicy->useJsNonce($this->csrfTokenManager->getToken()->getEncryptedValue());
216
+        }
217 217
 
218
-		$response->setContentSecurityPolicy($defaultPolicy);
218
+        $response->setContentSecurityPolicy($defaultPolicy);
219 219
 
220
-		return $response;
221
-	}
220
+        return $response;
221
+    }
222 222
 
223
-	/**
224
-	 * If an SecurityException is being caught, ajax requests return a JSON error
225
-	 * response and non ajax requests redirect to the index
226
-	 * @param Controller $controller the controller that is being called
227
-	 * @param string $methodName the name of the method that will be called on
228
-	 *                           the controller
229
-	 * @param \Exception $exception the thrown exception
230
-	 * @throws \Exception the passed in exception if it can't handle it
231
-	 * @return Response a Response object or null in case that the exception could not be handled
232
-	 */
233
-	public function afterException($controller, $methodName, \Exception $exception): Response {
234
-		if($exception instanceof SecurityException) {
235
-			if($exception instanceof StrictCookieMissingException) {
236
-				return new RedirectResponse(\OC::$WEBROOT);
237
- 			}
238
-			if (stripos($this->request->getHeader('Accept'),'html') === false) {
239
-				$response = new JSONResponse(
240
-					['message' => $exception->getMessage()],
241
-					$exception->getCode()
242
-				);
243
-			} else {
244
-				if($exception instanceof NotLoggedInException) {
245
-					$params = [];
246
-					if (isset($this->request->server['REQUEST_URI'])) {
247
-						$params['redirect_url'] = $this->request->server['REQUEST_URI'];
248
-					}
249
-					$url = $this->urlGenerator->linkToRoute('core.login.showLoginForm', $params);
250
-					$response = new RedirectResponse($url);
251
-				} else {
252
-					$response = new TemplateResponse('core', '403', ['file' => $exception->getMessage()], 'guest');
253
-					$response->setStatus($exception->getCode());
254
-				}
255
-			}
223
+    /**
224
+     * If an SecurityException is being caught, ajax requests return a JSON error
225
+     * response and non ajax requests redirect to the index
226
+     * @param Controller $controller the controller that is being called
227
+     * @param string $methodName the name of the method that will be called on
228
+     *                           the controller
229
+     * @param \Exception $exception the thrown exception
230
+     * @throws \Exception the passed in exception if it can't handle it
231
+     * @return Response a Response object or null in case that the exception could not be handled
232
+     */
233
+    public function afterException($controller, $methodName, \Exception $exception): Response {
234
+        if($exception instanceof SecurityException) {
235
+            if($exception instanceof StrictCookieMissingException) {
236
+                return new RedirectResponse(\OC::$WEBROOT);
237
+                }
238
+            if (stripos($this->request->getHeader('Accept'),'html') === false) {
239
+                $response = new JSONResponse(
240
+                    ['message' => $exception->getMessage()],
241
+                    $exception->getCode()
242
+                );
243
+            } else {
244
+                if($exception instanceof NotLoggedInException) {
245
+                    $params = [];
246
+                    if (isset($this->request->server['REQUEST_URI'])) {
247
+                        $params['redirect_url'] = $this->request->server['REQUEST_URI'];
248
+                    }
249
+                    $url = $this->urlGenerator->linkToRoute('core.login.showLoginForm', $params);
250
+                    $response = new RedirectResponse($url);
251
+                } else {
252
+                    $response = new TemplateResponse('core', '403', ['file' => $exception->getMessage()], 'guest');
253
+                    $response->setStatus($exception->getCode());
254
+                }
255
+            }
256 256
 
257
-			$this->logger->logException($exception, [
258
-				'level' => \OCP\Util::DEBUG,
259
-				'app' => 'core',
260
-			]);
261
-			return $response;
262
-		}
257
+            $this->logger->logException($exception, [
258
+                'level' => \OCP\Util::DEBUG,
259
+                'app' => 'core',
260
+            ]);
261
+            return $response;
262
+        }
263 263
 
264
-		throw $exception;
265
-	}
264
+        throw $exception;
265
+    }
266 266
 
267 267
 }
Please login to merge, or discard this patch.
Spacing   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php
2
-declare(strict_types=1);
2
+declare(strict_types = 1);
3 3
 /**
4 4
  * @copyright Copyright (c) 2016, ownCloud, Inc.
5 5
  *
@@ -138,25 +138,25 @@  discard block
 block discarded – undo
138 138
 
139 139
 		// security checks
140 140
 		$isPublicPage = $this->reflector->hasAnnotation('PublicPage');
141
-		if(!$isPublicPage) {
142
-			if(!$this->isLoggedIn) {
141
+		if (!$isPublicPage) {
142
+			if (!$this->isLoggedIn) {
143 143
 				throw new NotLoggedInException();
144 144
 			}
145 145
 
146
-			if(!$this->reflector->hasAnnotation('NoAdminRequired') && !$this->isAdminUser) {
146
+			if (!$this->reflector->hasAnnotation('NoAdminRequired') && !$this->isAdminUser) {
147 147
 				throw new NotAdminException($this->l10n->t('Logged in user must be an admin'));
148 148
 			}
149 149
 		}
150 150
 
151 151
 		// Check for strict cookie requirement
152
-		if($this->reflector->hasAnnotation('StrictCookieRequired') || !$this->reflector->hasAnnotation('NoCSRFRequired')) {
153
-			if(!$this->request->passesStrictCookieCheck()) {
152
+		if ($this->reflector->hasAnnotation('StrictCookieRequired') || !$this->reflector->hasAnnotation('NoCSRFRequired')) {
153
+			if (!$this->request->passesStrictCookieCheck()) {
154 154
 				throw new StrictCookieMissingException();
155 155
 			}
156 156
 		}
157 157
 		// CSRF check - also registers the CSRF token since the session may be closed later
158 158
 		Util::callRegister();
159
-		if(!$this->reflector->hasAnnotation('NoCSRFRequired')) {
159
+		if (!$this->reflector->hasAnnotation('NoCSRFRequired')) {
160 160
 			/*
161 161
 			 * Only allow the CSRF check to fail on OCS Requests. This kind of
162 162
 			 * hacks around that we have no full token auth in place yet and we
@@ -165,7 +165,7 @@  discard block
 block discarded – undo
165 165
 			 * Additionally we allow Bearer authenticated requests to pass on OCS routes.
166 166
 			 * This allows oauth apps (e.g. moodle) to use the OCS endpoints
167 167
 			 */
168
-			if(!$this->request->passesCSRFCheck() && !(
168
+			if (!$this->request->passesCSRFCheck() && !(
169 169
 					$controller instanceof OCSController && (
170 170
 						$this->request->getHeader('OCS-APIREQUEST') === 'true' ||
171 171
 						strpos($this->request->getHeader('Authorization'), 'Bearer ') === 0
@@ -211,7 +211,7 @@  discard block
 block discarded – undo
211 211
 		$defaultPolicy = $this->contentSecurityPolicyManager->getDefaultPolicy();
212 212
 		$defaultPolicy = $this->contentSecurityPolicyManager->mergePolicies($defaultPolicy, $policy);
213 213
 
214
-		if($this->cspNonceManager->browserSupportsCspV3()) {
214
+		if ($this->cspNonceManager->browserSupportsCspV3()) {
215 215
 			$defaultPolicy->useJsNonce($this->csrfTokenManager->getToken()->getEncryptedValue());
216 216
 		}
217 217
 
@@ -231,17 +231,17 @@  discard block
 block discarded – undo
231 231
 	 * @return Response a Response object or null in case that the exception could not be handled
232 232
 	 */
233 233
 	public function afterException($controller, $methodName, \Exception $exception): Response {
234
-		if($exception instanceof SecurityException) {
235
-			if($exception instanceof StrictCookieMissingException) {
234
+		if ($exception instanceof SecurityException) {
235
+			if ($exception instanceof StrictCookieMissingException) {
236 236
 				return new RedirectResponse(\OC::$WEBROOT);
237 237
  			}
238
-			if (stripos($this->request->getHeader('Accept'),'html') === false) {
238
+			if (stripos($this->request->getHeader('Accept'), 'html') === false) {
239 239
 				$response = new JSONResponse(
240 240
 					['message' => $exception->getMessage()],
241 241
 					$exception->getCode()
242 242
 				);
243 243
 			} else {
244
-				if($exception instanceof NotLoggedInException) {
244
+				if ($exception instanceof NotLoggedInException) {
245 245
 					$params = [];
246 246
 					if (isset($this->request->server['REQUEST_URI'])) {
247 247
 						$params['redirect_url'] = $this->request->server['REQUEST_URI'];
Please login to merge, or discard this patch.