1
0

ExceptionSerializer.php 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2018 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-License-Identifier: AGPL-3.0-or-later
  5. */
  6. namespace OC\Log;
  7. use OC\Core\Controller\SetupController;
  8. use OC\Http\Client\Client;
  9. use OC\Security\IdentityProof\Key;
  10. use OC\Setup;
  11. use OC\SystemConfig;
  12. use OCA\Encryption\Controller\RecoveryController;
  13. use OCA\Encryption\Controller\SettingsController;
  14. use OCA\Encryption\Crypto\Crypt;
  15. use OCA\Encryption\Crypto\Encryption;
  16. use OCA\Encryption\KeyManager;
  17. use OCA\Encryption\Listeners\UserEventsListener;
  18. use OCA\Encryption\Services\PassphraseService;
  19. use OCA\Encryption\Session;
  20. use OCP\HintException;
  21. class ExceptionSerializer {
  22. public const SENSITIVE_VALUE_PLACEHOLDER = '*** sensitive parameters replaced ***';
  23. public const methodsWithSensitiveParameters = [
  24. // Session/User
  25. 'completeLogin',
  26. 'login',
  27. 'checkPassword',
  28. 'checkPasswordNoLogging',
  29. 'loginWithPassword',
  30. 'updatePrivateKeyPassword',
  31. 'validateUserPass',
  32. 'loginWithToken',
  33. '{closure}',
  34. '{closure:*',
  35. 'createSessionToken',
  36. // Provisioning
  37. 'addUser',
  38. // TokenProvider
  39. 'getToken',
  40. 'isTokenPassword',
  41. 'getPassword',
  42. 'decryptPassword',
  43. 'logClientIn',
  44. 'generateToken',
  45. 'validateToken',
  46. // TwoFactorAuth
  47. 'solveChallenge',
  48. 'verifyChallenge',
  49. // ICrypto
  50. 'calculateHMAC',
  51. 'encrypt',
  52. 'decrypt',
  53. // LoginController
  54. 'tryLogin',
  55. 'confirmPassword',
  56. // LDAP
  57. 'bind',
  58. 'areCredentialsValid',
  59. 'invokeLDAPMethod',
  60. // Encryption
  61. 'storeKeyPair',
  62. 'setupUser',
  63. 'checkSignature',
  64. // files_external: OCA\Files_External\MountConfig
  65. 'getBackendStatus',
  66. // files_external: UserStoragesController
  67. 'update',
  68. // Preview providers, don't log big data strings
  69. 'imagecreatefromstring',
  70. // text: PublicSessionController, SessionController and ApiService
  71. 'create',
  72. 'close',
  73. 'push',
  74. 'sync',
  75. 'updateSession',
  76. 'mention',
  77. 'loginSessionUser',
  78. ];
  79. public function __construct(
  80. private SystemConfig $systemConfig,
  81. ) {
  82. }
  83. protected array $methodsWithSensitiveParametersByClass = [
  84. SetupController::class => [
  85. 'run',
  86. 'display',
  87. 'loadAutoConfig',
  88. ],
  89. Setup::class => [
  90. 'install'
  91. ],
  92. Key::class => [
  93. '__construct'
  94. ],
  95. Client::class => [
  96. 'request',
  97. 'delete',
  98. 'deleteAsync',
  99. 'get',
  100. 'getAsync',
  101. 'head',
  102. 'headAsync',
  103. 'options',
  104. 'optionsAsync',
  105. 'patch',
  106. 'post',
  107. 'postAsync',
  108. 'put',
  109. 'putAsync',
  110. ],
  111. \Redis::class => [
  112. 'auth'
  113. ],
  114. \RedisCluster::class => [
  115. '__construct'
  116. ],
  117. Crypt::class => [
  118. 'symmetricEncryptFileContent',
  119. 'encrypt',
  120. 'generatePasswordHash',
  121. 'encryptPrivateKey',
  122. 'decryptPrivateKey',
  123. 'isValidPrivateKey',
  124. 'symmetricDecryptFileContent',
  125. 'checkSignature',
  126. 'createSignature',
  127. 'decrypt',
  128. 'multiKeyDecrypt',
  129. 'multiKeyEncrypt',
  130. ],
  131. RecoveryController::class => [
  132. 'adminRecovery',
  133. 'changeRecoveryPassword'
  134. ],
  135. SettingsController::class => [
  136. 'updatePrivateKeyPassword',
  137. ],
  138. Encryption::class => [
  139. 'encrypt',
  140. 'decrypt',
  141. ],
  142. KeyManager::class => [
  143. 'checkRecoveryPassword',
  144. 'storeKeyPair',
  145. 'setRecoveryKey',
  146. 'setPrivateKey',
  147. 'setFileKey',
  148. 'setAllFileKeys',
  149. ],
  150. Session::class => [
  151. 'setPrivateKey',
  152. 'prepareDecryptAll',
  153. ],
  154. \OCA\Encryption\Users\Setup::class => [
  155. 'setupUser',
  156. ],
  157. UserEventsListener::class => [
  158. 'handle',
  159. 'onUserCreated',
  160. 'onUserLogin',
  161. 'onBeforePasswordUpdated',
  162. 'onPasswordUpdated',
  163. 'onPasswordReset',
  164. ],
  165. PassphraseService::class => [
  166. 'setPassphraseForUser',
  167. ],
  168. ];
  169. private function editTrace(array &$sensitiveValues, array $traceLine): array {
  170. if (isset($traceLine['args'])) {
  171. $sensitiveValues = array_merge($sensitiveValues, $traceLine['args']);
  172. }
  173. $traceLine['args'] = [self::SENSITIVE_VALUE_PLACEHOLDER];
  174. return $traceLine;
  175. }
  176. private function filterTrace(array $trace) {
  177. $sensitiveValues = [];
  178. $trace = array_map(function (array $traceLine) use (&$sensitiveValues) {
  179. $className = $traceLine['class'] ?? '';
  180. if ($className && isset($this->methodsWithSensitiveParametersByClass[$className])
  181. && in_array($traceLine['function'], $this->methodsWithSensitiveParametersByClass[$className], true)) {
  182. return $this->editTrace($sensitiveValues, $traceLine);
  183. }
  184. foreach (self::methodsWithSensitiveParameters as $sensitiveMethod) {
  185. if (str_contains($traceLine['function'], $sensitiveMethod)
  186. || (str_ends_with($sensitiveMethod, '*')
  187. && str_starts_with($traceLine['function'], substr($sensitiveMethod, 0, -1)))) {
  188. return $this->editTrace($sensitiveValues, $traceLine);
  189. }
  190. }
  191. return $traceLine;
  192. }, $trace);
  193. return array_map(function (array $traceLine) use ($sensitiveValues) {
  194. if (isset($traceLine['args'])) {
  195. $traceLine['args'] = $this->removeValuesFromArgs($traceLine['args'], $sensitiveValues);
  196. }
  197. return $traceLine;
  198. }, $trace);
  199. }
  200. private function removeValuesFromArgs($args, $values): array {
  201. $workArgs = [];
  202. foreach ($args as $key => $arg) {
  203. if (in_array($arg, $values, true)) {
  204. $arg = self::SENSITIVE_VALUE_PLACEHOLDER;
  205. } elseif (is_array($arg)) {
  206. $arg = $this->removeValuesFromArgs($arg, $values);
  207. }
  208. $workArgs[$key] = $arg;
  209. }
  210. return $workArgs;
  211. }
  212. private function encodeTrace($trace) {
  213. $trace = array_map(function (array $line) {
  214. if (isset($line['args'])) {
  215. $line['args'] = array_map([$this, 'encodeArg'], $line['args']);
  216. }
  217. return $line;
  218. }, $trace);
  219. return $this->filterTrace($trace);
  220. }
  221. private function encodeArg($arg, $nestingLevel = 5) {
  222. if (is_object($arg)) {
  223. if ($nestingLevel === 0) {
  224. return [
  225. '__class__' => get_class($arg),
  226. '__properties__' => 'Encoding skipped as the maximum nesting level was reached',
  227. ];
  228. }
  229. $objectInfo = [ '__class__' => get_class($arg) ];
  230. $objectVars = get_object_vars($arg);
  231. return array_map(function ($arg) use ($nestingLevel) {
  232. return $this->encodeArg($arg, $nestingLevel - 1);
  233. }, array_merge($objectInfo, $objectVars));
  234. }
  235. if (is_array($arg)) {
  236. if ($nestingLevel === 0) {
  237. return ['Encoding skipped as the maximum nesting level was reached'];
  238. }
  239. // Only log the first 5 elements of an array unless we are on debug
  240. if ((int)$this->systemConfig->getValue('loglevel', 2) !== 0) {
  241. $elemCount = count($arg);
  242. if ($elemCount > 5) {
  243. $arg = array_slice($arg, 0, 5);
  244. $arg[] = 'And ' . ($elemCount - 5) . ' more entries, set log level to debug to see all entries';
  245. }
  246. }
  247. return array_map(function ($e) use ($nestingLevel) {
  248. return $this->encodeArg($e, $nestingLevel - 1);
  249. }, $arg);
  250. }
  251. return $arg;
  252. }
  253. public function serializeException(\Throwable $exception): array {
  254. $data = [
  255. 'Exception' => get_class($exception),
  256. 'Message' => $exception->getMessage(),
  257. 'Code' => $exception->getCode(),
  258. 'Trace' => $this->encodeTrace($exception->getTrace()),
  259. 'File' => $exception->getFile(),
  260. 'Line' => $exception->getLine(),
  261. ];
  262. if ($exception instanceof HintException) {
  263. $data['Hint'] = $exception->getHint();
  264. }
  265. if ($exception->getPrevious()) {
  266. $data['Previous'] = $this->serializeException($exception->getPrevious());
  267. }
  268. return $data;
  269. }
  270. public function enlistSensitiveMethods(string $class, array $methods): void {
  271. if (!isset($this->methodsWithSensitiveParametersByClass[$class])) {
  272. $this->methodsWithSensitiveParametersByClass[$class] = [];
  273. }
  274. $this->methodsWithSensitiveParametersByClass[$class] = array_merge($this->methodsWithSensitiveParametersByClass[$class], $methods);
  275. }
  276. }