1
0

LoginFlowV2Service.php 7.6 KB

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