SecurityMiddleware.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright Copyright (c) 2016, ownCloud, Inc.
  5. *
  6. * @author Bernhard Posselt <dev@bernhard-posselt.com>
  7. * @author Bjoern Schiessle <bjoern@schiessle.org>
  8. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  9. * @author Daniel Kesselberg <mail@danielkesselberg.de>
  10. * @author Holger Hees <holger.hees@gmail.com>
  11. * @author Joas Schilling <coding@schilljs.com>
  12. * @author Julien Veyssier <eneiluj@posteo.net>
  13. * @author Lukas Reschke <lukas@statuscode.ch>
  14. * @author Morris Jobke <hey@morrisjobke.de>
  15. * @author Roeland Jago Douma <roeland@famdouma.nl>
  16. * @author Stefan Weil <sw@weilnetz.de>
  17. * @author Thomas Müller <thomas.mueller@tmit.eu>
  18. * @author Thomas Tanghus <thomas@tanghus.net>
  19. *
  20. * @license AGPL-3.0
  21. *
  22. * This code is free software: you can redistribute it and/or modify
  23. * it under the terms of the GNU Affero General Public License, version 3,
  24. * as published by the Free Software Foundation.
  25. *
  26. * This program is distributed in the hope that it will be useful,
  27. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  28. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  29. * GNU Affero General Public License for more details.
  30. *
  31. * You should have received a copy of the GNU Affero General Public License, version 3,
  32. * along with this program. If not, see <http://www.gnu.org/licenses/>
  33. *
  34. */
  35. namespace OC\AppFramework\Middleware\Security;
  36. use OC\AppFramework\Middleware\Security\Exceptions\AppNotEnabledException;
  37. use OC\AppFramework\Middleware\Security\Exceptions\CrossSiteRequestForgeryException;
  38. use OC\AppFramework\Middleware\Security\Exceptions\NotAdminException;
  39. use OC\AppFramework\Middleware\Security\Exceptions\NotLoggedInException;
  40. use OC\AppFramework\Middleware\Security\Exceptions\SecurityException;
  41. use OC\AppFramework\Middleware\Security\Exceptions\StrictCookieMissingException;
  42. use OC\AppFramework\Utility\ControllerMethodReflector;
  43. use OC\Settings\AuthorizedGroupMapper;
  44. use OCP\App\AppPathNotFoundException;
  45. use OCP\App\IAppManager;
  46. use OCP\AppFramework\Controller;
  47. use OCP\AppFramework\Http\JSONResponse;
  48. use OCP\AppFramework\Http\RedirectResponse;
  49. use OCP\AppFramework\Http\Response;
  50. use OCP\AppFramework\Http\TemplateResponse;
  51. use OCP\AppFramework\Middleware;
  52. use OCP\AppFramework\OCSController;
  53. use OCP\IL10N;
  54. use OCP\INavigationManager;
  55. use OCP\IRequest;
  56. use OCP\IURLGenerator;
  57. use OCP\IUserSession;
  58. use OCP\Util;
  59. use Psr\Log\LoggerInterface;
  60. /**
  61. * Used to do all the authentication and checking stuff for a controller method
  62. * It reads out the annotations of a controller method and checks which if
  63. * security things should be checked and also handles errors in case a security
  64. * check fails
  65. */
  66. class SecurityMiddleware extends Middleware {
  67. /** @var INavigationManager */
  68. private $navigationManager;
  69. /** @var IRequest */
  70. private $request;
  71. /** @var ControllerMethodReflector */
  72. private $reflector;
  73. /** @var string */
  74. private $appName;
  75. /** @var IURLGenerator */
  76. private $urlGenerator;
  77. /** @var LoggerInterface */
  78. private $logger;
  79. /** @var bool */
  80. private $isLoggedIn;
  81. /** @var bool */
  82. private $isAdminUser;
  83. /** @var bool */
  84. private $isSubAdmin;
  85. /** @var IAppManager */
  86. private $appManager;
  87. /** @var IL10N */
  88. private $l10n;
  89. /** @var AuthorizedGroupMapper */
  90. private $groupAuthorizationMapper;
  91. /** @var IUserSession */
  92. private $userSession;
  93. public function __construct(IRequest $request,
  94. ControllerMethodReflector $reflector,
  95. INavigationManager $navigationManager,
  96. IURLGenerator $urlGenerator,
  97. LoggerInterface $logger,
  98. string $appName,
  99. bool $isLoggedIn,
  100. bool $isAdminUser,
  101. bool $isSubAdmin,
  102. IAppManager $appManager,
  103. IL10N $l10n,
  104. AuthorizedGroupMapper $mapper,
  105. IUserSession $userSession
  106. ) {
  107. $this->navigationManager = $navigationManager;
  108. $this->request = $request;
  109. $this->reflector = $reflector;
  110. $this->appName = $appName;
  111. $this->urlGenerator = $urlGenerator;
  112. $this->logger = $logger;
  113. $this->isLoggedIn = $isLoggedIn;
  114. $this->isAdminUser = $isAdminUser;
  115. $this->isSubAdmin = $isSubAdmin;
  116. $this->appManager = $appManager;
  117. $this->l10n = $l10n;
  118. $this->groupAuthorizationMapper = $mapper;
  119. $this->userSession = $userSession;
  120. }
  121. /**
  122. * This runs all the security checks before a method call. The
  123. * security checks are determined by inspecting the controller method
  124. * annotations
  125. *
  126. * @param Controller $controller the controller
  127. * @param string $methodName the name of the method
  128. * @throws SecurityException when a security check fails
  129. *
  130. * @suppress PhanUndeclaredClassConstant
  131. */
  132. public function beforeController($controller, $methodName) {
  133. // this will set the current navigation entry of the app, use this only
  134. // for normal HTML requests and not for AJAX requests
  135. $this->navigationManager->setActiveEntry($this->appName);
  136. if (get_class($controller) === \OCA\Talk\Controller\PageController::class && $methodName === 'showCall') {
  137. $this->navigationManager->setActiveEntry('spreed');
  138. }
  139. // security checks
  140. $isPublicPage = $this->reflector->hasAnnotation('PublicPage');
  141. if (!$isPublicPage) {
  142. if (!$this->isLoggedIn) {
  143. throw new NotLoggedInException();
  144. }
  145. $authorized = false;
  146. if ($this->reflector->hasAnnotation('AuthorizedAdminSetting')) {
  147. $authorized = $this->isAdminUser;
  148. if (!$authorized && $this->reflector->hasAnnotation('SubAdminRequired')) {
  149. $authorized = $this->isSubAdmin;
  150. }
  151. if (!$authorized) {
  152. $settingClasses = explode(';', $this->reflector->getAnnotationParameter('AuthorizedAdminSetting', 'settings'));
  153. $authorizedClasses = $this->groupAuthorizationMapper->findAllClassesForUser($this->userSession->getUser());
  154. foreach ($settingClasses as $settingClass) {
  155. $authorized = in_array($settingClass, $authorizedClasses, true);
  156. if ($authorized) {
  157. break;
  158. }
  159. }
  160. }
  161. if (!$authorized) {
  162. throw new NotAdminException($this->l10n->t('Logged in user must be an admin, a sub admin or gotten special right to access this setting'));
  163. }
  164. }
  165. if ($this->reflector->hasAnnotation('SubAdminRequired')
  166. && !$this->isSubAdmin
  167. && !$this->isAdminUser
  168. && !$authorized) {
  169. throw new NotAdminException($this->l10n->t('Logged in user must be an admin or sub admin'));
  170. }
  171. if (!$this->reflector->hasAnnotation('SubAdminRequired')
  172. && !$this->reflector->hasAnnotation('NoAdminRequired')
  173. && !$this->isAdminUser
  174. && !$authorized) {
  175. throw new NotAdminException($this->l10n->t('Logged in user must be an admin'));
  176. }
  177. }
  178. // Check for strict cookie requirement
  179. if ($this->reflector->hasAnnotation('StrictCookieRequired') || !$this->reflector->hasAnnotation('NoCSRFRequired')) {
  180. if (!$this->request->passesStrictCookieCheck()) {
  181. throw new StrictCookieMissingException();
  182. }
  183. }
  184. // CSRF check - also registers the CSRF token since the session may be closed later
  185. Util::callRegister();
  186. if (!$this->reflector->hasAnnotation('NoCSRFRequired')) {
  187. /*
  188. * Only allow the CSRF check to fail on OCS Requests. This kind of
  189. * hacks around that we have no full token auth in place yet and we
  190. * do want to offer CSRF checks for web requests.
  191. *
  192. * Additionally we allow Bearer authenticated requests to pass on OCS routes.
  193. * This allows oauth apps (e.g. moodle) to use the OCS endpoints
  194. */
  195. if (!$this->request->passesCSRFCheck() && !(
  196. $controller instanceof OCSController && (
  197. $this->request->getHeader('OCS-APIREQUEST') === 'true' ||
  198. strpos($this->request->getHeader('Authorization'), 'Bearer ') === 0
  199. )
  200. )) {
  201. throw new CrossSiteRequestForgeryException();
  202. }
  203. }
  204. /**
  205. * Checks if app is enabled (also includes a check whether user is allowed to access the resource)
  206. * The getAppPath() check is here since components such as settings also use the AppFramework and
  207. * therefore won't pass this check.
  208. * If page is public, app does not need to be enabled for current user/visitor
  209. */
  210. try {
  211. $appPath = $this->appManager->getAppPath($this->appName);
  212. } catch (AppPathNotFoundException $e) {
  213. $appPath = false;
  214. }
  215. if ($appPath !== false && !$isPublicPage && !$this->appManager->isEnabledForUser($this->appName)) {
  216. throw new AppNotEnabledException();
  217. }
  218. }
  219. /**
  220. * If an SecurityException is being caught, ajax requests return a JSON error
  221. * response and non ajax requests redirect to the index
  222. *
  223. * @param Controller $controller the controller that is being called
  224. * @param string $methodName the name of the method that will be called on
  225. * the controller
  226. * @param \Exception $exception the thrown exception
  227. * @return Response a Response object or null in case that the exception could not be handled
  228. * @throws \Exception the passed in exception if it can't handle it
  229. */
  230. public function afterException($controller, $methodName, \Exception $exception): Response {
  231. if ($exception instanceof SecurityException) {
  232. if ($exception instanceof StrictCookieMissingException) {
  233. return new RedirectResponse(\OC::$WEBROOT . '/');
  234. }
  235. if (stripos($this->request->getHeader('Accept'), 'html') === false) {
  236. $response = new JSONResponse(
  237. ['message' => $exception->getMessage()],
  238. $exception->getCode()
  239. );
  240. } else {
  241. if ($exception instanceof NotLoggedInException) {
  242. $params = [];
  243. if (isset($this->request->server['REQUEST_URI'])) {
  244. $params['redirect_url'] = $this->request->server['REQUEST_URI'];
  245. }
  246. $usernamePrefill = $this->request->getParam('user', '');
  247. if ($usernamePrefill !== '') {
  248. $params['user'] = $usernamePrefill;
  249. }
  250. if ($this->request->getParam('direct')) {
  251. $params['direct'] = 1;
  252. }
  253. $url = $this->urlGenerator->linkToRoute('core.login.showLoginForm', $params);
  254. $response = new RedirectResponse($url);
  255. } else {
  256. $response = new TemplateResponse('core', '403', ['message' => $exception->getMessage()], 'guest');
  257. $response->setStatus($exception->getCode());
  258. }
  259. }
  260. $this->logger->debug($exception->getMessage(), [
  261. 'exception' => $exception,
  262. ]);
  263. return $response;
  264. }
  265. throw $exception;
  266. }
  267. }