CryptoSessionData.php 5.8 KB

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