1
0

CryptoSessionData.php 5.9 KB

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