nextcloud/lib/private/AppFramework/Middleware/Security/SecurityMiddleware.php

246 lines
8.6 KiB
PHP
Raw Normal View History

2013-08-17 13:16:48 +04:00
<?php
declare(strict_types=1);
2013-08-17 13:16:48 +04:00
/**
2016-07-21 18:07:57 +03:00
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Arthur Schiwon <blizzz@arthur-schiwon.de>
2015-03-26 13:44:34 +03:00
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @author Bjoern Schiessle <bjoern@schiessle.org>
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Daniel Kesselberg <mail@danielkesselberg.de>
* @author Holger Hees <holger.hees@gmail.com>
* @author Joas Schilling <coding@schilljs.com>
* @author Julien Veyssier <eneiluj@posteo.net>
2016-05-26 20:56:05 +03:00
* @author Lukas Reschke <lukas@statuscode.ch>
2015-03-26 13:44:34 +03:00
* @author Morris Jobke <hey@morrisjobke.de>
2016-07-21 18:07:57 +03:00
* @author Roeland Jago Douma <roeland@famdouma.nl>
2016-05-26 20:56:05 +03:00
* @author Stefan Weil <sw@weilnetz.de>
2015-03-26 13:44:34 +03:00
* @author Thomas Müller <thomas.mueller@tmit.eu>
* @author Thomas Tanghus <thomas@tanghus.net>
2013-08-17 13:16:48 +04:00
*
2015-03-26 13:44:34 +03:00
* @license AGPL-3.0
2013-08-17 13:16:48 +04:00
*
2015-03-26 13:44:34 +03:00
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
2013-08-17 13:16:48 +04:00
*
2015-03-26 13:44:34 +03:00
* This program is distributed in the hope that it will be useful,
2013-08-17 13:16:48 +04:00
* but WITHOUT ANY WARRANTY; without even the implied warranty of
2015-03-26 13:44:34 +03:00
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
2013-08-17 13:16:48 +04:00
*
2015-03-26 13:44:34 +03:00
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
2013-08-17 13:16:48 +04:00
*
*/
2013-08-17 13:16:48 +04:00
namespace OC\AppFramework\Middleware\Security;
use OC\AppFramework\Middleware\Security\Exceptions\AppNotEnabledException;
use OC\AppFramework\Middleware\Security\Exceptions\CrossSiteRequestForgeryException;
use OC\AppFramework\Middleware\Security\Exceptions\NotAdminException;
use OC\AppFramework\Middleware\Security\Exceptions\NotLoggedInException;
use OC\AppFramework\Middleware\Security\Exceptions\SecurityException;
use OC\AppFramework\Middleware\Security\Exceptions\StrictCookieMissingException;
use OC\AppFramework\Utility\ControllerMethodReflector;
use OCP\App\AppPathNotFoundException;
use OCP\App\IAppManager;
use OCP\AppFramework\Controller;
use OCP\AppFramework\Http\JSONResponse;
use OCP\AppFramework\Http\RedirectResponse;
use OCP\AppFramework\Http\Response;
use OCP\AppFramework\Http\TemplateResponse;
use OCP\AppFramework\Middleware;
use OCP\AppFramework\OCSController;
use OCP\IL10N;
use OCP\ILogger;
use OCP\INavigationManager;
use OCP\IRequest;
use OCP\IURLGenerator;
use OCP\Util;
2013-08-17 13:16:48 +04:00
/**
* Used to do all the authentication and checking stuff for a controller method
* It reads out the annotations of a controller method and checks which if
* security things should be checked and also handles errors in case a security
* check fails
*/
class SecurityMiddleware extends Middleware {
Add public API to give developers the possibility to adjust the global CSP defaults Allows to inject something into the default content policy. This is for example useful when you're injecting Javascript code into a view belonging to another controller and cannot modify its Content-Security-Policy itself. Note that the adjustment is only applied to applications that use AppFramework controllers. To use this from your `app.php` use `\OC::$server->getContentSecurityPolicyManager()->addDefaultPolicy($policy)`, $policy has to be of type `\OCP\AppFramework\Http\ContentSecurityPolicy`. To test this add something like the following into an `app.php` of any enabled app: ``` $manager = \OC::$server->getContentSecurityPolicyManager(); $policy = new \OCP\AppFramework\Http\ContentSecurityPolicy(false); $policy->addAllowedFrameDomain('asdf'); $policy->addAllowedScriptDomain('yolo.com'); $policy->allowInlineScript(false); $manager->addDefaultPolicy($policy); $policy = new \OCP\AppFramework\Http\ContentSecurityPolicy(false); $policy->addAllowedFontDomain('yolo.com'); $manager->addDefaultPolicy($policy); $policy = new \OCP\AppFramework\Http\ContentSecurityPolicy(false); $policy->addAllowedFrameDomain('banana.com'); $manager->addDefaultPolicy($policy); ``` If you now open the files app the policy should be: ``` Content-Security-Policy:default-src 'none';script-src yolo.com 'self' 'unsafe-eval';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src yolo.com 'self';connect-src 'self';media-src 'self';frame-src asdf banana.com 'self' ```
2016-01-28 16:33:02 +03:00
/** @var INavigationManager */
private $navigationManager;
Add public API to give developers the possibility to adjust the global CSP defaults Allows to inject something into the default content policy. This is for example useful when you're injecting Javascript code into a view belonging to another controller and cannot modify its Content-Security-Policy itself. Note that the adjustment is only applied to applications that use AppFramework controllers. To use this from your `app.php` use `\OC::$server->getContentSecurityPolicyManager()->addDefaultPolicy($policy)`, $policy has to be of type `\OCP\AppFramework\Http\ContentSecurityPolicy`. To test this add something like the following into an `app.php` of any enabled app: ``` $manager = \OC::$server->getContentSecurityPolicyManager(); $policy = new \OCP\AppFramework\Http\ContentSecurityPolicy(false); $policy->addAllowedFrameDomain('asdf'); $policy->addAllowedScriptDomain('yolo.com'); $policy->allowInlineScript(false); $manager->addDefaultPolicy($policy); $policy = new \OCP\AppFramework\Http\ContentSecurityPolicy(false); $policy->addAllowedFontDomain('yolo.com'); $manager->addDefaultPolicy($policy); $policy = new \OCP\AppFramework\Http\ContentSecurityPolicy(false); $policy->addAllowedFrameDomain('banana.com'); $manager->addDefaultPolicy($policy); ``` If you now open the files app the policy should be: ``` Content-Security-Policy:default-src 'none';script-src yolo.com 'self' 'unsafe-eval';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src yolo.com 'self';connect-src 'self';media-src 'self';frame-src asdf banana.com 'self' ```
2016-01-28 16:33:02 +03:00
/** @var IRequest */
2013-08-17 13:16:48 +04:00
private $request;
Add public API to give developers the possibility to adjust the global CSP defaults Allows to inject something into the default content policy. This is for example useful when you're injecting Javascript code into a view belonging to another controller and cannot modify its Content-Security-Policy itself. Note that the adjustment is only applied to applications that use AppFramework controllers. To use this from your `app.php` use `\OC::$server->getContentSecurityPolicyManager()->addDefaultPolicy($policy)`, $policy has to be of type `\OCP\AppFramework\Http\ContentSecurityPolicy`. To test this add something like the following into an `app.php` of any enabled app: ``` $manager = \OC::$server->getContentSecurityPolicyManager(); $policy = new \OCP\AppFramework\Http\ContentSecurityPolicy(false); $policy->addAllowedFrameDomain('asdf'); $policy->addAllowedScriptDomain('yolo.com'); $policy->allowInlineScript(false); $manager->addDefaultPolicy($policy); $policy = new \OCP\AppFramework\Http\ContentSecurityPolicy(false); $policy->addAllowedFontDomain('yolo.com'); $manager->addDefaultPolicy($policy); $policy = new \OCP\AppFramework\Http\ContentSecurityPolicy(false); $policy->addAllowedFrameDomain('banana.com'); $manager->addDefaultPolicy($policy); ``` If you now open the files app the policy should be: ``` Content-Security-Policy:default-src 'none';script-src yolo.com 'self' 'unsafe-eval';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src yolo.com 'self';connect-src 'self';media-src 'self';frame-src asdf banana.com 'self' ```
2016-01-28 16:33:02 +03:00
/** @var ControllerMethodReflector */
private $reflector;
Add public API to give developers the possibility to adjust the global CSP defaults Allows to inject something into the default content policy. This is for example useful when you're injecting Javascript code into a view belonging to another controller and cannot modify its Content-Security-Policy itself. Note that the adjustment is only applied to applications that use AppFramework controllers. To use this from your `app.php` use `\OC::$server->getContentSecurityPolicyManager()->addDefaultPolicy($policy)`, $policy has to be of type `\OCP\AppFramework\Http\ContentSecurityPolicy`. To test this add something like the following into an `app.php` of any enabled app: ``` $manager = \OC::$server->getContentSecurityPolicyManager(); $policy = new \OCP\AppFramework\Http\ContentSecurityPolicy(false); $policy->addAllowedFrameDomain('asdf'); $policy->addAllowedScriptDomain('yolo.com'); $policy->allowInlineScript(false); $manager->addDefaultPolicy($policy); $policy = new \OCP\AppFramework\Http\ContentSecurityPolicy(false); $policy->addAllowedFontDomain('yolo.com'); $manager->addDefaultPolicy($policy); $policy = new \OCP\AppFramework\Http\ContentSecurityPolicy(false); $policy->addAllowedFrameDomain('banana.com'); $manager->addDefaultPolicy($policy); ``` If you now open the files app the policy should be: ``` Content-Security-Policy:default-src 'none';script-src yolo.com 'self' 'unsafe-eval';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src yolo.com 'self';connect-src 'self';media-src 'self';frame-src asdf banana.com 'self' ```
2016-01-28 16:33:02 +03:00
/** @var string */
private $appName;
Add public API to give developers the possibility to adjust the global CSP defaults Allows to inject something into the default content policy. This is for example useful when you're injecting Javascript code into a view belonging to another controller and cannot modify its Content-Security-Policy itself. Note that the adjustment is only applied to applications that use AppFramework controllers. To use this from your `app.php` use `\OC::$server->getContentSecurityPolicyManager()->addDefaultPolicy($policy)`, $policy has to be of type `\OCP\AppFramework\Http\ContentSecurityPolicy`. To test this add something like the following into an `app.php` of any enabled app: ``` $manager = \OC::$server->getContentSecurityPolicyManager(); $policy = new \OCP\AppFramework\Http\ContentSecurityPolicy(false); $policy->addAllowedFrameDomain('asdf'); $policy->addAllowedScriptDomain('yolo.com'); $policy->allowInlineScript(false); $manager->addDefaultPolicy($policy); $policy = new \OCP\AppFramework\Http\ContentSecurityPolicy(false); $policy->addAllowedFontDomain('yolo.com'); $manager->addDefaultPolicy($policy); $policy = new \OCP\AppFramework\Http\ContentSecurityPolicy(false); $policy->addAllowedFrameDomain('banana.com'); $manager->addDefaultPolicy($policy); ``` If you now open the files app the policy should be: ``` Content-Security-Policy:default-src 'none';script-src yolo.com 'self' 'unsafe-eval';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src yolo.com 'self';connect-src 'self';media-src 'self';frame-src asdf banana.com 'self' ```
2016-01-28 16:33:02 +03:00
/** @var IURLGenerator */
private $urlGenerator;
Add public API to give developers the possibility to adjust the global CSP defaults Allows to inject something into the default content policy. This is for example useful when you're injecting Javascript code into a view belonging to another controller and cannot modify its Content-Security-Policy itself. Note that the adjustment is only applied to applications that use AppFramework controllers. To use this from your `app.php` use `\OC::$server->getContentSecurityPolicyManager()->addDefaultPolicy($policy)`, $policy has to be of type `\OCP\AppFramework\Http\ContentSecurityPolicy`. To test this add something like the following into an `app.php` of any enabled app: ``` $manager = \OC::$server->getContentSecurityPolicyManager(); $policy = new \OCP\AppFramework\Http\ContentSecurityPolicy(false); $policy->addAllowedFrameDomain('asdf'); $policy->addAllowedScriptDomain('yolo.com'); $policy->allowInlineScript(false); $manager->addDefaultPolicy($policy); $policy = new \OCP\AppFramework\Http\ContentSecurityPolicy(false); $policy->addAllowedFontDomain('yolo.com'); $manager->addDefaultPolicy($policy); $policy = new \OCP\AppFramework\Http\ContentSecurityPolicy(false); $policy->addAllowedFrameDomain('banana.com'); $manager->addDefaultPolicy($policy); ``` If you now open the files app the policy should be: ``` Content-Security-Policy:default-src 'none';script-src yolo.com 'self' 'unsafe-eval';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src yolo.com 'self';connect-src 'self';media-src 'self';frame-src asdf banana.com 'self' ```
2016-01-28 16:33:02 +03:00
/** @var ILogger */
private $logger;
/** @var bool */
private $isLoggedIn;
Add public API to give developers the possibility to adjust the global CSP defaults Allows to inject something into the default content policy. This is for example useful when you're injecting Javascript code into a view belonging to another controller and cannot modify its Content-Security-Policy itself. Note that the adjustment is only applied to applications that use AppFramework controllers. To use this from your `app.php` use `\OC::$server->getContentSecurityPolicyManager()->addDefaultPolicy($policy)`, $policy has to be of type `\OCP\AppFramework\Http\ContentSecurityPolicy`. To test this add something like the following into an `app.php` of any enabled app: ``` $manager = \OC::$server->getContentSecurityPolicyManager(); $policy = new \OCP\AppFramework\Http\ContentSecurityPolicy(false); $policy->addAllowedFrameDomain('asdf'); $policy->addAllowedScriptDomain('yolo.com'); $policy->allowInlineScript(false); $manager->addDefaultPolicy($policy); $policy = new \OCP\AppFramework\Http\ContentSecurityPolicy(false); $policy->addAllowedFontDomain('yolo.com'); $manager->addDefaultPolicy($policy); $policy = new \OCP\AppFramework\Http\ContentSecurityPolicy(false); $policy->addAllowedFrameDomain('banana.com'); $manager->addDefaultPolicy($policy); ``` If you now open the files app the policy should be: ``` Content-Security-Policy:default-src 'none';script-src yolo.com 'self' 'unsafe-eval';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src yolo.com 'self';connect-src 'self';media-src 'self';frame-src asdf banana.com 'self' ```
2016-01-28 16:33:02 +03:00
/** @var bool */
private $isAdminUser;
/** @var bool */
private $isSubAdmin;
/** @var IAppManager */
private $appManager;
/** @var IL10N */
private $l10n;
public function __construct(IRequest $request,
ControllerMethodReflector $reflector,
INavigationManager $navigationManager,
IURLGenerator $urlGenerator,
ILogger $logger,
string $appName,
bool $isLoggedIn,
bool $isAdminUser,
bool $isSubAdmin,
IAppManager $appManager,
IL10N $l10n
) {
$this->navigationManager = $navigationManager;
2013-08-17 13:16:48 +04:00
$this->request = $request;
$this->reflector = $reflector;
$this->appName = $appName;
$this->urlGenerator = $urlGenerator;
$this->logger = $logger;
$this->isLoggedIn = $isLoggedIn;
$this->isAdminUser = $isAdminUser;
$this->isSubAdmin = $isSubAdmin;
$this->appManager = $appManager;
$this->l10n = $l10n;
2013-08-17 13:16:48 +04:00
}
/**
* This runs all the security checks before a method call. The
* security checks are determined by inspecting the controller method
* annotations
* @param Controller $controller the controller
2013-08-17 13:16:48 +04:00
* @param string $methodName the name of the method
* @throws SecurityException when a security check fails
*
* @suppress PhanUndeclaredClassConstant
2013-08-17 13:16:48 +04:00
*/
public function beforeController($controller, $methodName) {
2013-08-17 13:16:48 +04:00
// this will set the current navigation entry of the app, use this only
// for normal HTML requests and not for AJAX requests
$this->navigationManager->setActiveEntry($this->appName);
2013-08-17 13:16:48 +04:00
if (get_class($controller) === \OCA\Talk\Controller\PageController::class && $methodName === 'showCall') {
$this->navigationManager->setActiveEntry('spreed');
}
2013-08-17 13:16:48 +04:00
// security checks
$isPublicPage = $this->reflector->hasAnnotation('PublicPage');
if (!$isPublicPage) {
if (!$this->isLoggedIn) {
throw new NotLoggedInException();
2013-08-17 13:16:48 +04:00
}
if ($this->reflector->hasAnnotation('SubAdminRequired')
&& !$this->isSubAdmin
&& !$this->isAdminUser) {
throw new NotAdminException($this->l10n->t('Logged in user must be an admin or sub admin'));
}
if (!$this->reflector->hasAnnotation('SubAdminRequired')
&& !$this->reflector->hasAnnotation('NoAdminRequired')
&& !$this->isAdminUser) {
throw new NotAdminException($this->l10n->t('Logged in user must be an admin'));
2013-08-17 13:16:48 +04:00
}
}
// Check for strict cookie requirement
if ($this->reflector->hasAnnotation('StrictCookieRequired') || !$this->reflector->hasAnnotation('NoCSRFRequired')) {
if (!$this->request->passesStrictCookieCheck()) {
throw new StrictCookieMissingException();
}
}
// CSRF check - also registers the CSRF token since the session may be closed later
Util::callRegister();
if (!$this->reflector->hasAnnotation('NoCSRFRequired')) {
/*
* Only allow the CSRF check to fail on OCS Requests. This kind of
* hacks around that we have no full token auth in place yet and we
* do want to offer CSRF checks for web requests.
*
* Additionally we allow Bearer authenticated requests to pass on OCS routes.
* This allows oauth apps (e.g. moodle) to use the OCS endpoints
*/
if (!$this->request->passesCSRFCheck() && !(
$controller instanceof OCSController && (
$this->request->getHeader('OCS-APIREQUEST') === 'true' ||
strpos($this->request->getHeader('Authorization'), 'Bearer ') === 0
)
)) {
throw new CrossSiteRequestForgeryException();
2013-08-17 13:16:48 +04:00
}
}
/**
* Checks if app is enabled (also includes a check whether user is allowed to access the resource)
* The getAppPath() check is here since components such as settings also use the AppFramework and
* therefore won't pass this check.
* If page is public, app does not need to be enabled for current user/visitor
*/
try {
$appPath = $this->appManager->getAppPath($this->appName);
} catch (AppPathNotFoundException $e) {
$appPath = false;
}
if ($appPath !== false && !$isPublicPage && !$this->appManager->isEnabledForUser($this->appName)) {
throw new AppNotEnabledException();
}
2013-08-17 13:16:48 +04:00
}
/**
* If an SecurityException is being caught, ajax requests return a JSON error
* response and non ajax requests redirect to the index
* @param Controller $controller the controller that is being called
* @param string $methodName the name of the method that will be called on
* the controller
* @param \Exception $exception the thrown exception
* @throws \Exception the passed in exception if it can't handle it
2013-08-17 13:16:48 +04:00
* @return Response a Response object or null in case that the exception could not be handled
*/
public function afterException($controller, $methodName, \Exception $exception): Response {
if ($exception instanceof SecurityException) {
if ($exception instanceof StrictCookieMissingException) {
return new RedirectResponse(\OC::$WEBROOT . '/');
}
if (stripos($this->request->getHeader('Accept'),'html') === false) {
2013-08-17 13:16:48 +04:00
$response = new JSONResponse(
['message' => $exception->getMessage()],
2013-08-17 13:16:48 +04:00
$exception->getCode()
);
} else {
if ($exception instanceof NotLoggedInException) {
$params = [];
if (isset($this->request->server['REQUEST_URI'])) {
$params['redirect_url'] = $this->request->server['REQUEST_URI'];
}
$url = $this->urlGenerator->linkToRoute('core.login.showLoginForm', $params);
$response = new RedirectResponse($url);
} else {
$response = new TemplateResponse('core', '403', ['message' => $exception->getMessage()], 'guest');
$response->setStatus($exception->getCode());
}
2013-08-17 13:16:48 +04:00
}
$this->logger->logException($exception, [
'level' => ILogger::DEBUG,
'app' => 'core',
]);
2013-08-17 13:16:48 +04:00
return $response;
}
throw $exception;
}
}