LoginFlowV2Service.php 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  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. private LoginFlowV2Mapper $mapper;
  43. private ISecureRandom $random;
  44. private ITimeFactory $time;
  45. private IConfig $config;
  46. private ICrypto $crypto;
  47. private LoggerInterface $logger;
  48. private IProvider $tokenProvider;
  49. public function __construct(LoginFlowV2Mapper $mapper,
  50. ISecureRandom $random,
  51. ITimeFactory $time,
  52. IConfig $config,
  53. ICrypto $crypto,
  54. LoggerInterface $logger,
  55. IProvider $tokenProvider) {
  56. $this->mapper = $mapper;
  57. $this->random = $random;
  58. $this->time = $time;
  59. $this->config = $config;
  60. $this->crypto = $crypto;
  61. $this->logger = $logger;
  62. $this->tokenProvider = $tokenProvider;
  63. }
  64. /**
  65. * @param string $pollToken
  66. * @return LoginFlowV2Credentials
  67. * @throws LoginFlowV2NotFoundException
  68. */
  69. public function poll(string $pollToken): LoginFlowV2Credentials {
  70. try {
  71. $data = $this->mapper->getByPollToken($this->hashToken($pollToken));
  72. } catch (DoesNotExistException $e) {
  73. throw new LoginFlowV2NotFoundException('Invalid token');
  74. }
  75. $loginName = $data->getLoginName();
  76. $server = $data->getServer();
  77. $appPassword = $data->getAppPassword();
  78. if ($loginName === null || $server === null || $appPassword === null) {
  79. throw new LoginFlowV2NotFoundException('Token not yet ready');
  80. }
  81. // Remove the data from the DB
  82. $this->mapper->delete($data);
  83. try {
  84. // Decrypt the apptoken
  85. $privateKey = $this->crypto->decrypt($data->getPrivateKey(), $pollToken);
  86. $appPassword = $this->decryptPassword($data->getAppPassword(), $privateKey);
  87. } catch (\Exception $e) {
  88. throw new LoginFlowV2NotFoundException('Apptoken could not be decrypted');
  89. }
  90. return new LoginFlowV2Credentials($server, $loginName, $appPassword);
  91. }
  92. /**
  93. * @param string $loginToken
  94. * @return LoginFlowV2
  95. * @throws LoginFlowV2NotFoundException
  96. */
  97. public function getByLoginToken(string $loginToken): LoginFlowV2 {
  98. try {
  99. return $this->mapper->getByLoginToken($loginToken);
  100. } catch (DoesNotExistException $e) {
  101. throw new LoginFlowV2NotFoundException('Login token invalid');
  102. }
  103. }
  104. /**
  105. * @param string $loginToken
  106. * @return bool returns true if the start was successfull. False if not.
  107. */
  108. public function startLoginFlow(string $loginToken): bool {
  109. try {
  110. $data = $this->mapper->getByLoginToken($loginToken);
  111. } catch (DoesNotExistException $e) {
  112. return false;
  113. }
  114. $data->setStarted(1);
  115. $this->mapper->update($data);
  116. return true;
  117. }
  118. /**
  119. * @param string $loginToken
  120. * @param string $sessionId
  121. * @param string $server
  122. * @param string $userId
  123. * @return bool true if the flow was successfully completed false otherwise
  124. */
  125. public function flowDone(string $loginToken, string $sessionId, string $server, string $userId): bool {
  126. try {
  127. $data = $this->mapper->getByLoginToken($loginToken);
  128. } catch (DoesNotExistException $e) {
  129. return false;
  130. }
  131. try {
  132. $sessionToken = $this->tokenProvider->getToken($sessionId);
  133. $loginName = $sessionToken->getLoginName();
  134. try {
  135. $password = $this->tokenProvider->getPassword($sessionToken, $sessionId);
  136. } catch (PasswordlessTokenException $ex) {
  137. $password = null;
  138. }
  139. } catch (InvalidTokenException $ex) {
  140. return false;
  141. }
  142. $appPassword = $this->random->generate(72, ISecureRandom::CHAR_UPPER.ISecureRandom::CHAR_LOWER.ISecureRandom::CHAR_DIGITS);
  143. $this->tokenProvider->generateToken(
  144. $appPassword,
  145. $userId,
  146. $loginName,
  147. $password,
  148. $data->getClientName(),
  149. IToken::PERMANENT_TOKEN,
  150. IToken::DO_NOT_REMEMBER
  151. );
  152. $data->setLoginName($loginName);
  153. $data->setServer($server);
  154. // Properly encrypt
  155. $data->setAppPassword($this->encryptPassword($appPassword, $data->getPublicKey()));
  156. $this->mapper->update($data);
  157. return true;
  158. }
  159. public function flowDoneWithAppPassword(string $loginToken, string $server, string $loginName, string $appPassword): bool {
  160. try {
  161. $data = $this->mapper->getByLoginToken($loginToken);
  162. } catch (DoesNotExistException $e) {
  163. return false;
  164. }
  165. $data->setLoginName($loginName);
  166. $data->setServer($server);
  167. // Properly encrypt
  168. $data->setAppPassword($this->encryptPassword($appPassword, $data->getPublicKey()));
  169. $this->mapper->update($data);
  170. return true;
  171. }
  172. public function createTokens(string $userAgent): LoginFlowV2Tokens {
  173. $flow = new LoginFlowV2();
  174. $pollToken = $this->random->generate(128, ISecureRandom::CHAR_DIGITS.ISecureRandom::CHAR_LOWER.ISecureRandom::CHAR_UPPER);
  175. $loginToken = $this->random->generate(128, ISecureRandom::CHAR_DIGITS.ISecureRandom::CHAR_LOWER.ISecureRandom::CHAR_UPPER);
  176. $flow->setPollToken($this->hashToken($pollToken));
  177. $flow->setLoginToken($loginToken);
  178. $flow->setStarted(0);
  179. $flow->setTimestamp($this->time->getTime());
  180. $flow->setClientName($userAgent);
  181. [$publicKey, $privateKey] = $this->getKeyPair();
  182. $privateKey = $this->crypto->encrypt($privateKey, $pollToken);
  183. $flow->setPublicKey($publicKey);
  184. $flow->setPrivateKey($privateKey);
  185. $this->mapper->insert($flow);
  186. return new LoginFlowV2Tokens($loginToken, $pollToken);
  187. }
  188. private function hashToken(string $token): string {
  189. $secret = $this->config->getSystemValue('secret');
  190. return hash('sha512', $token . $secret);
  191. }
  192. private function getKeyPair(): array {
  193. $config = array_merge([
  194. 'digest_alg' => 'sha512',
  195. 'private_key_bits' => 2048,
  196. ], $this->config->getSystemValue('openssl', []));
  197. // Generate new key
  198. $res = openssl_pkey_new($config);
  199. if ($res === false) {
  200. $this->logOpensslError();
  201. throw new \RuntimeException('Could not initialize keys');
  202. }
  203. if (openssl_pkey_export($res, $privateKey, null, $config) === false) {
  204. $this->logOpensslError();
  205. throw new \RuntimeException('OpenSSL reported a problem');
  206. }
  207. // Extract the public key from $res to $pubKey
  208. $publicKey = openssl_pkey_get_details($res);
  209. $publicKey = $publicKey['key'];
  210. return [$publicKey, $privateKey];
  211. }
  212. private function logOpensslError(): void {
  213. $errors = [];
  214. while ($error = openssl_error_string()) {
  215. $errors[] = $error;
  216. }
  217. $this->logger->critical('Something is wrong with your openssl setup: ' . implode(', ', $errors));
  218. }
  219. private function encryptPassword(string $password, string $publicKey): string {
  220. openssl_public_encrypt($password, $encryptedPassword, $publicKey, OPENSSL_PKCS1_OAEP_PADDING);
  221. $encryptedPassword = base64_encode($encryptedPassword);
  222. return $encryptedPassword;
  223. }
  224. private function decryptPassword(string $encryptedPassword, string $privateKey): string {
  225. $encryptedPassword = base64_decode($encryptedPassword);
  226. openssl_private_decrypt($encryptedPassword, $password, $privateKey, OPENSSL_PKCS1_OAEP_PADDING);
  227. return $password;
  228. }
  229. }