ExceptionSerializer.php 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2018 Robin Appelman <robin@icewind.nl>
  4. *
  5. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  6. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  7. * @author Joas Schilling <coding@schilljs.com>
  8. * @author Morris Jobke <hey@morrisjobke.de>
  9. * @author Robin Appelman <robin@icewind.nl>
  10. * @author Roeland Jago Douma <roeland@famdouma.nl>
  11. * @author Vincent Petry <vincent@nextcloud.com>
  12. *
  13. * @license GNU AGPL version 3 or any later version
  14. *
  15. * This program is free software: you can redistribute it and/or modify
  16. * it under the terms of the GNU Affero General Public License as
  17. * published by the Free Software Foundation, either version 3 of the
  18. * License, or (at your option) any later version.
  19. *
  20. * This program is distributed in the hope that it will be useful,
  21. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  22. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  23. * GNU Affero General Public License for more details.
  24. *
  25. * You should have received a copy of the GNU Affero General Public License
  26. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  27. *
  28. */
  29. namespace OC\Log;
  30. use OC\Core\Controller\SetupController;
  31. use OC\Security\IdentityProof\Key;
  32. use OC\Setup;
  33. use OC\SystemConfig;
  34. use OCA\Encryption\Controller\RecoveryController;
  35. use OCA\Encryption\Controller\SettingsController;
  36. use OCA\Encryption\Crypto\Crypt;
  37. use OCA\Encryption\Crypto\Encryption;
  38. use OCA\Encryption\Hooks\UserHooks;
  39. use OCA\Encryption\KeyManager;
  40. use OCA\Encryption\Session;
  41. use OCP\HintException;
  42. class ExceptionSerializer {
  43. public const SENSITIVE_VALUE_PLACEHOLDER = '*** sensitive parameters replaced ***';
  44. public const methodsWithSensitiveParameters = [
  45. // Session/User
  46. 'completeLogin',
  47. 'login',
  48. 'checkPassword',
  49. 'checkPasswordNoLogging',
  50. 'loginWithPassword',
  51. 'updatePrivateKeyPassword',
  52. 'validateUserPass',
  53. 'loginWithToken',
  54. '{closure}',
  55. 'createSessionToken',
  56. // Provisioning
  57. 'addUser',
  58. // TokenProvider
  59. 'getToken',
  60. 'isTokenPassword',
  61. 'getPassword',
  62. 'decryptPassword',
  63. 'logClientIn',
  64. 'generateToken',
  65. 'validateToken',
  66. // TwoFactorAuth
  67. 'solveChallenge',
  68. 'verifyChallenge',
  69. // ICrypto
  70. 'calculateHMAC',
  71. 'encrypt',
  72. 'decrypt',
  73. // LoginController
  74. 'tryLogin',
  75. 'confirmPassword',
  76. // LDAP
  77. 'bind',
  78. 'areCredentialsValid',
  79. 'invokeLDAPMethod',
  80. // Encryption
  81. 'storeKeyPair',
  82. 'setupUser',
  83. 'checkSignature',
  84. // files_external: OCA\Files_External\MountConfig
  85. 'getBackendStatus',
  86. // files_external: UserStoragesController
  87. 'update',
  88. // Preview providers, don't log big data strings
  89. 'imagecreatefromstring',
  90. // text: PublicSessionController, SessionController and ApiService
  91. 'create',
  92. 'close',
  93. 'push',
  94. 'sync',
  95. 'updateSession',
  96. 'mention',
  97. 'loginSessionUser',
  98. ];
  99. public function __construct(
  100. private SystemConfig $systemConfig,
  101. ) {
  102. }
  103. protected array $methodsWithSensitiveParametersByClass = [
  104. SetupController::class => [
  105. 'run',
  106. 'display',
  107. 'loadAutoConfig',
  108. ],
  109. Setup::class => [
  110. 'install'
  111. ],
  112. Key::class => [
  113. '__construct'
  114. ],
  115. \Redis::class => [
  116. 'auth'
  117. ],
  118. \RedisCluster::class => [
  119. '__construct'
  120. ],
  121. Crypt::class => [
  122. 'symmetricEncryptFileContent',
  123. 'encrypt',
  124. 'generatePasswordHash',
  125. 'encryptPrivateKey',
  126. 'decryptPrivateKey',
  127. 'isValidPrivateKey',
  128. 'symmetricDecryptFileContent',
  129. 'checkSignature',
  130. 'createSignature',
  131. 'decrypt',
  132. 'multiKeyDecrypt',
  133. 'multiKeyEncrypt',
  134. ],
  135. RecoveryController::class => [
  136. 'adminRecovery',
  137. 'changeRecoveryPassword'
  138. ],
  139. SettingsController::class => [
  140. 'updatePrivateKeyPassword',
  141. ],
  142. Encryption::class => [
  143. 'encrypt',
  144. 'decrypt',
  145. ],
  146. KeyManager::class => [
  147. 'checkRecoveryPassword',
  148. 'storeKeyPair',
  149. 'setRecoveryKey',
  150. 'setPrivateKey',
  151. 'setFileKey',
  152. 'setAllFileKeys',
  153. ],
  154. Session::class => [
  155. 'setPrivateKey',
  156. 'prepareDecryptAll',
  157. ],
  158. \OCA\Encryption\Users\Setup::class => [
  159. 'setupUser',
  160. ],
  161. UserHooks::class => [
  162. 'login',
  163. 'postCreateUser',
  164. 'postDeleteUser',
  165. 'prePasswordReset',
  166. 'postPasswordReset',
  167. 'preSetPassphrase',
  168. 'setPassphrase',
  169. ],
  170. ];
  171. private function editTrace(array &$sensitiveValues, array $traceLine): array {
  172. if (isset($traceLine['args'])) {
  173. $sensitiveValues = array_merge($sensitiveValues, $traceLine['args']);
  174. }
  175. $traceLine['args'] = [self::SENSITIVE_VALUE_PLACEHOLDER];
  176. return $traceLine;
  177. }
  178. private function filterTrace(array $trace) {
  179. $sensitiveValues = [];
  180. $trace = array_map(function (array $traceLine) use (&$sensitiveValues) {
  181. $className = $traceLine['class'] ?? '';
  182. if ($className && isset($this->methodsWithSensitiveParametersByClass[$className])
  183. && in_array($traceLine['function'], $this->methodsWithSensitiveParametersByClass[$className], true)) {
  184. return $this->editTrace($sensitiveValues, $traceLine);
  185. }
  186. foreach (self::methodsWithSensitiveParameters as $sensitiveMethod) {
  187. if (str_contains($traceLine['function'], $sensitiveMethod)) {
  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 $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[] = $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. }