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.

PublicKeyTokenProvider.php 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  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 OCP\Cache\CappedMemoryCache;
  35. use OCP\AppFramework\Db\DoesNotExistException;
  36. use OCP\AppFramework\Utility\ITimeFactory;
  37. use OCP\IConfig;
  38. use OCP\Security\ICrypto;
  39. use Psr\Log\LoggerInterface;
  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 LoggerInterface */
  48. private $logger;
  49. /** @var ITimeFactory */
  50. private $time;
  51. /** @var CappedMemoryCache */
  52. private $cache;
  53. public function __construct(PublicKeyTokenMapper $mapper,
  54. ICrypto $crypto,
  55. IConfig $config,
  56. LoggerInterface $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. ?string $password,
  72. string $name,
  73. int $type = IToken::TEMPORARY_TOKEN,
  74. int $remember = IToken::DO_NOT_REMEMBER): IToken {
  75. if (mb_strlen($name) > 128) {
  76. $name = mb_substr($name, 0, 120) . '…';
  77. }
  78. $dbToken = $this->newToken($token, $uid, $loginName, $password, $name, $type, $remember);
  79. $this->mapper->insert($dbToken);
  80. // Add the token to the cache
  81. $this->cache[$dbToken->getToken()] = $dbToken;
  82. return $dbToken;
  83. }
  84. public function getToken(string $tokenId): IToken {
  85. $tokenHash = $this->hashToken($tokenId);
  86. if (isset($this->cache[$tokenHash])) {
  87. if ($this->cache[$tokenHash] instanceof DoesNotExistException) {
  88. $ex = $this->cache[$tokenHash];
  89. throw new InvalidTokenException("Token does not exist: " . $ex->getMessage(), 0, $ex);
  90. }
  91. $token = $this->cache[$tokenHash];
  92. } else {
  93. try {
  94. $token = $this->mapper->getToken($this->hashToken($tokenId));
  95. $this->cache[$token->getToken()] = $token;
  96. } catch (DoesNotExistException $ex) {
  97. $this->cache[$tokenHash] = $ex;
  98. throw new InvalidTokenException("Token does not exist: " . $ex->getMessage(), 0, $ex);
  99. }
  100. }
  101. if ((int)$token->getExpires() !== 0 && $token->getExpires() < $this->time->getTime()) {
  102. throw new ExpiredTokenException($token);
  103. }
  104. if ($token->getType() === IToken::WIPE_TOKEN) {
  105. throw new WipeTokenException($token);
  106. }
  107. if ($token->getPasswordInvalid() === true) {
  108. //The password is invalid we should throw an TokenPasswordExpiredException
  109. throw new TokenPasswordExpiredException($token);
  110. }
  111. return $token;
  112. }
  113. public function getTokenById(int $tokenId): IToken {
  114. try {
  115. $token = $this->mapper->getTokenById($tokenId);
  116. } catch (DoesNotExistException $ex) {
  117. throw new InvalidTokenException("Token with ID $tokenId does not exist: " . $ex->getMessage(), 0, $ex);
  118. }
  119. if ((int)$token->getExpires() !== 0 && $token->getExpires() < $this->time->getTime()) {
  120. throw new ExpiredTokenException($token);
  121. }
  122. if ($token->getType() === IToken::WIPE_TOKEN) {
  123. throw new WipeTokenException($token);
  124. }
  125. if ($token->getPasswordInvalid() === true) {
  126. //The password is invalid we should throw an TokenPasswordExpiredException
  127. throw new TokenPasswordExpiredException($token);
  128. }
  129. return $token;
  130. }
  131. public function renewSessionToken(string $oldSessionId, string $sessionId): IToken {
  132. $this->cache->clear();
  133. $token = $this->getToken($oldSessionId);
  134. if (!($token instanceof PublicKeyToken)) {
  135. throw new InvalidTokenException("Invalid token type");
  136. }
  137. $password = null;
  138. if (!is_null($token->getPassword())) {
  139. $privateKey = $this->decrypt($token->getPrivateKey(), $oldSessionId);
  140. $password = $this->decryptPassword($token->getPassword(), $privateKey);
  141. }
  142. $newToken = $this->generateToken(
  143. $sessionId,
  144. $token->getUID(),
  145. $token->getLoginName(),
  146. $password,
  147. $token->getName(),
  148. IToken::TEMPORARY_TOKEN,
  149. $token->getRemember()
  150. );
  151. $this->mapper->delete($token);
  152. return $newToken;
  153. }
  154. public function invalidateToken(string $token) {
  155. $this->cache->clear();
  156. $this->mapper->invalidate($this->hashToken($token));
  157. }
  158. public function invalidateTokenById(string $uid, int $id) {
  159. $this->cache->clear();
  160. $this->mapper->deleteById($uid, $id);
  161. }
  162. public function invalidateOldTokens() {
  163. $this->cache->clear();
  164. $olderThan = $this->time->getTime() - (int) $this->config->getSystemValue('session_lifetime', 60 * 60 * 24);
  165. $this->logger->debug('Invalidating session tokens older than ' . date('c', $olderThan), ['app' => 'cron']);
  166. $this->mapper->invalidateOld($olderThan, IToken::DO_NOT_REMEMBER);
  167. $rememberThreshold = $this->time->getTime() - (int) $this->config->getSystemValue('remember_login_cookie_lifetime', 60 * 60 * 24 * 15);
  168. $this->logger->debug('Invalidating remembered session tokens older than ' . date('c', $rememberThreshold), ['app' => 'cron']);
  169. $this->mapper->invalidateOld($rememberThreshold, IToken::REMEMBER);
  170. }
  171. public function updateToken(IToken $token) {
  172. $this->cache->clear();
  173. if (!($token instanceof PublicKeyToken)) {
  174. throw new InvalidTokenException("Invalid token type");
  175. }
  176. $this->mapper->update($token);
  177. }
  178. public function updateTokenActivity(IToken $token) {
  179. $this->cache->clear();
  180. if (!($token instanceof PublicKeyToken)) {
  181. throw new InvalidTokenException("Invalid token type");
  182. }
  183. $activityInterval = $this->config->getSystemValueInt('token_auth_activity_update', 60);
  184. $activityInterval = min(max($activityInterval, 0), 300);
  185. /** @var PublicKeyToken $token */
  186. $now = $this->time->getTime();
  187. if ($token->getLastActivity() < ($now - $activityInterval)) {
  188. $token->setLastActivity($now);
  189. $this->mapper->updateActivity($token, $now);
  190. }
  191. }
  192. public function getTokenByUser(string $uid): array {
  193. return $this->mapper->getTokenByUser($uid);
  194. }
  195. public function getPassword(IToken $savedToken, string $tokenId): string {
  196. if (!($savedToken instanceof PublicKeyToken)) {
  197. throw new InvalidTokenException("Invalid token type");
  198. }
  199. if ($savedToken->getPassword() === null) {
  200. throw new PasswordlessTokenException();
  201. }
  202. // Decrypt private key with tokenId
  203. $privateKey = $this->decrypt($savedToken->getPrivateKey(), $tokenId);
  204. // Decrypt password with private key
  205. return $this->decryptPassword($savedToken->getPassword(), $privateKey);
  206. }
  207. public function setPassword(IToken $token, string $tokenId, string $password) {
  208. $this->cache->clear();
  209. if (!($token instanceof PublicKeyToken)) {
  210. throw new InvalidTokenException("Invalid token type");
  211. }
  212. // When changing passwords all temp tokens are deleted
  213. $this->mapper->deleteTempToken($token);
  214. // Update the password for all tokens
  215. $tokens = $this->mapper->getTokenByUser($token->getUID());
  216. foreach ($tokens as $t) {
  217. $publicKey = $t->getPublicKey();
  218. $t->setPassword($this->encryptPassword($password, $publicKey));
  219. $this->updateToken($t);
  220. }
  221. }
  222. public function rotate(IToken $token, string $oldTokenId, string $newTokenId): IToken {
  223. $this->cache->clear();
  224. if (!($token instanceof PublicKeyToken)) {
  225. throw new InvalidTokenException("Invalid token type");
  226. }
  227. // Decrypt private key with oldTokenId
  228. $privateKey = $this->decrypt($token->getPrivateKey(), $oldTokenId);
  229. // Encrypt with the new token
  230. $token->setPrivateKey($this->encrypt($privateKey, $newTokenId));
  231. $token->setToken($this->hashToken($newTokenId));
  232. $this->updateToken($token);
  233. return $token;
  234. }
  235. private function encrypt(string $plaintext, string $token): string {
  236. $secret = $this->config->getSystemValue('secret');
  237. return $this->crypto->encrypt($plaintext, $token . $secret);
  238. }
  239. /**
  240. * @throws InvalidTokenException
  241. */
  242. private function decrypt(string $cipherText, string $token): string {
  243. $secret = $this->config->getSystemValue('secret');
  244. try {
  245. return $this->crypto->decrypt($cipherText, $token . $secret);
  246. } catch (\Exception $ex) {
  247. // Delete the invalid token
  248. $this->invalidateToken($token);
  249. throw new InvalidTokenException("Could not decrypt token password: " . $ex->getMessage(), 0, $ex);
  250. }
  251. }
  252. private function encryptPassword(string $password, string $publicKey): string {
  253. openssl_public_encrypt($password, $encryptedPassword, $publicKey, OPENSSL_PKCS1_OAEP_PADDING);
  254. $encryptedPassword = base64_encode($encryptedPassword);
  255. return $encryptedPassword;
  256. }
  257. private function decryptPassword(string $encryptedPassword, string $privateKey): string {
  258. $encryptedPassword = base64_decode($encryptedPassword);
  259. openssl_private_decrypt($encryptedPassword, $password, $privateKey, OPENSSL_PKCS1_OAEP_PADDING);
  260. return $password;
  261. }
  262. private function hashToken(string $token): string {
  263. $secret = $this->config->getSystemValue('secret');
  264. return hash('sha512', $token . $secret);
  265. }
  266. /**
  267. * @throws \RuntimeException when OpenSSL reports a problem
  268. */
  269. private function newToken(string $token,
  270. string $uid,
  271. string $loginName,
  272. $password,
  273. string $name,
  274. int $type,
  275. int $remember): PublicKeyToken {
  276. $dbToken = new PublicKeyToken();
  277. $dbToken->setUid($uid);
  278. $dbToken->setLoginName($loginName);
  279. $config = array_merge([
  280. 'digest_alg' => 'sha512',
  281. 'private_key_bits' => $password !== null && strlen($password) > 250 ? 4096 : 2048,
  282. ], $this->config->getSystemValue('openssl', []));
  283. // Generate new key
  284. $res = openssl_pkey_new($config);
  285. if ($res === false) {
  286. $this->logOpensslError();
  287. throw new \RuntimeException('OpenSSL reported a problem');
  288. }
  289. if (openssl_pkey_export($res, $privateKey, null, $config) === false) {
  290. $this->logOpensslError();
  291. throw new \RuntimeException('OpenSSL reported a problem');
  292. }
  293. // Extract the public key from $res to $pubKey
  294. $publicKey = openssl_pkey_get_details($res);
  295. $publicKey = $publicKey['key'];
  296. $dbToken->setPublicKey($publicKey);
  297. $dbToken->setPrivateKey($this->encrypt($privateKey, $token));
  298. if (!is_null($password) && $this->config->getSystemValueBool('auth.storeCryptedPassword', true)) {
  299. if (strlen($password) > 469) {
  300. throw new \RuntimeException('Trying to save a password with more than 469 characters is not supported. If you want to use big passwords, disable the auth.storeCryptedPassword option in config.php');
  301. }
  302. $dbToken->setPassword($this->encryptPassword($password, $publicKey));
  303. }
  304. $dbToken->setName($name);
  305. $dbToken->setToken($this->hashToken($token));
  306. $dbToken->setType($type);
  307. $dbToken->setRemember($remember);
  308. $dbToken->setLastActivity($this->time->getTime());
  309. $dbToken->setLastCheck($this->time->getTime());
  310. $dbToken->setVersion(PublicKeyToken::VERSION);
  311. return $dbToken;
  312. }
  313. public function markPasswordInvalid(IToken $token, string $tokenId) {
  314. $this->cache->clear();
  315. if (!($token instanceof PublicKeyToken)) {
  316. throw new InvalidTokenException("Invalid token type");
  317. }
  318. $token->setPasswordInvalid(true);
  319. $this->mapper->update($token);
  320. }
  321. public function updatePasswords(string $uid, string $password) {
  322. $this->cache->clear();
  323. // prevent setting an empty pw as result of pw-less-login
  324. if ($password === '' || !$this->config->getSystemValueBool('auth.storeCryptedPassword', true)) {
  325. return;
  326. }
  327. // Update the password for all tokens
  328. $tokens = $this->mapper->getTokenByUser($uid);
  329. foreach ($tokens as $t) {
  330. $publicKey = $t->getPublicKey();
  331. $encryptedPassword = $this->encryptPassword($password, $publicKey);
  332. if ($t->getPassword() !== $encryptedPassword) {
  333. $t->setPassword($encryptedPassword);
  334. $t->setPasswordInvalid(false);
  335. $this->updateToken($t);
  336. }
  337. }
  338. }
  339. private function logOpensslError() {
  340. $errors = [];
  341. while ($error = openssl_error_string()) {
  342. $errors[] = $error;
  343. }
  344. $this->logger->critical('Something is wrong with your openssl setup: ' . implode(', ', $errors));
  345. }
  346. }