You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

439 lines
13 KiB

3 years ago
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright Copyright 2018, Roeland Jago Douma <roeland@famdouma.nl>
  5. *
  6. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  7. * @author Daniel Kesselberg <mail@danielkesselberg.de>
  8. * @author Joas Schilling <coding@schilljs.com>
  9. * @author Morris Jobke <hey@morrisjobke.de>
  10. * @author Roeland Jago Douma <roeland@famdouma.nl>
  11. *
  12. * @license GNU AGPL version 3 or any later version
  13. *
  14. * This program is free software: you can redistribute it and/or modify
  15. * it under the terms of the GNU Affero General Public License as
  16. * published by the Free Software Foundation, either version 3 of the
  17. * License, or (at your option) any later version.
  18. *
  19. * This program is distributed in the hope that it will be useful,
  20. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  21. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  22. * GNU Affero General Public License for more details.
  23. *
  24. * You should have received a copy of the GNU Affero General Public License
  25. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  26. *
  27. */
  28. namespace OC\Authentication\Token;
  29. use OC\Authentication\Exceptions\ExpiredTokenException;
  30. use OC\Authentication\Exceptions\InvalidTokenException;
  31. use OC\Authentication\Exceptions\TokenPasswordExpiredException;
  32. use OC\Authentication\Exceptions\PasswordlessTokenException;
  33. use OC\Authentication\Exceptions\WipeTokenException;
  34. use OC\Cache\CappedMemoryCache;
  35. use OCP\AppFramework\Db\DoesNotExistException;
  36. use OCP\AppFramework\Utility\ITimeFactory;
  37. use OCP\IConfig;
  38. use OCP\ILogger;
  39. use OCP\Security\ICrypto;
  40. class PublicKeyTokenProvider implements IProvider {
  41. /** @var PublicKeyTokenMapper */
  42. private $mapper;
  43. /** @var ICrypto */
  44. private $crypto;
  45. /** @var IConfig */
  46. private $config;
  47. /** @var ILogger $logger */
  48. private $logger;
  49. /** @var ITimeFactory $time */
  50. private $time;
  51. /** @var CappedMemoryCache */
  52. private $cache;
  53. public function __construct(PublicKeyTokenMapper $mapper,
  54. ICrypto $crypto,
  55. IConfig $config,
  56. ILogger $logger,
  57. ITimeFactory $time) {
  58. $this->mapper = $mapper;
  59. $this->crypto = $crypto;
  60. $this->config = $config;
  61. $this->logger = $logger;
  62. $this->time = $time;
  63. $this->cache = new CappedMemoryCache();
  64. }
  65. /**
  66. * {@inheritDoc}
  67. */
  68. public function generateToken(string $token,
  69. string $uid,
  70. string $loginName,
  71. $password,
  72. string $name,
  73. int $type = IToken::TEMPORARY_TOKEN,
  74. int $remember = IToken::DO_NOT_REMEMBER): IToken {
  75. $dbToken = $this->newToken($token, $uid, $loginName, $password, $name, $type, $remember);
  76. $this->mapper->insert($dbToken);
  77. // Add the token to the cache
  78. $this->cache[$dbToken->getToken()] = $dbToken;
  79. return $dbToken;
  80. }
  81. public function getToken(string $tokenId): IToken {
  82. $tokenHash = $this->hashToken($tokenId);
  83. if (isset($this->cache[$tokenHash])) {
  84. $token = $this->cache[$tokenHash];
  85. } else {
  86. try {
  87. $token = $this->mapper->getToken($this->hashToken($tokenId));
  88. $this->cache[$token->getToken()] = $token;
  89. } catch (DoesNotExistException $ex) {
  90. throw new InvalidTokenException("Token does not exist: " . $ex->getMessage(), 0, $ex);
  91. }
  92. }
  93. if ((int)$token->getExpires() !== 0 && $token->getExpires() < $this->time->getTime()) {
  94. throw new ExpiredTokenException($token);
  95. }
  96. if ($token->getType() === IToken::WIPE_TOKEN) {
  97. throw new WipeTokenException($token);
  98. }
  99. if ($token->getPasswordInvalid() === true) {
  100. //The password is invalid we should throw an TokenPasswordExpiredException
  101. throw new TokenPasswordExpiredException($token);
  102. }
  103. return $token;
  104. }
  105. public function getTokenById(int $tokenId): IToken {
  106. try {
  107. $token = $this->mapper->getTokenById($tokenId);
  108. } catch (DoesNotExistException $ex) {
  109. throw new InvalidTokenException("Token with ID $tokenId does not exist: " . $ex->getMessage(), 0, $ex);
  110. }
  111. if ((int)$token->getExpires() !== 0 && $token->getExpires() < $this->time->getTime()) {
  112. throw new ExpiredTokenException($token);
  113. }
  114. if ($token->getType() === IToken::WIPE_TOKEN) {
  115. throw new WipeTokenException($token);
  116. }
  117. if ($token->getPasswordInvalid() === true) {
  118. //The password is invalid we should throw an TokenPasswordExpiredException
  119. throw new TokenPasswordExpiredException($token);
  120. }
  121. return $token;
  122. }
  123. public function renewSessionToken(string $oldSessionId, string $sessionId): IToken {
  124. $this->cache->clear();
  125. $token = $this->getToken($oldSessionId);
  126. if (!($token instanceof PublicKeyToken)) {
  127. throw new InvalidTokenException("Invalid token type");
  128. }
  129. $password = null;
  130. if (!is_null($token->getPassword())) {
  131. $privateKey = $this->decrypt($token->getPrivateKey(), $oldSessionId);
  132. $password = $this->decryptPassword($token->getPassword(), $privateKey);
  133. }
  134. $newToken = $this->generateToken(
  135. $sessionId,
  136. $token->getUID(),
  137. $token->getLoginName(),
  138. $password,
  139. $token->getName(),
  140. IToken::TEMPORARY_TOKEN,
  141. $token->getRemember()
  142. );
  143. $this->mapper->delete($token);
  144. return $newToken;
  145. }
  146. public function invalidateToken(string $token) {
  147. $this->cache->clear();
  148. $this->mapper->invalidate($this->hashToken($token));
  149. }
  150. public function invalidateTokenById(string $uid, int $id) {
  151. $this->cache->clear();
  152. $this->mapper->deleteById($uid, $id);
  153. }
  154. public function invalidateOldTokens() {
  155. $this->cache->clear();
  156. $olderThan = $this->time->getTime() - (int) $this->config->getSystemValue('session_lifetime', 60 * 60 * 24);
  157. $this->logger->debug('Invalidating session tokens older than ' . date('c', $olderThan), ['app' => 'cron']);
  158. $this->mapper->invalidateOld($olderThan, IToken::DO_NOT_REMEMBER);
  159. $rememberThreshold = $this->time->getTime() - (int) $this->config->getSystemValue('remember_login_cookie_lifetime', 60 * 60 * 24 * 15);
  160. $this->logger->debug('Invalidating remembered session tokens older than ' . date('c', $rememberThreshold), ['app' => 'cron']);
  161. $this->mapper->invalidateOld($rememberThreshold, IToken::REMEMBER);
  162. }
  163. public function updateToken(IToken $token) {
  164. $this->cache->clear();
  165. if (!($token instanceof PublicKeyToken)) {
  166. throw new InvalidTokenException("Invalid token type");
  167. }
  168. $this->mapper->update($token);
  169. }
  170. public function updateTokenActivity(IToken $token) {
  171. $this->cache->clear();
  172. if (!($token instanceof PublicKeyToken)) {
  173. throw new InvalidTokenException("Invalid token type");
  174. }
  175. $activityInterval = $this->config->getSystemValueInt('token_auth_activity_update', 60);
  176. $activityInterval = min(max($activityInterval, 0), 300);
  177. /** @var DefaultToken $token */
  178. $now = $this->time->getTime();
  179. if ($token->getLastActivity() < ($now - $activityInterval)) {
  180. // Update token only once per minute
  181. $token->setLastActivity($now);
  182. $this->mapper->update($token);
  183. }
  184. }
  185. public function getTokenByUser(string $uid): array {
  186. return $this->mapper->getTokenByUser($uid);
  187. }
  188. public function getPassword(IToken $savedToken, string $tokenId): string {
  189. if (!($savedToken instanceof PublicKeyToken)) {
  190. throw new InvalidTokenException("Invalid token type");
  191. }
  192. if ($savedToken->getPassword() === null) {
  193. throw new PasswordlessTokenException();
  194. }
  195. // Decrypt private key with tokenId
  196. $privateKey = $this->decrypt($savedToken->getPrivateKey(), $tokenId);
  197. // Decrypt password with private key
  198. return $this->decryptPassword($savedToken->getPassword(), $privateKey);
  199. }
  200. public function setPassword(IToken $token, string $tokenId, string $password) {
  201. $this->cache->clear();
  202. if (!($token instanceof PublicKeyToken)) {
  203. throw new InvalidTokenException("Invalid token type");
  204. }
  205. // When changing passwords all temp tokens are deleted
  206. $this->mapper->deleteTempToken($token);
  207. // Update the password for all tokens
  208. $tokens = $this->mapper->getTokenByUser($token->getUID());
  209. foreach ($tokens as $t) {
  210. $publicKey = $t->getPublicKey();
  211. $t->setPassword($this->encryptPassword($password, $publicKey));
  212. $this->updateToken($t);
  213. }
  214. }
  215. public function rotate(IToken $token, string $oldTokenId, string $newTokenId): IToken {
  216. $this->cache->clear();
  217. if (!($token instanceof PublicKeyToken)) {
  218. throw new InvalidTokenException("Invalid token type");
  219. }
  220. // Decrypt private key with oldTokenId
  221. $privateKey = $this->decrypt($token->getPrivateKey(), $oldTokenId);
  222. // Encrypt with the new token
  223. $token->setPrivateKey($this->encrypt($privateKey, $newTokenId));
  224. $token->setToken($this->hashToken($newTokenId));
  225. $this->updateToken($token);
  226. return $token;
  227. }
  228. private function encrypt(string $plaintext, string $token): string {
  229. $secret = $this->config->getSystemValue('secret');
  230. return $this->crypto->encrypt($plaintext, $token . $secret);
  231. }
  232. /**
  233. * @throws InvalidTokenException
  234. */
  235. private function decrypt(string $cipherText, string $token): string {
  236. $secret = $this->config->getSystemValue('secret');
  237. try {
  238. return $this->crypto->decrypt($cipherText, $token . $secret);
  239. } catch (\Exception $ex) {
  240. // Delete the invalid token
  241. $this->invalidateToken($token);
  242. throw new InvalidTokenException("Could not decrypt token password: " . $ex->getMessage(), 0, $ex);
  243. }
  244. }
  245. private function encryptPassword(string $password, string $publicKey): string {
  246. openssl_public_encrypt($password, $encryptedPassword, $publicKey, OPENSSL_PKCS1_OAEP_PADDING);
  247. $encryptedPassword = base64_encode($encryptedPassword);
  248. return $encryptedPassword;
  249. }
  250. private function decryptPassword(string $encryptedPassword, string $privateKey): string {
  251. $encryptedPassword = base64_decode($encryptedPassword);
  252. openssl_private_decrypt($encryptedPassword, $password, $privateKey, OPENSSL_PKCS1_OAEP_PADDING);
  253. return $password;
  254. }
  255. private function hashToken(string $token): string {
  256. $secret = $this->config->getSystemValue('secret');
  257. return hash('sha512', $token . $secret);
  258. }
  259. /**
  260. * Convert a DefaultToken to a publicKeyToken
  261. * This will also be updated directly in the Database
  262. * @throws \RuntimeException when OpenSSL reports a problem
  263. */
  264. public function convertToken(DefaultToken $defaultToken, string $token, $password): PublicKeyToken {
  265. $this->cache->clear();
  266. $pkToken = $this->newToken(
  267. $token,
  268. $defaultToken->getUID(),
  269. $defaultToken->getLoginName(),
  270. $password,
  271. $defaultToken->getName(),
  272. $defaultToken->getType(),
  273. $defaultToken->getRemember()
  274. );
  275. $pkToken->setExpires($defaultToken->getExpires());
  276. $pkToken->setId($defaultToken->getId());
  277. return $this->mapper->update($pkToken);
  278. }
  279. /**
  280. * @throws \RuntimeException when OpenSSL reports a problem
  281. */
  282. private function newToken(string $token,
  283. string $uid,
  284. string $loginName,
  285. $password,
  286. string $name,
  287. int $type,
  288. int $remember): PublicKeyToken {
  289. $dbToken = new PublicKeyToken();
  290. $dbToken->setUid($uid);
  291. $dbToken->setLoginName($loginName);
  292. $config = array_merge([
  293. 'digest_alg' => 'sha512',
  294. 'private_key_bits' => 2048,
  295. ], $this->config->getSystemValue('openssl', []));
  296. // Generate new key
  297. $res = openssl_pkey_new($config);
  298. if ($res === false) {
  299. $this->logOpensslError();
  300. throw new \RuntimeException('OpenSSL reported a problem');
  301. }
  302. if (openssl_pkey_export($res, $privateKey, null, $config) === false) {
  303. $this->logOpensslError();
  304. throw new \RuntimeException('OpenSSL reported a problem');
  305. }
  306. // Extract the public key from $res to $pubKey
  307. $publicKey = openssl_pkey_get_details($res);
  308. $publicKey = $publicKey['key'];
  309. $dbToken->setPublicKey($publicKey);
  310. $dbToken->setPrivateKey($this->encrypt($privateKey, $token));
  311. if (!is_null($password)) {
  312. $dbToken->setPassword($this->encryptPassword($password, $publicKey));
  313. }
  314. $dbToken->setName($name);
  315. $dbToken->setToken($this->hashToken($token));
  316. $dbToken->setType($type);
  317. $dbToken->setRemember($remember);
  318. $dbToken->setLastActivity($this->time->getTime());
  319. $dbToken->setLastCheck($this->time->getTime());
  320. $dbToken->setVersion(PublicKeyToken::VERSION);
  321. return $dbToken;
  322. }
  323. public function markPasswordInvalid(IToken $token, string $tokenId) {
  324. $this->cache->clear();
  325. if (!($token instanceof PublicKeyToken)) {
  326. throw new InvalidTokenException("Invalid token type");
  327. }
  328. $token->setPasswordInvalid(true);
  329. $this->mapper->update($token);
  330. }
  331. public function updatePasswords(string $uid, string $password) {
  332. $this->cache->clear();
  333. if (!$this->mapper->hasExpiredTokens($uid)) {
  334. // Nothing to do here
  335. return;
  336. }
  337. // Update the password for all tokens
  338. $tokens = $this->mapper->getTokenByUser($uid);
  339. foreach ($tokens as $t) {
  340. $publicKey = $t->getPublicKey();
  341. $t->setPassword($this->encryptPassword($password, $publicKey));
  342. $t->setPasswordInvalid(false);
  343. $this->updateToken($t);
  344. }
  345. }
  346. private function logOpensslError() {
  347. $errors = [];
  348. while ($error = openssl_error_string()) {
  349. $errors[] = $error;
  350. }
  351. $this->logger->critical('Something is wrong with your openssl setup: ' . implode(', ', $errors));
  352. }
  353. }