CryptoSessionData.php 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  6. * SPDX-License-Identifier: AGPL-3.0-only
  7. */
  8. namespace OC\Session;
  9. use OCP\ISession;
  10. use OCP\Security\ICrypto;
  11. use OCP\Session\Exceptions\SessionNotAvailableException;
  12. use function json_decode;
  13. use function OCP\Log\logger;
  14. /**
  15. * Class CryptoSessionData
  16. *
  17. * @package OC\Session
  18. * @template-implements \ArrayAccess<string,mixed>
  19. */
  20. class CryptoSessionData implements \ArrayAccess, ISession {
  21. /** @var ISession */
  22. protected $session;
  23. /** @var \OCP\Security\ICrypto */
  24. protected $crypto;
  25. /** @var string */
  26. protected $passphrase;
  27. /** @var array */
  28. protected $sessionValues;
  29. /** @var bool */
  30. protected $isModified = false;
  31. public const encryptedSessionName = 'encrypted_session_data';
  32. /**
  33. * @param ISession $session
  34. * @param ICrypto $crypto
  35. * @param string $passphrase
  36. */
  37. public function __construct(ISession $session,
  38. ICrypto $crypto,
  39. string $passphrase) {
  40. $this->crypto = $crypto;
  41. $this->session = $session;
  42. $this->passphrase = $passphrase;
  43. $this->initializeSession();
  44. }
  45. /**
  46. * Close session if class gets destructed
  47. */
  48. public function __destruct() {
  49. try {
  50. $this->close();
  51. } catch (SessionNotAvailableException $e) {
  52. // This exception can occur if session is already closed
  53. // So it is safe to ignore it and let the garbage collector to proceed
  54. }
  55. }
  56. protected function initializeSession() {
  57. $encryptedSessionData = $this->session->get(self::encryptedSessionName) ?: '';
  58. if ($encryptedSessionData === '') {
  59. // Nothing to decrypt
  60. $this->sessionValues = [];
  61. } else {
  62. try {
  63. $this->sessionValues = json_decode(
  64. $this->crypto->decrypt($encryptedSessionData, $this->passphrase),
  65. true,
  66. 512,
  67. JSON_THROW_ON_ERROR,
  68. );
  69. } catch (\Exception $e) {
  70. logger('core')->critical('Could not decrypt or decode encrypted session data', [
  71. 'exception' => $e,
  72. ]);
  73. $this->sessionValues = [];
  74. $this->regenerateId(true, false);
  75. }
  76. }
  77. }
  78. /**
  79. * Set a value in the session
  80. *
  81. * @param string $key
  82. * @param mixed $value
  83. */
  84. public function set(string $key, $value) {
  85. if ($this->get($key) === $value) {
  86. // Do not write the session if the value hasn't changed to avoid reopening
  87. return;
  88. }
  89. $reopened = $this->reopen();
  90. $this->sessionValues[$key] = $value;
  91. $this->isModified = true;
  92. if ($reopened) {
  93. $this->close();
  94. }
  95. }
  96. /**
  97. * Get a value from the session
  98. *
  99. * @param string $key
  100. * @return string|null Either the value or null
  101. */
  102. public function get(string $key) {
  103. if (isset($this->sessionValues[$key])) {
  104. return $this->sessionValues[$key];
  105. }
  106. return null;
  107. }
  108. /**
  109. * Check if a named key exists in the session
  110. *
  111. * @param string $key
  112. * @return bool
  113. */
  114. public function exists(string $key): bool {
  115. return isset($this->sessionValues[$key]);
  116. }
  117. /**
  118. * Remove a $key/$value pair from the session
  119. *
  120. * @param string $key
  121. */
  122. public function remove(string $key) {
  123. $reopened = $this->reopen();
  124. $this->isModified = true;
  125. unset($this->sessionValues[$key]);
  126. if ($reopened) {
  127. $this->close();
  128. }
  129. }
  130. /**
  131. * Reset and recreate the session
  132. */
  133. public function clear() {
  134. $reopened = $this->reopen();
  135. $requesttoken = $this->get('requesttoken');
  136. $this->sessionValues = [];
  137. if ($requesttoken !== null) {
  138. $this->set('requesttoken', $requesttoken);
  139. }
  140. $this->isModified = true;
  141. $this->session->clear();
  142. if ($reopened) {
  143. $this->close();
  144. }
  145. }
  146. public function reopen(): bool {
  147. $reopened = $this->session->reopen();
  148. if ($reopened) {
  149. $this->initializeSession();
  150. }
  151. return $reopened;
  152. }
  153. /**
  154. * Wrapper around session_regenerate_id
  155. *
  156. * @param bool $deleteOldSession Whether to delete the old associated session file or not.
  157. * @param bool $updateToken Wheater to update the associated auth token
  158. * @return void
  159. */
  160. public function regenerateId(bool $deleteOldSession = true, bool $updateToken = false) {
  161. $this->session->regenerateId($deleteOldSession, $updateToken);
  162. }
  163. /**
  164. * Wrapper around session_id
  165. *
  166. * @return string
  167. * @throws SessionNotAvailableException
  168. * @since 9.1.0
  169. */
  170. public function getId(): string {
  171. return $this->session->getId();
  172. }
  173. /**
  174. * Close the session and release the lock, also writes all changed data in batch
  175. */
  176. public function close() {
  177. if ($this->isModified) {
  178. $encryptedValue = $this->crypto->encrypt(json_encode($this->sessionValues), $this->passphrase);
  179. $this->session->set(self::encryptedSessionName, $encryptedValue);
  180. $this->isModified = false;
  181. }
  182. $this->session->close();
  183. }
  184. /**
  185. * @param mixed $offset
  186. * @return bool
  187. */
  188. public function offsetExists($offset): bool {
  189. return $this->exists($offset);
  190. }
  191. /**
  192. * @param mixed $offset
  193. * @return mixed
  194. */
  195. #[\ReturnTypeWillChange]
  196. public function offsetGet($offset) {
  197. return $this->get($offset);
  198. }
  199. /**
  200. * @param mixed $offset
  201. * @param mixed $value
  202. */
  203. public function offsetSet($offset, $value): void {
  204. $this->set($offset, $value);
  205. }
  206. /**
  207. * @param mixed $offset
  208. */
  209. public function offsetUnset($offset): void {
  210. $this->remove($offset);
  211. }
  212. }