1
0

Log.php 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Bart Visscher <bartv@thisnet.nl>
  6. * @author Bernhard Posselt <dev@bernhard-posselt.com>
  7. * @author Joas Schilling <coding@schilljs.com>
  8. * @author Lukas Reschke <lukas@statuscode.ch>
  9. * @author Morris Jobke <hey@morrisjobke.de>
  10. * @author Olivier Paroz <github@oparoz.com>
  11. * @author Robin Appelman <robin@icewind.nl>
  12. * @author Roeland Jago Douma <roeland@famdouma.nl>
  13. * @author Thomas Müller <thomas.mueller@tmit.eu>
  14. * @author Victor Dubiniuk <dubiniuk@owncloud.com>
  15. *
  16. * @license AGPL-3.0
  17. *
  18. * This code is free software: you can redistribute it and/or modify
  19. * it under the terms of the GNU Affero General Public License, version 3,
  20. * as published by the Free Software Foundation.
  21. *
  22. * This program is distributed in the hope that it will be useful,
  23. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  24. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  25. * GNU Affero General Public License for more details.
  26. *
  27. * You should have received a copy of the GNU Affero General Public License, version 3,
  28. * along with this program. If not, see <http://www.gnu.org/licenses/>
  29. *
  30. */
  31. namespace OC;
  32. use InterfaSys\LogNormalizer\Normalizer;
  33. use \OCP\ILogger;
  34. use OCP\Util;
  35. /**
  36. * logging utilities
  37. *
  38. * This is a stand in, this should be replaced by a Psr\Log\LoggerInterface
  39. * compatible logger. See https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-3-logger-interface.md
  40. * for the full interface specification.
  41. *
  42. * MonoLog is an example implementing this interface.
  43. */
  44. class Log implements ILogger {
  45. /** @var string */
  46. private $logger;
  47. /** @var SystemConfig */
  48. private $config;
  49. /** @var boolean|null cache the result of the log condition check for the request */
  50. private $logConditionSatisfied = null;
  51. /** @var Normalizer */
  52. private $normalizer;
  53. protected $methodsWithSensitiveParameters = [
  54. // Session/User
  55. 'completeLogin',
  56. 'login',
  57. 'checkPassword',
  58. 'checkPasswordNoLogging',
  59. 'loginWithPassword',
  60. 'updatePrivateKeyPassword',
  61. 'validateUserPass',
  62. 'loginWithToken',
  63. '\{closure\}',
  64. 'createSessionToken',
  65. // TokenProvider
  66. 'getToken',
  67. 'isTokenPassword',
  68. 'getPassword',
  69. 'decryptPassword',
  70. 'logClientIn',
  71. 'generateToken',
  72. 'validateToken',
  73. // TwoFactorAuth
  74. 'solveChallenge',
  75. 'verifyChallenge',
  76. // ICrypto
  77. 'calculateHMAC',
  78. 'encrypt',
  79. 'decrypt',
  80. // LoginController
  81. 'tryLogin',
  82. 'confirmPassword',
  83. // LDAP
  84. 'bind',
  85. 'areCredentialsValid',
  86. 'invokeLDAPMethod',
  87. // Encryption
  88. 'storeKeyPair',
  89. 'setupUser',
  90. ];
  91. /**
  92. * @param string $logger The logger that should be used
  93. * @param SystemConfig $config the system config object
  94. * @param null $normalizer
  95. */
  96. public function __construct($logger = null, SystemConfig $config = null, $normalizer = null) {
  97. // FIXME: Add this for backwards compatibility, should be fixed at some point probably
  98. if($config === null) {
  99. $config = \OC::$server->getSystemConfig();
  100. }
  101. $this->config = $config;
  102. // FIXME: Add this for backwards compatibility, should be fixed at some point probably
  103. if($logger === null) {
  104. $logType = $this->config->getValue('log_type', 'file');
  105. $this->logger = static::getLogClass($logType);
  106. call_user_func(array($this->logger, 'init'));
  107. } else {
  108. $this->logger = $logger;
  109. }
  110. if ($normalizer === null) {
  111. $this->normalizer = new Normalizer();
  112. } else {
  113. $this->normalizer = $normalizer;
  114. }
  115. }
  116. /**
  117. * System is unusable.
  118. *
  119. * @param string $message
  120. * @param array $context
  121. * @return void
  122. */
  123. public function emergency($message, array $context = array()) {
  124. $this->log(Util::FATAL, $message, $context);
  125. }
  126. /**
  127. * Action must be taken immediately.
  128. *
  129. * Example: Entire website down, database unavailable, etc. This should
  130. * trigger the SMS alerts and wake you up.
  131. *
  132. * @param string $message
  133. * @param array $context
  134. * @return void
  135. */
  136. public function alert($message, array $context = array()) {
  137. $this->log(Util::ERROR, $message, $context);
  138. }
  139. /**
  140. * Critical conditions.
  141. *
  142. * Example: Application component unavailable, unexpected exception.
  143. *
  144. * @param string $message
  145. * @param array $context
  146. * @return void
  147. */
  148. public function critical($message, array $context = array()) {
  149. $this->log(Util::ERROR, $message, $context);
  150. }
  151. /**
  152. * Runtime errors that do not require immediate action but should typically
  153. * be logged and monitored.
  154. *
  155. * @param string $message
  156. * @param array $context
  157. * @return void
  158. */
  159. public function error($message, array $context = array()) {
  160. $this->log(Util::ERROR, $message, $context);
  161. }
  162. /**
  163. * Exceptional occurrences that are not errors.
  164. *
  165. * Example: Use of deprecated APIs, poor use of an API, undesirable things
  166. * that are not necessarily wrong.
  167. *
  168. * @param string $message
  169. * @param array $context
  170. * @return void
  171. */
  172. public function warning($message, array $context = array()) {
  173. $this->log(Util::WARN, $message, $context);
  174. }
  175. /**
  176. * Normal but significant events.
  177. *
  178. * @param string $message
  179. * @param array $context
  180. * @return void
  181. */
  182. public function notice($message, array $context = array()) {
  183. $this->log(Util::INFO, $message, $context);
  184. }
  185. /**
  186. * Interesting events.
  187. *
  188. * Example: User logs in, SQL logs.
  189. *
  190. * @param string $message
  191. * @param array $context
  192. * @return void
  193. */
  194. public function info($message, array $context = array()) {
  195. $this->log(Util::INFO, $message, $context);
  196. }
  197. /**
  198. * Detailed debug information.
  199. *
  200. * @param string $message
  201. * @param array $context
  202. * @return void
  203. */
  204. public function debug($message, array $context = array()) {
  205. $this->log(Util::DEBUG, $message, $context);
  206. }
  207. /**
  208. * Logs with an arbitrary level.
  209. *
  210. * @param mixed $level
  211. * @param string $message
  212. * @param array $context
  213. * @return void
  214. */
  215. public function log($level, $message, array $context = array()) {
  216. $minLevel = min($this->config->getValue('loglevel', Util::WARN), Util::FATAL);
  217. $logCondition = $this->config->getValue('log.condition', []);
  218. array_walk($context, [$this->normalizer, 'format']);
  219. if (isset($context['app'])) {
  220. $app = $context['app'];
  221. /**
  222. * check log condition based on the context of each log message
  223. * once this is met -> change the required log level to debug
  224. */
  225. if(!empty($logCondition)
  226. && isset($logCondition['apps'])
  227. && in_array($app, $logCondition['apps'], true)) {
  228. $minLevel = Util::DEBUG;
  229. }
  230. } else {
  231. $app = 'no app in context';
  232. }
  233. // interpolate $message as defined in PSR-3
  234. $replace = array();
  235. foreach ($context as $key => $val) {
  236. $replace['{' . $key . '}'] = $val;
  237. }
  238. // interpolate replacement values into the message and return
  239. $message = strtr($message, $replace);
  240. /**
  241. * check for a special log condition - this enables an increased log on
  242. * a per request/user base
  243. */
  244. if($this->logConditionSatisfied === null) {
  245. // default to false to just process this once per request
  246. $this->logConditionSatisfied = false;
  247. if(!empty($logCondition)) {
  248. // check for secret token in the request
  249. if(isset($logCondition['shared_secret'])) {
  250. $request = \OC::$server->getRequest();
  251. if ($request->getMethod() === 'PUT' &&
  252. strpos($request->getHeader('Content-Type'), 'application/x-www-form-urlencoded') === false &&
  253. strpos($request->getHeader('Content-Type'), 'application/json') === false) {
  254. $logSecretRequest = '';
  255. } else {
  256. $logSecretRequest = $request->getParam('log_secret', '');
  257. }
  258. // if token is found in the request change set the log condition to satisfied
  259. if ($request && hash_equals($logCondition['shared_secret'], $logSecretRequest)) {
  260. $this->logConditionSatisfied = true;
  261. }
  262. }
  263. // check for user
  264. if(isset($logCondition['users'])) {
  265. $user = \OC::$server->getUserSession()->getUser();
  266. // if the user matches set the log condition to satisfied
  267. if($user !== null && in_array($user->getUID(), $logCondition['users'], true)) {
  268. $this->logConditionSatisfied = true;
  269. }
  270. }
  271. }
  272. }
  273. // if log condition is satisfied change the required log level to DEBUG
  274. if($this->logConditionSatisfied) {
  275. $minLevel = Util::DEBUG;
  276. }
  277. if ($level >= $minLevel) {
  278. $logger = $this->logger;
  279. call_user_func(array($logger, 'write'), $app, $message, $level);
  280. }
  281. }
  282. /**
  283. * Logs an exception very detailed
  284. *
  285. * @param \Exception|\Throwable $exception
  286. * @param array $context
  287. * @return void
  288. * @since 8.2.0
  289. */
  290. public function logException($exception, array $context = array()) {
  291. $level = Util::ERROR;
  292. if (isset($context['level'])) {
  293. $level = $context['level'];
  294. unset($context['level']);
  295. }
  296. $data = array(
  297. 'Exception' => get_class($exception),
  298. 'Message' => $exception->getMessage(),
  299. 'Code' => $exception->getCode(),
  300. 'Trace' => $exception->getTraceAsString(),
  301. 'File' => $exception->getFile(),
  302. 'Line' => $exception->getLine(),
  303. );
  304. $data['Trace'] = preg_replace('!(' . implode('|', $this->methodsWithSensitiveParameters) . ')\(.*\)!', '$1(*** sensitive parameters replaced ***)', $data['Trace']);
  305. $msg = isset($context['message']) ? $context['message'] : 'Exception';
  306. $msg .= ': ' . json_encode($data);
  307. $this->log($level, $msg, $context);
  308. }
  309. /**
  310. * @param string $logType
  311. * @return string
  312. * @internal
  313. */
  314. public static function getLogClass($logType) {
  315. switch (strtolower($logType)) {
  316. case 'errorlog':
  317. return \OC\Log\Errorlog::class;
  318. case 'syslog':
  319. return \OC\Log\Syslog::class;
  320. case 'file':
  321. return \OC\Log\File::class;
  322. // Backwards compatibility for old and fallback for unknown log types
  323. case 'owncloud':
  324. case 'nextcloud':
  325. default:
  326. return \OC\Log\File::class;
  327. }
  328. }
  329. }