PublicKeyTokenProvider.php 10.0 KB

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