LoginFlowV2Service.php 8.1 KB

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