1
0

ExceptionSerializer.php 8.0 KB

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