SecurityMiddleware.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  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\Attribute\AuthorizedAdminSetting;
  48. use OCP\AppFramework\Http\Attribute\NoAdminRequired;
  49. use OCP\AppFramework\Http\Attribute\NoCSRFRequired;
  50. use OCP\AppFramework\Http\Attribute\PublicPage;
  51. use OCP\AppFramework\Http\Attribute\StrictCookiesRequired;
  52. use OCP\AppFramework\Http\Attribute\SubAdminRequired;
  53. use OCP\AppFramework\Http\JSONResponse;
  54. use OCP\AppFramework\Http\RedirectResponse;
  55. use OCP\AppFramework\Http\Response;
  56. use OCP\AppFramework\Http\TemplateResponse;
  57. use OCP\AppFramework\Middleware;
  58. use OCP\AppFramework\OCSController;
  59. use OCP\IL10N;
  60. use OCP\INavigationManager;
  61. use OCP\IRequest;
  62. use OCP\IURLGenerator;
  63. use OCP\IUserSession;
  64. use OCP\Util;
  65. use Psr\Log\LoggerInterface;
  66. use ReflectionMethod;
  67. /**
  68. * Used to do all the authentication and checking stuff for a controller method
  69. * It reads out the annotations of a controller method and checks which if
  70. * security things should be checked and also handles errors in case a security
  71. * check fails
  72. */
  73. class SecurityMiddleware extends Middleware {
  74. /** @var INavigationManager */
  75. private $navigationManager;
  76. /** @var IRequest */
  77. private $request;
  78. /** @var ControllerMethodReflector */
  79. private $reflector;
  80. /** @var string */
  81. private $appName;
  82. /** @var IURLGenerator */
  83. private $urlGenerator;
  84. /** @var LoggerInterface */
  85. private $logger;
  86. /** @var bool */
  87. private $isLoggedIn;
  88. /** @var bool */
  89. private $isAdminUser;
  90. /** @var bool */
  91. private $isSubAdmin;
  92. /** @var IAppManager */
  93. private $appManager;
  94. /** @var IL10N */
  95. private $l10n;
  96. /** @var AuthorizedGroupMapper */
  97. private $groupAuthorizationMapper;
  98. /** @var IUserSession */
  99. private $userSession;
  100. public function __construct(IRequest $request,
  101. ControllerMethodReflector $reflector,
  102. INavigationManager $navigationManager,
  103. IURLGenerator $urlGenerator,
  104. LoggerInterface $logger,
  105. string $appName,
  106. bool $isLoggedIn,
  107. bool $isAdminUser,
  108. bool $isSubAdmin,
  109. IAppManager $appManager,
  110. IL10N $l10n,
  111. AuthorizedGroupMapper $mapper,
  112. IUserSession $userSession
  113. ) {
  114. $this->navigationManager = $navigationManager;
  115. $this->request = $request;
  116. $this->reflector = $reflector;
  117. $this->appName = $appName;
  118. $this->urlGenerator = $urlGenerator;
  119. $this->logger = $logger;
  120. $this->isLoggedIn = $isLoggedIn;
  121. $this->isAdminUser = $isAdminUser;
  122. $this->isSubAdmin = $isSubAdmin;
  123. $this->appManager = $appManager;
  124. $this->l10n = $l10n;
  125. $this->groupAuthorizationMapper = $mapper;
  126. $this->userSession = $userSession;
  127. }
  128. /**
  129. * This runs all the security checks before a method call. The
  130. * security checks are determined by inspecting the controller method
  131. * annotations
  132. *
  133. * @param Controller $controller the controller
  134. * @param string $methodName the name of the method
  135. * @throws SecurityException when a security check fails
  136. *
  137. * @suppress PhanUndeclaredClassConstant
  138. */
  139. public function beforeController($controller, $methodName) {
  140. // this will set the current navigation entry of the app, use this only
  141. // for normal HTML requests and not for AJAX requests
  142. $this->navigationManager->setActiveEntry($this->appName);
  143. if (get_class($controller) === \OCA\Talk\Controller\PageController::class && $methodName === 'showCall') {
  144. $this->navigationManager->setActiveEntry('spreed');
  145. }
  146. $reflectionMethod = new ReflectionMethod($controller, $methodName);
  147. // security checks
  148. $isPublicPage = $this->hasAnnotationOrAttribute($reflectionMethod, 'PublicPage', PublicPage::class);
  149. if (!$isPublicPage) {
  150. if (!$this->isLoggedIn) {
  151. throw new NotLoggedInException();
  152. }
  153. $authorized = false;
  154. if ($this->hasAnnotationOrAttribute($reflectionMethod, 'AuthorizedAdminSetting', AuthorizedAdminSetting::class)) {
  155. $authorized = $this->isAdminUser;
  156. if (!$authorized && $this->hasAnnotationOrAttribute($reflectionMethod, 'SubAdminRequired', SubAdminRequired::class)) {
  157. $authorized = $this->isSubAdmin;
  158. }
  159. if (!$authorized) {
  160. $settingClasses = $this->getAuthorizedAdminSettingClasses($reflectionMethod);
  161. $authorizedClasses = $this->groupAuthorizationMapper->findAllClassesForUser($this->userSession->getUser());
  162. foreach ($settingClasses as $settingClass) {
  163. $authorized = in_array($settingClass, $authorizedClasses, true);
  164. if ($authorized) {
  165. break;
  166. }
  167. }
  168. }
  169. if (!$authorized) {
  170. throw new NotAdminException($this->l10n->t('Logged in account must be an admin, a sub admin or gotten special right to access this setting'));
  171. }
  172. }
  173. if ($this->hasAnnotationOrAttribute($reflectionMethod, 'SubAdminRequired', SubAdminRequired::class)
  174. && !$this->isSubAdmin
  175. && !$this->isAdminUser
  176. && !$authorized) {
  177. throw new NotAdminException($this->l10n->t('Logged in account must be an admin or sub admin'));
  178. }
  179. if (!$this->hasAnnotationOrAttribute($reflectionMethod, 'SubAdminRequired', SubAdminRequired::class)
  180. && !$this->hasAnnotationOrAttribute($reflectionMethod, 'NoAdminRequired', NoAdminRequired::class)
  181. && !$this->isAdminUser
  182. && !$authorized) {
  183. throw new NotAdminException($this->l10n->t('Logged in account must be an admin'));
  184. }
  185. }
  186. // Check for strict cookie requirement
  187. if ($this->hasAnnotationOrAttribute($reflectionMethod, 'StrictCookieRequired', StrictCookiesRequired::class) ||
  188. !$this->hasAnnotationOrAttribute($reflectionMethod, 'NoCSRFRequired', NoCSRFRequired::class)) {
  189. if (!$this->request->passesStrictCookieCheck()) {
  190. throw new StrictCookieMissingException();
  191. }
  192. }
  193. // CSRF check - also registers the CSRF token since the session may be closed later
  194. Util::callRegister();
  195. if ($this->isInvalidCSRFRequired($reflectionMethod)) {
  196. /*
  197. * Only allow the CSRF check to fail on OCS Requests. This kind of
  198. * hacks around that we have no full token auth in place yet and we
  199. * do want to offer CSRF checks for web requests.
  200. *
  201. * Additionally we allow Bearer authenticated requests to pass on OCS routes.
  202. * This allows oauth apps (e.g. moodle) to use the OCS endpoints
  203. */
  204. if (!$controller instanceof OCSController || !$this->isValidOCSRequest()) {
  205. throw new CrossSiteRequestForgeryException();
  206. }
  207. }
  208. /**
  209. * Checks if app is enabled (also includes a check whether user is allowed to access the resource)
  210. * The getAppPath() check is here since components such as settings also use the AppFramework and
  211. * therefore won't pass this check.
  212. * If page is public, app does not need to be enabled for current user/visitor
  213. */
  214. try {
  215. $appPath = $this->appManager->getAppPath($this->appName);
  216. } catch (AppPathNotFoundException $e) {
  217. $appPath = false;
  218. }
  219. if ($appPath !== false && !$isPublicPage && !$this->appManager->isEnabledForUser($this->appName)) {
  220. throw new AppNotEnabledException();
  221. }
  222. }
  223. private function isInvalidCSRFRequired(ReflectionMethod $reflectionMethod): bool {
  224. if ($this->hasAnnotationOrAttribute($reflectionMethod, 'NoCSRFRequired', NoCSRFRequired::class)) {
  225. return false;
  226. }
  227. return !$this->request->passesCSRFCheck();
  228. }
  229. private function isValidOCSRequest(): bool {
  230. return $this->request->getHeader('OCS-APIREQUEST') === 'true'
  231. || str_starts_with($this->request->getHeader('Authorization'), 'Bearer ');
  232. }
  233. /**
  234. * @template T
  235. *
  236. * @param ReflectionMethod $reflectionMethod
  237. * @param string $annotationName
  238. * @param class-string<T> $attributeClass
  239. * @return boolean
  240. */
  241. protected function hasAnnotationOrAttribute(ReflectionMethod $reflectionMethod, string $annotationName, string $attributeClass): bool {
  242. if (!empty($reflectionMethod->getAttributes($attributeClass))) {
  243. return true;
  244. }
  245. if ($this->reflector->hasAnnotation($annotationName)) {
  246. return true;
  247. }
  248. return false;
  249. }
  250. /**
  251. * @param ReflectionMethod $reflectionMethod
  252. * @return string[]
  253. */
  254. protected function getAuthorizedAdminSettingClasses(ReflectionMethod $reflectionMethod): array {
  255. $classes = [];
  256. if ($this->reflector->hasAnnotation('AuthorizedAdminSetting')) {
  257. $classes = explode(';', $this->reflector->getAnnotationParameter('AuthorizedAdminSetting', 'settings'));
  258. }
  259. $attributes = $reflectionMethod->getAttributes(AuthorizedAdminSetting::class);
  260. if (!empty($attributes)) {
  261. foreach ($attributes as $attribute) {
  262. /** @var AuthorizedAdminSetting $setting */
  263. $setting = $attribute->newInstance();
  264. $classes[] = $setting->getSettings();
  265. }
  266. }
  267. return $classes;
  268. }
  269. /**
  270. * If an SecurityException is being caught, ajax requests return a JSON error
  271. * response and non ajax requests redirect to the index
  272. *
  273. * @param Controller $controller the controller that is being called
  274. * @param string $methodName the name of the method that will be called on
  275. * the controller
  276. * @param \Exception $exception the thrown exception
  277. * @return Response a Response object or null in case that the exception could not be handled
  278. * @throws \Exception the passed in exception if it can't handle it
  279. */
  280. public function afterException($controller, $methodName, \Exception $exception): Response {
  281. if ($exception instanceof SecurityException) {
  282. if ($exception instanceof StrictCookieMissingException) {
  283. return new RedirectResponse(\OC::$WEBROOT . '/');
  284. }
  285. if (stripos($this->request->getHeader('Accept'), 'html') === false) {
  286. $response = new JSONResponse(
  287. ['message' => $exception->getMessage()],
  288. $exception->getCode()
  289. );
  290. } else {
  291. if ($exception instanceof NotLoggedInException) {
  292. $params = [];
  293. if (isset($this->request->server['REQUEST_URI'])) {
  294. $params['redirect_url'] = $this->request->server['REQUEST_URI'];
  295. }
  296. $usernamePrefill = $this->request->getParam('user', '');
  297. if ($usernamePrefill !== '') {
  298. $params['user'] = $usernamePrefill;
  299. }
  300. if ($this->request->getParam('direct')) {
  301. $params['direct'] = 1;
  302. }
  303. $url = $this->urlGenerator->linkToRoute('core.login.showLoginForm', $params);
  304. $response = new RedirectResponse($url);
  305. } else {
  306. $response = new TemplateResponse('core', '403', ['message' => $exception->getMessage()], 'guest');
  307. $response->setStatus($exception->getCode());
  308. }
  309. }
  310. $this->logger->debug($exception->getMessage(), [
  311. 'exception' => $exception,
  312. ]);
  313. return $response;
  314. }
  315. throw $exception;
  316. }
  317. }