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.

LoginFlowV2Service.php 7.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright Copyright (c) 2019, Roeland Jago Douma <roeland@famdouma.nl>
  5. *
  6. * @author Daniel Kesselberg <mail@danielkesselberg.de>
  7. * @author Roeland Jago Douma <roeland@famdouma.nl>
  8. *
  9. * @license GNU AGPL version 3 or any later version
  10. *
  11. * This program is free software: you can redistribute it and/or modify
  12. * it under the terms of the GNU Affero General Public License as
  13. * published by the Free Software Foundation, either version 3 of the
  14. * License, or (at your option) any later version.
  15. *
  16. * This program is distributed in the hope that it will be useful,
  17. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. * GNU Affero General Public License for more details.
  20. *
  21. * You should have received a copy of the GNU Affero General Public License
  22. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  23. *
  24. */
  25. namespace OC\Core\Service;
  26. use OC\Authentication\Exceptions\InvalidTokenException;
  27. use OC\Authentication\Exceptions\PasswordlessTokenException;
  28. use OC\Authentication\Token\IProvider;
  29. use OC\Authentication\Token\IToken;
  30. use OC\Core\Data\LoginFlowV2Credentials;
  31. use OC\Core\Data\LoginFlowV2Tokens;
  32. use OC\Core\Db\LoginFlowV2;
  33. use OC\Core\Db\LoginFlowV2Mapper;
  34. use OC\Core\Exception\LoginFlowV2NotFoundException;
  35. use OCP\AppFramework\Db\DoesNotExistException;
  36. use OCP\AppFramework\Utility\ITimeFactory;
  37. use OCP\IConfig;
  38. use OCP\Security\ICrypto;
  39. use OCP\Security\ISecureRandom;
  40. use Psr\Log\LoggerInterface;
  41. class LoginFlowV2Service {
  42. public function __construct(
  43. private LoginFlowV2Mapper $mapper,
  44. private ISecureRandom $random,
  45. private ITimeFactory $time,
  46. private IConfig $config,
  47. private ICrypto $crypto,
  48. private LoggerInterface $logger,
  49. private IProvider $tokenProvider,
  50. ) {
  51. }
  52. /**
  53. * @param string $pollToken
  54. * @return LoginFlowV2Credentials
  55. * @throws LoginFlowV2NotFoundException
  56. */
  57. public function poll(string $pollToken): LoginFlowV2Credentials {
  58. try {
  59. $data = $this->mapper->getByPollToken($this->hashToken($pollToken));
  60. } catch (DoesNotExistException $e) {
  61. throw new LoginFlowV2NotFoundException('Invalid token');
  62. }
  63. $loginName = $data->getLoginName();
  64. $server = $data->getServer();
  65. $appPassword = $data->getAppPassword();
  66. if ($loginName === null || $server === null || $appPassword === null) {
  67. throw new LoginFlowV2NotFoundException('Token not yet ready');
  68. }
  69. // Remove the data from the DB
  70. $this->mapper->delete($data);
  71. try {
  72. // Decrypt the apptoken
  73. $privateKey = $this->crypto->decrypt($data->getPrivateKey(), $pollToken);
  74. $appPassword = $this->decryptPassword($data->getAppPassword(), $privateKey);
  75. } catch (\Exception $e) {
  76. throw new LoginFlowV2NotFoundException('Apptoken could not be decrypted');
  77. }
  78. return new LoginFlowV2Credentials($server, $loginName, $appPassword);
  79. }
  80. /**
  81. * @param string $loginToken
  82. * @return LoginFlowV2
  83. * @throws LoginFlowV2NotFoundException
  84. */
  85. public function getByLoginToken(string $loginToken): LoginFlowV2 {
  86. try {
  87. return $this->mapper->getByLoginToken($loginToken);
  88. } catch (DoesNotExistException $e) {
  89. throw new LoginFlowV2NotFoundException('Login token invalid');
  90. }
  91. }
  92. /**
  93. * @param string $loginToken
  94. * @return bool returns true if the start was successfull. False if not.
  95. */
  96. public function startLoginFlow(string $loginToken): bool {
  97. try {
  98. $data = $this->mapper->getByLoginToken($loginToken);
  99. } catch (DoesNotExistException $e) {
  100. return false;
  101. }
  102. $data->setStarted(1);
  103. $this->mapper->update($data);
  104. return true;
  105. }
  106. /**
  107. * @param string $loginToken
  108. * @param string $sessionId
  109. * @param string $server
  110. * @param string $userId
  111. * @return bool true if the flow was successfully completed false otherwise
  112. */
  113. public function flowDone(string $loginToken, string $sessionId, string $server, string $userId): bool {
  114. try {
  115. $data = $this->mapper->getByLoginToken($loginToken);
  116. } catch (DoesNotExistException $e) {
  117. return false;
  118. }
  119. try {
  120. $sessionToken = $this->tokenProvider->getToken($sessionId);
  121. $loginName = $sessionToken->getLoginName();
  122. try {
  123. $password = $this->tokenProvider->getPassword($sessionToken, $sessionId);
  124. } catch (PasswordlessTokenException $ex) {
  125. $password = null;
  126. }
  127. } catch (InvalidTokenException $ex) {
  128. return false;
  129. }
  130. $appPassword = $this->random->generate(72, ISecureRandom::CHAR_UPPER.ISecureRandom::CHAR_LOWER.ISecureRandom::CHAR_DIGITS);
  131. $this->tokenProvider->generateToken(
  132. $appPassword,
  133. $userId,
  134. $loginName,
  135. $password,
  136. $data->getClientName(),
  137. IToken::PERMANENT_TOKEN,
  138. IToken::DO_NOT_REMEMBER
  139. );
  140. $data->setLoginName($loginName);
  141. $data->setServer($server);
  142. // Properly encrypt
  143. $data->setAppPassword($this->encryptPassword($appPassword, $data->getPublicKey()));
  144. $this->mapper->update($data);
  145. return true;
  146. }
  147. public function flowDoneWithAppPassword(string $loginToken, string $server, string $loginName, string $appPassword): bool {
  148. try {
  149. $data = $this->mapper->getByLoginToken($loginToken);
  150. } catch (DoesNotExistException $e) {
  151. return false;
  152. }
  153. $data->setLoginName($loginName);
  154. $data->setServer($server);
  155. // Properly encrypt
  156. $data->setAppPassword($this->encryptPassword($appPassword, $data->getPublicKey()));
  157. $this->mapper->update($data);
  158. return true;
  159. }
  160. public function createTokens(string $userAgent): LoginFlowV2Tokens {
  161. $flow = new LoginFlowV2();
  162. $pollToken = $this->random->generate(128, ISecureRandom::CHAR_DIGITS.ISecureRandom::CHAR_LOWER.ISecureRandom::CHAR_UPPER);
  163. $loginToken = $this->random->generate(128, ISecureRandom::CHAR_DIGITS.ISecureRandom::CHAR_LOWER.ISecureRandom::CHAR_UPPER);
  164. $flow->setPollToken($this->hashToken($pollToken));
  165. $flow->setLoginToken($loginToken);
  166. $flow->setStarted(0);
  167. $flow->setTimestamp($this->time->getTime());
  168. $flow->setClientName($userAgent);
  169. [$publicKey, $privateKey] = $this->getKeyPair();
  170. $privateKey = $this->crypto->encrypt($privateKey, $pollToken);
  171. $flow->setPublicKey($publicKey);
  172. $flow->setPrivateKey($privateKey);
  173. $this->mapper->insert($flow);
  174. return new LoginFlowV2Tokens($loginToken, $pollToken);
  175. }
  176. private function hashToken(string $token): string {
  177. $secret = $this->config->getSystemValue('secret');
  178. return hash('sha512', $token . $secret);
  179. }
  180. private function getKeyPair(): array {
  181. $config = array_merge([
  182. 'digest_alg' => 'sha512',
  183. 'private_key_bits' => 2048,
  184. ], $this->config->getSystemValue('openssl', []));
  185. // Generate new key
  186. $res = openssl_pkey_new($config);
  187. if ($res === false) {
  188. $this->logOpensslError();
  189. throw new \RuntimeException('Could not initialize keys');
  190. }
  191. if (openssl_pkey_export($res, $privateKey, null, $config) === false) {
  192. $this->logOpensslError();
  193. throw new \RuntimeException('OpenSSL reported a problem');
  194. }
  195. // Extract the public key from $res to $pubKey
  196. $publicKey = openssl_pkey_get_details($res);
  197. $publicKey = $publicKey['key'];
  198. return [$publicKey, $privateKey];
  199. }
  200. private function logOpensslError(): void {
  201. $errors = [];
  202. while ($error = openssl_error_string()) {
  203. $errors[] = $error;
  204. }
  205. $this->logger->critical('Something is wrong with your openssl setup: ' . implode(', ', $errors));
  206. }
  207. private function encryptPassword(string $password, string $publicKey): string {
  208. openssl_public_encrypt($password, $encryptedPassword, $publicKey, OPENSSL_PKCS1_OAEP_PADDING);
  209. $encryptedPassword = base64_encode($encryptedPassword);
  210. return $encryptedPassword;
  211. }
  212. private function decryptPassword(string $encryptedPassword, string $privateKey): string {
  213. $encryptedPassword = base64_decode($encryptedPassword);
  214. openssl_private_decrypt($encryptedPassword, $password, $privateKey, OPENSSL_PKCS1_OAEP_PADDING);
  215. return $password;
  216. }
  217. }