ExceptionSerializer.php 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  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. ];
  91. /** @var SystemConfig */
  92. private $systemConfig;
  93. public function __construct(SystemConfig $systemConfig) {
  94. $this->systemConfig = $systemConfig;
  95. }
  96. protected array $methodsWithSensitiveParametersByClass = [
  97. SetupController::class => [
  98. 'run',
  99. 'display',
  100. 'loadAutoConfig',
  101. ],
  102. Setup::class => [
  103. 'install'
  104. ],
  105. Key::class => [
  106. '__construct'
  107. ],
  108. \Redis::class => [
  109. 'auth'
  110. ],
  111. \RedisCluster::class => [
  112. '__construct'
  113. ],
  114. Crypt::class => [
  115. 'symmetricEncryptFileContent',
  116. 'encrypt',
  117. 'generatePasswordHash',
  118. 'encryptPrivateKey',
  119. 'decryptPrivateKey',
  120. 'isValidPrivateKey',
  121. 'symmetricDecryptFileContent',
  122. 'checkSignature',
  123. 'createSignature',
  124. 'decrypt',
  125. 'multiKeyDecrypt',
  126. 'multiKeyEncrypt',
  127. ],
  128. RecoveryController::class => [
  129. 'adminRecovery',
  130. 'changeRecoveryPassword'
  131. ],
  132. SettingsController::class => [
  133. 'updatePrivateKeyPassword',
  134. ],
  135. Encryption::class => [
  136. 'encrypt',
  137. 'decrypt',
  138. ],
  139. KeyManager::class => [
  140. 'checkRecoveryPassword',
  141. 'storeKeyPair',
  142. 'setRecoveryKey',
  143. 'setPrivateKey',
  144. 'setFileKey',
  145. 'setAllFileKeys',
  146. ],
  147. Session::class => [
  148. 'setPrivateKey',
  149. 'prepareDecryptAll',
  150. ],
  151. \OCA\Encryption\Users\Setup::class => [
  152. 'setupUser',
  153. ],
  154. UserHooks::class => [
  155. 'login',
  156. 'postCreateUser',
  157. 'postDeleteUser',
  158. 'prePasswordReset',
  159. 'postPasswordReset',
  160. 'preSetPassphrase',
  161. 'setPassphrase',
  162. ],
  163. ];
  164. private function editTrace(array &$sensitiveValues, array $traceLine): array {
  165. if (isset($traceLine['args'])) {
  166. $sensitiveValues = array_merge($sensitiveValues, $traceLine['args']);
  167. }
  168. $traceLine['args'] = [self::SENSITIVE_VALUE_PLACEHOLDER];
  169. return $traceLine;
  170. }
  171. private function filterTrace(array $trace) {
  172. $sensitiveValues = [];
  173. $trace = array_map(function (array $traceLine) use (&$sensitiveValues) {
  174. $className = $traceLine['class'] ?? '';
  175. if ($className && isset($this->methodsWithSensitiveParametersByClass[$className])
  176. && in_array($traceLine['function'], $this->methodsWithSensitiveParametersByClass[$className], true)) {
  177. return $this->editTrace($sensitiveValues, $traceLine);
  178. }
  179. foreach (self::methodsWithSensitiveParameters as $sensitiveMethod) {
  180. if (strpos($traceLine['function'], $sensitiveMethod) !== false) {
  181. return $this->editTrace($sensitiveValues, $traceLine);
  182. }
  183. }
  184. return $traceLine;
  185. }, $trace);
  186. return array_map(function (array $traceLine) use ($sensitiveValues) {
  187. if (isset($traceLine['args'])) {
  188. $traceLine['args'] = $this->removeValuesFromArgs($traceLine['args'], $sensitiveValues);
  189. }
  190. return $traceLine;
  191. }, $trace);
  192. }
  193. private function removeValuesFromArgs($args, $values) {
  194. $workArgs = [];
  195. foreach ($args as $arg) {
  196. if (in_array($arg, $values, true)) {
  197. $arg = self::SENSITIVE_VALUE_PLACEHOLDER;
  198. } elseif (is_array($arg)) {
  199. $arg = $this->removeValuesFromArgs($arg, $values);
  200. }
  201. $workArgs[] = $arg;
  202. }
  203. return $workArgs;
  204. }
  205. private function encodeTrace($trace) {
  206. $filteredTrace = $this->filterTrace($trace);
  207. return array_map(function (array $line) {
  208. if (isset($line['args'])) {
  209. $line['args'] = array_map([$this, 'encodeArg'], $line['args']);
  210. }
  211. return $line;
  212. }, $filteredTrace);
  213. }
  214. private function encodeArg($arg, $nestingLevel = 5) {
  215. if (is_object($arg)) {
  216. if ($nestingLevel === 0) {
  217. return [
  218. '__class__' => get_class($arg),
  219. '__properties__' => 'Encoding skipped as the maximum nesting level was reached',
  220. ];
  221. }
  222. $objectInfo = [ '__class__' => get_class($arg) ];
  223. $objectVars = get_object_vars($arg);
  224. return array_map(function ($arg) use ($nestingLevel) {
  225. return $this->encodeArg($arg, $nestingLevel - 1);
  226. }, array_merge($objectInfo, $objectVars));
  227. }
  228. if (is_array($arg)) {
  229. if ($nestingLevel === 0) {
  230. return ['Encoding skipped as the maximum nesting level was reached'];
  231. }
  232. // Only log the first 5 elements of an array unless we are on debug
  233. if ((int)$this->systemConfig->getValue('loglevel', 2) !== 0) {
  234. $elemCount = count($arg);
  235. if ($elemCount > 5) {
  236. $arg = array_slice($arg, 0, 5);
  237. $arg[] = 'And ' . ($elemCount - 5) . ' more entries, set log level to debug to see all entries';
  238. }
  239. }
  240. return array_map(function ($e) use ($nestingLevel) {
  241. return $this->encodeArg($e, $nestingLevel - 1);
  242. }, $arg);
  243. }
  244. return $arg;
  245. }
  246. public function serializeException(\Throwable $exception) {
  247. $data = [
  248. 'Exception' => get_class($exception),
  249. 'Message' => $exception->getMessage(),
  250. 'Code' => $exception->getCode(),
  251. 'Trace' => $this->encodeTrace($exception->getTrace()),
  252. 'File' => $exception->getFile(),
  253. 'Line' => $exception->getLine(),
  254. ];
  255. if ($exception instanceof HintException) {
  256. $data['Hint'] = $exception->getHint();
  257. }
  258. if ($exception->getPrevious()) {
  259. $data['Previous'] = $this->serializeException($exception->getPrevious());
  260. }
  261. return $data;
  262. }
  263. public function enlistSensitiveMethods(string $class, array $methods): void {
  264. if (!isset($this->methodsWithSensitiveParametersByClass[$class])) {
  265. $this->methodsWithSensitiveParametersByClass[$class] = [];
  266. }
  267. $this->methodsWithSensitiveParametersByClass[$class] = array_merge($this->methodsWithSensitiveParametersByClass[$class], $methods);
  268. }
  269. }