AuthSettingsController.php 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  6. * @author Daniel Kesselberg <mail@danielkesselberg.de>
  7. * @author Fabrizio Steiner <fabrizio.steiner@gmail.com>
  8. * @author Greta Doci <gretadoci@gmail.com>
  9. * @author Joas Schilling <coding@schilljs.com>
  10. * @author Lukas Reschke <lukas@statuscode.ch>
  11. * @author Marcel Waldvogel <marcel.waldvogel@uni-konstanz.de>
  12. * @author Morris Jobke <hey@morrisjobke.de>
  13. * @author Robin Appelman <robin@icewind.nl>
  14. * @author Roeland Jago Douma <roeland@famdouma.nl>
  15. * @author Sergej Nikolaev <kinolaev@gmail.com>
  16. *
  17. * @license AGPL-3.0
  18. *
  19. * This code is free software: you can redistribute it and/or modify
  20. * it under the terms of the GNU Affero General Public License, version 3,
  21. * as published by the Free Software Foundation.
  22. *
  23. * This program is distributed in the hope that it will be useful,
  24. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  25. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  26. * GNU Affero General Public License for more details.
  27. *
  28. * You should have received a copy of the GNU Affero General Public License, version 3,
  29. * along with this program. If not, see <http://www.gnu.org/licenses/>
  30. *
  31. */
  32. namespace OCA\Settings\Controller;
  33. use BadMethodCallException;
  34. use OC\Authentication\Exceptions\InvalidTokenException as OcInvalidTokenException;
  35. use OC\Authentication\Exceptions\PasswordlessTokenException;
  36. use OC\Authentication\Token\INamedToken;
  37. use OC\Authentication\Token\IProvider;
  38. use OC\Authentication\Token\RemoteWipe;
  39. use OCA\Settings\Activity\Provider;
  40. use OCP\Activity\IManager;
  41. use OCP\AppFramework\Controller;
  42. use OCP\AppFramework\Http;
  43. use OCP\AppFramework\Http\JSONResponse;
  44. use OCP\Authentication\Exceptions\ExpiredTokenException;
  45. use OCP\Authentication\Exceptions\InvalidTokenException;
  46. use OCP\Authentication\Exceptions\WipeTokenException;
  47. use OCP\Authentication\Token\IToken;
  48. use OCP\IRequest;
  49. use OCP\ISession;
  50. use OCP\IUserSession;
  51. use OCP\Security\ISecureRandom;
  52. use OCP\Session\Exceptions\SessionNotAvailableException;
  53. use Psr\Log\LoggerInterface;
  54. class AuthSettingsController extends Controller {
  55. /** @var IProvider */
  56. private $tokenProvider;
  57. /** @var ISession */
  58. private $session;
  59. /** @var IUserSession */
  60. private $userSession;
  61. /** @var string */
  62. private $uid;
  63. /** @var ISecureRandom */
  64. private $random;
  65. /** @var IManager */
  66. private $activityManager;
  67. /** @var RemoteWipe */
  68. private $remoteWipe;
  69. /** @var LoggerInterface */
  70. private $logger;
  71. /**
  72. * @param string $appName
  73. * @param IRequest $request
  74. * @param IProvider $tokenProvider
  75. * @param ISession $session
  76. * @param ISecureRandom $random
  77. * @param string|null $userId
  78. * @param IUserSession $userSession
  79. * @param IManager $activityManager
  80. * @param RemoteWipe $remoteWipe
  81. * @param LoggerInterface $logger
  82. */
  83. public function __construct(string $appName,
  84. IRequest $request,
  85. IProvider $tokenProvider,
  86. ISession $session,
  87. ISecureRandom $random,
  88. ?string $userId,
  89. IUserSession $userSession,
  90. IManager $activityManager,
  91. RemoteWipe $remoteWipe,
  92. LoggerInterface $logger) {
  93. parent::__construct($appName, $request);
  94. $this->tokenProvider = $tokenProvider;
  95. $this->uid = $userId;
  96. $this->userSession = $userSession;
  97. $this->session = $session;
  98. $this->random = $random;
  99. $this->activityManager = $activityManager;
  100. $this->remoteWipe = $remoteWipe;
  101. $this->logger = $logger;
  102. }
  103. /**
  104. * @NoAdminRequired
  105. * @NoSubAdminRequired
  106. * @PasswordConfirmationRequired
  107. *
  108. * @param string $name
  109. * @return JSONResponse
  110. */
  111. public function create($name) {
  112. if ($this->checkAppToken()) {
  113. return $this->getServiceNotAvailableResponse();
  114. }
  115. try {
  116. $sessionId = $this->session->getId();
  117. } catch (SessionNotAvailableException $ex) {
  118. return $this->getServiceNotAvailableResponse();
  119. }
  120. if ($this->userSession->getImpersonatingUserID() !== null) {
  121. return $this->getServiceNotAvailableResponse();
  122. }
  123. try {
  124. $sessionToken = $this->tokenProvider->getToken($sessionId);
  125. $loginName = $sessionToken->getLoginName();
  126. try {
  127. $password = $this->tokenProvider->getPassword($sessionToken, $sessionId);
  128. } catch (PasswordlessTokenException $ex) {
  129. $password = null;
  130. }
  131. } catch (InvalidTokenException $ex) {
  132. return $this->getServiceNotAvailableResponse();
  133. }
  134. if (mb_strlen($name) > 128) {
  135. $name = mb_substr($name, 0, 120) . '…';
  136. }
  137. $token = $this->generateRandomDeviceToken();
  138. $deviceToken = $this->tokenProvider->generateToken($token, $this->uid, $loginName, $password, $name, IToken::PERMANENT_TOKEN);
  139. $tokenData = $deviceToken->jsonSerialize();
  140. $tokenData['canDelete'] = true;
  141. $tokenData['canRename'] = true;
  142. $this->publishActivity(Provider::APP_TOKEN_CREATED, $deviceToken->getId(), ['name' => $deviceToken->getName()]);
  143. return new JSONResponse([
  144. 'token' => $token,
  145. 'loginName' => $loginName,
  146. 'deviceToken' => $tokenData,
  147. ]);
  148. }
  149. /**
  150. * @return JSONResponse
  151. */
  152. private function getServiceNotAvailableResponse() {
  153. $resp = new JSONResponse();
  154. $resp->setStatus(Http::STATUS_SERVICE_UNAVAILABLE);
  155. return $resp;
  156. }
  157. /**
  158. * Return a 25 digit device password
  159. *
  160. * Example: AbCdE-fGhJk-MnPqR-sTwXy-23456
  161. *
  162. * @return string
  163. */
  164. private function generateRandomDeviceToken() {
  165. $groups = [];
  166. for ($i = 0; $i < 5; $i++) {
  167. $groups[] = $this->random->generate(5, ISecureRandom::CHAR_HUMAN_READABLE);
  168. }
  169. return implode('-', $groups);
  170. }
  171. private function checkAppToken(): bool {
  172. return $this->session->exists('app_password');
  173. }
  174. /**
  175. * @NoAdminRequired
  176. * @NoSubAdminRequired
  177. *
  178. * @param int $id
  179. * @return array|JSONResponse
  180. */
  181. public function destroy($id) {
  182. if ($this->checkAppToken()) {
  183. return new JSONResponse([], Http::STATUS_BAD_REQUEST);
  184. }
  185. try {
  186. $token = $this->findTokenByIdAndUser($id);
  187. } catch (WipeTokenException $e) {
  188. //continue as we can destroy tokens in wipe
  189. $token = $e->getToken();
  190. } catch (InvalidTokenException $e) {
  191. return new JSONResponse([], Http::STATUS_NOT_FOUND);
  192. }
  193. $this->tokenProvider->invalidateTokenById($this->uid, $token->getId());
  194. $this->publishActivity(Provider::APP_TOKEN_DELETED, $token->getId(), ['name' => $token->getName()]);
  195. return [];
  196. }
  197. /**
  198. * @NoAdminRequired
  199. * @NoSubAdminRequired
  200. *
  201. * @param int $id
  202. * @param array $scope
  203. * @param string $name
  204. * @return array|JSONResponse
  205. */
  206. public function update($id, array $scope, string $name) {
  207. if ($this->checkAppToken()) {
  208. return new JSONResponse([], Http::STATUS_BAD_REQUEST);
  209. }
  210. try {
  211. $token = $this->findTokenByIdAndUser($id);
  212. } catch (InvalidTokenException $e) {
  213. return new JSONResponse([], Http::STATUS_NOT_FOUND);
  214. }
  215. $currentName = $token->getName();
  216. if ($scope !== $token->getScopeAsArray()) {
  217. $token->setScope(['filesystem' => $scope['filesystem']]);
  218. $this->publishActivity($scope['filesystem'] ? Provider::APP_TOKEN_FILESYSTEM_GRANTED : Provider::APP_TOKEN_FILESYSTEM_REVOKED, $token->getId(), ['name' => $currentName]);
  219. }
  220. if (mb_strlen($name) > 128) {
  221. $name = mb_substr($name, 0, 120) . '…';
  222. }
  223. if ($token instanceof INamedToken && $name !== $currentName) {
  224. $token->setName($name);
  225. $this->publishActivity(Provider::APP_TOKEN_RENAMED, $token->getId(), ['name' => $currentName, 'newName' => $name]);
  226. }
  227. $this->tokenProvider->updateToken($token);
  228. return [];
  229. }
  230. /**
  231. * @param string $subject
  232. * @param int $id
  233. * @param array $parameters
  234. */
  235. private function publishActivity(string $subject, int $id, array $parameters = []): void {
  236. $event = $this->activityManager->generateEvent();
  237. $event->setApp('settings')
  238. ->setType('security')
  239. ->setAffectedUser($this->uid)
  240. ->setAuthor($this->uid)
  241. ->setSubject($subject, $parameters)
  242. ->setObject('app_token', $id, 'App Password');
  243. try {
  244. $this->activityManager->publish($event);
  245. } catch (BadMethodCallException $e) {
  246. $this->logger->warning('could not publish activity', ['exception' => $e]);
  247. }
  248. }
  249. /**
  250. * Find a token by given id and check if uid for current session belongs to this token
  251. *
  252. * @param int $id
  253. * @return IToken
  254. * @throws InvalidTokenException
  255. */
  256. private function findTokenByIdAndUser(int $id): IToken {
  257. try {
  258. $token = $this->tokenProvider->getTokenById($id);
  259. } catch (ExpiredTokenException $e) {
  260. $token = $e->getToken();
  261. }
  262. if ($token->getUID() !== $this->uid) {
  263. /** @psalm-suppress DeprecatedClass We have to throw the OC version so both OC and OCP catches catch it */
  264. throw new OcInvalidTokenException('This token does not belong to you!');
  265. }
  266. return $token;
  267. }
  268. /**
  269. * @NoAdminRequired
  270. * @NoSubAdminRequired
  271. * @PasswordConfirmationRequired
  272. *
  273. * @param int $id
  274. * @return JSONResponse
  275. * @throws InvalidTokenException
  276. * @throws ExpiredTokenException
  277. */
  278. public function wipe(int $id): JSONResponse {
  279. if ($this->checkAppToken()) {
  280. return new JSONResponse([], Http::STATUS_BAD_REQUEST);
  281. }
  282. try {
  283. $token = $this->findTokenByIdAndUser($id);
  284. } catch (InvalidTokenException $e) {
  285. return new JSONResponse([], Http::STATUS_NOT_FOUND);
  286. }
  287. if (!$this->remoteWipe->markTokenForWipe($token)) {
  288. return new JSONResponse([], Http::STATUS_BAD_REQUEST);
  289. }
  290. return new JSONResponse([]);
  291. }
  292. }