CryptoSessionData.php 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright Copyright (c) 2016, ownCloud, Inc.
  5. *
  6. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  7. * @author Joas Schilling <coding@schilljs.com>
  8. * @author Lukas Reschke <lukas@statuscode.ch>
  9. * @author Morris Jobke <hey@morrisjobke.de>
  10. * @author Roeland Jago Douma <roeland@famdouma.nl>
  11. * @author Victor Dubiniuk <dubiniuk@owncloud.com>
  12. *
  13. * @license AGPL-3.0
  14. *
  15. * This code is free software: you can redistribute it and/or modify
  16. * it under the terms of the GNU Affero General Public License, version 3,
  17. * as published by the Free Software Foundation.
  18. *
  19. * This program is distributed in the hope that it will be useful,
  20. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  21. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  22. * GNU Affero General Public License for more details.
  23. *
  24. * You should have received a copy of the GNU Affero General Public License, version 3,
  25. * along with this program. If not, see <http://www.gnu.org/licenses/>
  26. *
  27. */
  28. namespace OC\Session;
  29. use OCP\ISession;
  30. use OCP\Security\ICrypto;
  31. use OCP\Session\Exceptions\SessionNotAvailableException;
  32. use function json_decode;
  33. use function OCP\Log\logger;
  34. /**
  35. * Class CryptoSessionData
  36. *
  37. * @package OC\Session
  38. * @template-implements \ArrayAccess<string,mixed>
  39. */
  40. class CryptoSessionData implements \ArrayAccess, ISession {
  41. /** @var ISession */
  42. protected $session;
  43. /** @var \OCP\Security\ICrypto */
  44. protected $crypto;
  45. /** @var string */
  46. protected $passphrase;
  47. /** @var array */
  48. protected $sessionValues;
  49. /** @var bool */
  50. protected $isModified = false;
  51. public const encryptedSessionName = 'encrypted_session_data';
  52. /**
  53. * @param ISession $session
  54. * @param ICrypto $crypto
  55. * @param string $passphrase
  56. */
  57. public function __construct(ISession $session,
  58. ICrypto $crypto,
  59. string $passphrase) {
  60. $this->crypto = $crypto;
  61. $this->session = $session;
  62. $this->passphrase = $passphrase;
  63. $this->initializeSession();
  64. }
  65. /**
  66. * Close session if class gets destructed
  67. */
  68. public function __destruct() {
  69. try {
  70. $this->close();
  71. } catch (SessionNotAvailableException $e) {
  72. // This exception can occur if session is already closed
  73. // So it is safe to ignore it and let the garbage collector to proceed
  74. }
  75. }
  76. protected function initializeSession() {
  77. $encryptedSessionData = $this->session->get(self::encryptedSessionName) ?: '';
  78. if ($encryptedSessionData === '') {
  79. // Nothing to decrypt
  80. $this->sessionValues = [];
  81. } else {
  82. try {
  83. $this->sessionValues = json_decode(
  84. $this->crypto->decrypt($encryptedSessionData, $this->passphrase),
  85. true,
  86. 512,
  87. JSON_THROW_ON_ERROR,
  88. );
  89. } catch (\Exception $e) {
  90. logger('core')->critical('Could not decrypt or decode encrypted session data', [
  91. 'exception' => $e,
  92. ]);
  93. $this->sessionValues = [];
  94. $this->regenerateId(true, false);
  95. }
  96. }
  97. }
  98. /**
  99. * Set a value in the session
  100. *
  101. * @param string $key
  102. * @param mixed $value
  103. */
  104. public function set(string $key, $value) {
  105. if ($this->get($key) === $value) {
  106. // Do not write the session if the value hasn't changed to avoid reopening
  107. return;
  108. }
  109. $reopened = $this->reopen();
  110. $this->sessionValues[$key] = $value;
  111. $this->isModified = true;
  112. if ($reopened) {
  113. $this->close();
  114. }
  115. }
  116. /**
  117. * Get a value from the session
  118. *
  119. * @param string $key
  120. * @return string|null Either the value or null
  121. */
  122. public function get(string $key) {
  123. if (isset($this->sessionValues[$key])) {
  124. return $this->sessionValues[$key];
  125. }
  126. return null;
  127. }
  128. /**
  129. * Check if a named key exists in the session
  130. *
  131. * @param string $key
  132. * @return bool
  133. */
  134. public function exists(string $key): bool {
  135. return isset($this->sessionValues[$key]);
  136. }
  137. /**
  138. * Remove a $key/$value pair from the session
  139. *
  140. * @param string $key
  141. */
  142. public function remove(string $key) {
  143. $reopened = $this->reopen();
  144. $this->isModified = true;
  145. unset($this->sessionValues[$key]);
  146. if ($reopened) {
  147. $this->close();
  148. }
  149. }
  150. /**
  151. * Reset and recreate the session
  152. */
  153. public function clear() {
  154. $reopened = $this->reopen();
  155. $requesttoken = $this->get('requesttoken');
  156. $this->sessionValues = [];
  157. if ($requesttoken !== null) {
  158. $this->set('requesttoken', $requesttoken);
  159. }
  160. $this->isModified = true;
  161. $this->session->clear();
  162. if ($reopened) {
  163. $this->close();
  164. }
  165. }
  166. public function reopen(): bool {
  167. $reopened = $this->session->reopen();
  168. if ($reopened) {
  169. $this->initializeSession();
  170. }
  171. return $reopened;
  172. }
  173. /**
  174. * Wrapper around session_regenerate_id
  175. *
  176. * @param bool $deleteOldSession Whether to delete the old associated session file or not.
  177. * @param bool $updateToken Wheater to update the associated auth token
  178. * @return void
  179. */
  180. public function regenerateId(bool $deleteOldSession = true, bool $updateToken = false) {
  181. $this->session->regenerateId($deleteOldSession, $updateToken);
  182. }
  183. /**
  184. * Wrapper around session_id
  185. *
  186. * @return string
  187. * @throws SessionNotAvailableException
  188. * @since 9.1.0
  189. */
  190. public function getId(): string {
  191. return $this->session->getId();
  192. }
  193. /**
  194. * Close the session and release the lock, also writes all changed data in batch
  195. */
  196. public function close() {
  197. if ($this->isModified) {
  198. $encryptedValue = $this->crypto->encrypt(json_encode($this->sessionValues), $this->passphrase);
  199. $this->session->set(self::encryptedSessionName, $encryptedValue);
  200. $this->isModified = false;
  201. }
  202. $this->session->close();
  203. }
  204. /**
  205. * @param mixed $offset
  206. * @return bool
  207. */
  208. public function offsetExists($offset): bool {
  209. return $this->exists($offset);
  210. }
  211. /**
  212. * @param mixed $offset
  213. * @return mixed
  214. */
  215. #[\ReturnTypeWillChange]
  216. public function offsetGet($offset) {
  217. return $this->get($offset);
  218. }
  219. /**
  220. * @param mixed $offset
  221. * @param mixed $value
  222. */
  223. public function offsetSet($offset, $value): void {
  224. $this->set($offset, $value);
  225. }
  226. /**
  227. * @param mixed $offset
  228. */
  229. public function offsetUnset($offset): void {
  230. $this->remove($offset);
  231. }
  232. }