CheckSetupController.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  6. * @author Bjoern Schiessle <bjoern@schiessle.org>
  7. * @author Derek <derek.kelly27@gmail.com>
  8. * @author Joas Schilling <coding@schilljs.com>
  9. * @author Ko- <k.stoffelen@cs.ru.nl>
  10. * @author Lukas Reschke <lukas@statuscode.ch>
  11. * @author Morris Jobke <hey@morrisjobke.de>
  12. * @author Robin McCorkell <robin@mccorkell.me.uk>
  13. * @author Roeland Jago Douma <roeland@famdouma.nl>
  14. *
  15. * @license AGPL-3.0
  16. *
  17. * This code is free software: you can redistribute it and/or modify
  18. * it under the terms of the GNU Affero General Public License, version 3,
  19. * as published by the Free Software Foundation.
  20. *
  21. * This program is distributed in the hope that it will be useful,
  22. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  23. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  24. * GNU Affero General Public License for more details.
  25. *
  26. * You should have received a copy of the GNU Affero General Public License, version 3,
  27. * along with this program. If not, see <http://www.gnu.org/licenses/>
  28. *
  29. */
  30. namespace OC\Settings\Controller;
  31. use bantu\IniGetWrapper\IniGetWrapper;
  32. use Doctrine\DBAL\DBALException;
  33. use Doctrine\DBAL\Platforms\SqlitePlatform;
  34. use GuzzleHttp\Exception\ClientException;
  35. use OC\AppFramework\Http;
  36. use OC\DB\Connection;
  37. use OC\DB\MissingIndexInformation;
  38. use OC\IntegrityCheck\Checker;
  39. use OC\Lock\NoopLockingProvider;
  40. use OCP\AppFramework\Controller;
  41. use OCP\AppFramework\Http\DataDisplayResponse;
  42. use OCP\AppFramework\Http\DataResponse;
  43. use OCP\AppFramework\Http\RedirectResponse;
  44. use OCP\Http\Client\IClientService;
  45. use OCP\IConfig;
  46. use OCP\IDateTimeFormatter;
  47. use OCP\IDBConnection;
  48. use OCP\IL10N;
  49. use OCP\ILogger;
  50. use OCP\IRequest;
  51. use OCP\IURLGenerator;
  52. use OCP\Lock\ILockingProvider;
  53. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  54. use Symfony\Component\EventDispatcher\GenericEvent;
  55. /**
  56. * @package OC\Settings\Controller
  57. */
  58. class CheckSetupController extends Controller {
  59. /** @var IConfig */
  60. private $config;
  61. /** @var IClientService */
  62. private $clientService;
  63. /** @var \OC_Util */
  64. private $util;
  65. /** @var IURLGenerator */
  66. private $urlGenerator;
  67. /** @var IL10N */
  68. private $l10n;
  69. /** @var Checker */
  70. private $checker;
  71. /** @var ILogger */
  72. private $logger;
  73. /** @var EventDispatcherInterface */
  74. private $dispatcher;
  75. /** @var IDBConnection|Connection */
  76. private $db;
  77. /** @var ILockingProvider */
  78. private $lockingProvider;
  79. /** @var IDateTimeFormatter */
  80. private $dateTimeFormatter;
  81. public function __construct($AppName,
  82. IRequest $request,
  83. IConfig $config,
  84. IClientService $clientService,
  85. IURLGenerator $urlGenerator,
  86. \OC_Util $util,
  87. IL10N $l10n,
  88. Checker $checker,
  89. ILogger $logger,
  90. EventDispatcherInterface $dispatcher,
  91. IDBConnection $db,
  92. ILockingProvider $lockingProvider,
  93. IDateTimeFormatter $dateTimeFormatter) {
  94. parent::__construct($AppName, $request);
  95. $this->config = $config;
  96. $this->clientService = $clientService;
  97. $this->util = $util;
  98. $this->urlGenerator = $urlGenerator;
  99. $this->l10n = $l10n;
  100. $this->checker = $checker;
  101. $this->logger = $logger;
  102. $this->dispatcher = $dispatcher;
  103. $this->db = $db;
  104. $this->lockingProvider = $lockingProvider;
  105. $this->dateTimeFormatter = $dateTimeFormatter;
  106. }
  107. /**
  108. * Checks if the server can connect to the internet using HTTPS and HTTP
  109. * @return bool
  110. */
  111. private function isInternetConnectionWorking() {
  112. if ($this->config->getSystemValue('has_internet_connection', true) === false) {
  113. return false;
  114. }
  115. $siteArray = ['www.nextcloud.com',
  116. 'www.startpage.com',
  117. 'www.eff.org',
  118. 'www.edri.org',
  119. ];
  120. foreach($siteArray as $site) {
  121. if ($this->isSiteReachable($site)) {
  122. return true;
  123. }
  124. }
  125. return false;
  126. }
  127. /**
  128. * Checks if the Nextcloud server can connect to a specific URL using both HTTPS and HTTP
  129. * @return bool
  130. */
  131. private function isSiteReachable($sitename) {
  132. $httpSiteName = 'http://' . $sitename . '/';
  133. $httpsSiteName = 'https://' . $sitename . '/';
  134. try {
  135. $client = $this->clientService->newClient();
  136. $client->get($httpSiteName);
  137. $client->get($httpsSiteName);
  138. } catch (\Exception $e) {
  139. $this->logger->logException($e, ['app' => 'internet_connection_check']);
  140. return false;
  141. }
  142. return true;
  143. }
  144. /**
  145. * Checks whether a local memcache is installed or not
  146. * @return bool
  147. */
  148. private function isMemcacheConfigured() {
  149. return $this->config->getSystemValue('memcache.local', null) !== null;
  150. }
  151. /**
  152. * Whether /dev/urandom is available to the PHP controller
  153. *
  154. * @return bool
  155. */
  156. private function isUrandomAvailable() {
  157. if(@file_exists('/dev/urandom')) {
  158. $file = fopen('/dev/urandom', 'rb');
  159. if($file) {
  160. fclose($file);
  161. return true;
  162. }
  163. }
  164. return false;
  165. }
  166. /**
  167. * Public for the sake of unit-testing
  168. *
  169. * @return array
  170. */
  171. protected function getCurlVersion() {
  172. return curl_version();
  173. }
  174. /**
  175. * Check if the used SSL lib is outdated. Older OpenSSL and NSS versions do
  176. * have multiple bugs which likely lead to problems in combination with
  177. * functionality required by ownCloud such as SNI.
  178. *
  179. * @link https://github.com/owncloud/core/issues/17446#issuecomment-122877546
  180. * @link https://bugzilla.redhat.com/show_bug.cgi?id=1241172
  181. * @return string
  182. */
  183. private function isUsedTlsLibOutdated() {
  184. // Don't run check when:
  185. // 1. Server has `has_internet_connection` set to false
  186. // 2. AppStore AND S2S is disabled
  187. if(!$this->config->getSystemValue('has_internet_connection', true)) {
  188. return '';
  189. }
  190. if(!$this->config->getSystemValue('appstoreenabled', true)
  191. && $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'no'
  192. && $this->config->getAppValue('files_sharing', 'incoming_server2server_share_enabled', 'yes') === 'no') {
  193. return '';
  194. }
  195. $versionString = $this->getCurlVersion();
  196. if(isset($versionString['ssl_version'])) {
  197. $versionString = $versionString['ssl_version'];
  198. } else {
  199. return '';
  200. }
  201. $features = (string)$this->l10n->t('installing and updating apps via the app store or Federated Cloud Sharing');
  202. if(!$this->config->getSystemValue('appstoreenabled', true)) {
  203. $features = (string)$this->l10n->t('Federated Cloud Sharing');
  204. }
  205. // Check if at least OpenSSL after 1.01d or 1.0.2b
  206. if(strpos($versionString, 'OpenSSL/') === 0) {
  207. $majorVersion = substr($versionString, 8, 5);
  208. $patchRelease = substr($versionString, 13, 6);
  209. if(($majorVersion === '1.0.1' && ord($patchRelease) < ord('d')) ||
  210. ($majorVersion === '1.0.2' && ord($patchRelease) < ord('b'))) {
  211. return (string) $this->l10n->t('cURL is using an outdated %s version (%s). Please update your operating system or features such as %s will not work reliably.', ['OpenSSL', $versionString, $features]);
  212. }
  213. }
  214. // Check if NSS and perform heuristic check
  215. if(strpos($versionString, 'NSS/') === 0) {
  216. try {
  217. $firstClient = $this->clientService->newClient();
  218. $firstClient->get('https://nextcloud.com/');
  219. $secondClient = $this->clientService->newClient();
  220. $secondClient->get('https://nextcloud.com/');
  221. } catch (ClientException $e) {
  222. if($e->getResponse()->getStatusCode() === 400) {
  223. return (string) $this->l10n->t('cURL is using an outdated %s version (%s). Please update your operating system or features such as %s will not work reliably.', ['NSS', $versionString, $features]);
  224. }
  225. }
  226. }
  227. return '';
  228. }
  229. /**
  230. * Whether the version is outdated
  231. *
  232. * @return bool
  233. */
  234. protected function isPhpOutdated() {
  235. if (version_compare(PHP_VERSION, '7.0.0', '<')) {
  236. return true;
  237. }
  238. return false;
  239. }
  240. /**
  241. * Whether the php version is still supported (at time of release)
  242. * according to: https://secure.php.net/supported-versions.php
  243. *
  244. * @return array
  245. */
  246. private function isPhpSupported() {
  247. return ['eol' => $this->isPhpOutdated(), 'version' => PHP_VERSION];
  248. }
  249. /**
  250. * Check if the reverse proxy configuration is working as expected
  251. *
  252. * @return bool
  253. */
  254. private function forwardedForHeadersWorking() {
  255. $trustedProxies = $this->config->getSystemValue('trusted_proxies', []);
  256. $remoteAddress = $this->request->getRemoteAddress();
  257. if (is_array($trustedProxies) && in_array($remoteAddress, $trustedProxies)) {
  258. return false;
  259. }
  260. // either not enabled or working correctly
  261. return true;
  262. }
  263. /**
  264. * Checks if the correct memcache module for PHP is installed. Only
  265. * fails if memcached is configured and the working module is not installed.
  266. *
  267. * @return bool
  268. */
  269. private function isCorrectMemcachedPHPModuleInstalled() {
  270. if ($this->config->getSystemValue('memcache.distributed', null) !== '\OC\Memcache\Memcached') {
  271. return true;
  272. }
  273. // there are two different memcached modules for PHP
  274. // we only support memcached and not memcache
  275. // https://code.google.com/p/memcached/wiki/PHPClientComparison
  276. return !(!extension_loaded('memcached') && extension_loaded('memcache'));
  277. }
  278. /**
  279. * Checks if set_time_limit is not disabled.
  280. *
  281. * @return bool
  282. */
  283. private function isSettimelimitAvailable() {
  284. if (function_exists('set_time_limit')
  285. && strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
  286. return true;
  287. }
  288. return false;
  289. }
  290. /**
  291. * @return RedirectResponse
  292. */
  293. public function rescanFailedIntegrityCheck() {
  294. $this->checker->runInstanceVerification();
  295. return new RedirectResponse(
  296. $this->urlGenerator->linkToRoute('settings.AdminSettings.index')
  297. );
  298. }
  299. /**
  300. * @NoCSRFRequired
  301. * @return DataResponse
  302. */
  303. public function getFailedIntegrityCheckFiles() {
  304. if(!$this->checker->isCodeCheckEnforced()) {
  305. return new DataDisplayResponse('Integrity checker has been disabled. Integrity cannot be verified.');
  306. }
  307. $completeResults = $this->checker->getResults();
  308. if(!empty($completeResults)) {
  309. $formattedTextResponse = 'Technical information
  310. =====================
  311. The following list covers which files have failed the integrity check. Please read
  312. the previous linked documentation to learn more about the errors and how to fix
  313. them.
  314. Results
  315. =======
  316. ';
  317. foreach($completeResults as $context => $contextResult) {
  318. $formattedTextResponse .= "- $context\n";
  319. foreach($contextResult as $category => $result) {
  320. $formattedTextResponse .= "\t- $category\n";
  321. if($category !== 'EXCEPTION') {
  322. foreach ($result as $key => $results) {
  323. $formattedTextResponse .= "\t\t- $key\n";
  324. }
  325. } else {
  326. foreach ($result as $key => $results) {
  327. $formattedTextResponse .= "\t\t- $results\n";
  328. }
  329. }
  330. }
  331. }
  332. $formattedTextResponse .= '
  333. Raw output
  334. ==========
  335. ';
  336. $formattedTextResponse .= print_r($completeResults, true);
  337. } else {
  338. $formattedTextResponse = 'No errors have been found.';
  339. }
  340. $response = new DataDisplayResponse(
  341. $formattedTextResponse,
  342. Http::STATUS_OK,
  343. [
  344. 'Content-Type' => 'text/plain',
  345. ]
  346. );
  347. return $response;
  348. }
  349. /**
  350. * Checks whether a PHP opcache is properly set up
  351. * @return bool
  352. */
  353. protected function isOpcacheProperlySetup() {
  354. $iniWrapper = new IniGetWrapper();
  355. if(!$iniWrapper->getBool('opcache.enable')) {
  356. return false;
  357. }
  358. if(!$iniWrapper->getBool('opcache.save_comments')) {
  359. return false;
  360. }
  361. if(!$iniWrapper->getBool('opcache.enable_cli')) {
  362. return false;
  363. }
  364. if($iniWrapper->getNumeric('opcache.max_accelerated_files') < 10000) {
  365. return false;
  366. }
  367. if($iniWrapper->getNumeric('opcache.memory_consumption') < 128) {
  368. return false;
  369. }
  370. if($iniWrapper->getNumeric('opcache.interned_strings_buffer') < 8) {
  371. return false;
  372. }
  373. return true;
  374. }
  375. /**
  376. * Check if the required FreeType functions are present
  377. * @return bool
  378. */
  379. protected function hasFreeTypeSupport() {
  380. return function_exists('imagettfbbox') && function_exists('imagettftext');
  381. }
  382. protected function hasMissingIndexes(): array {
  383. $indexInfo = new MissingIndexInformation();
  384. // Dispatch event so apps can also hint for pending index updates if needed
  385. $event = new GenericEvent($indexInfo);
  386. $this->dispatcher->dispatch(IDBConnection::CHECK_MISSING_INDEXES_EVENT, $event);
  387. return $indexInfo->getListOfMissingIndexes();
  388. }
  389. /**
  390. * warn if outdated version of a memcache module is used
  391. */
  392. protected function getOutdatedCaches(): array {
  393. $caches = [
  394. 'apcu' => ['name' => 'APCu', 'version' => '4.0.6'],
  395. 'redis' => ['name' => 'Redis', 'version' => '2.2.5'],
  396. ];
  397. $outdatedCaches = [];
  398. foreach ($caches as $php_module => $data) {
  399. $isOutdated = extension_loaded($php_module) && version_compare(phpversion($php_module), $data['version'], '<');
  400. if ($isOutdated) {
  401. $outdatedCaches[] = $data;
  402. }
  403. }
  404. return $outdatedCaches;
  405. }
  406. protected function isSqliteUsed() {
  407. return strpos($this->config->getSystemValue('dbtype'), 'sqlite') !== false;
  408. }
  409. protected function isReadOnlyConfig(): bool {
  410. return \OC_Helper::isReadOnlyConfigEnabled();
  411. }
  412. protected function hasValidTransactionIsolationLevel(): bool {
  413. try {
  414. if ($this->db->getDatabasePlatform() instanceof SqlitePlatform) {
  415. return true;
  416. }
  417. return $this->db->getTransactionIsolation() === Connection::TRANSACTION_READ_COMMITTED;
  418. } catch (DBALException $e) {
  419. // ignore
  420. }
  421. return true;
  422. }
  423. protected function hasFileinfoInstalled(): bool {
  424. return \OC_Util::fileInfoLoaded();
  425. }
  426. protected function hasWorkingFileLocking(): bool {
  427. return !($this->lockingProvider instanceof NoopLockingProvider);
  428. }
  429. protected function getSuggestedOverwriteCliURL(): string {
  430. $suggestedOverwriteCliUrl = '';
  431. if ($this->config->getSystemValue('overwrite.cli.url', '') === '') {
  432. $suggestedOverwriteCliUrl = $this->request->getServerProtocol() . '://' . $this->request->getInsecureServerHost() . \OC::$WEBROOT;
  433. if (!$this->config->getSystemValue('config_is_read_only', false)) {
  434. // Set the overwrite URL when it was not set yet.
  435. $this->config->setSystemValue('overwrite.cli.url', $suggestedOverwriteCliUrl);
  436. $suggestedOverwriteCliUrl = '';
  437. }
  438. }
  439. return $suggestedOverwriteCliUrl;
  440. }
  441. protected function getLastCronInfo(): array {
  442. $lastCronRun = $this->config->getAppValue('core', 'lastcron', 0);
  443. return [
  444. 'diffInSeconds' => time() - $lastCronRun,
  445. 'relativeTime' => $this->dateTimeFormatter->formatTimeSpan($lastCronRun),
  446. 'backgroundJobsUrl' => $this->urlGenerator->linkToRoute('settings.AdminSettings.index', ['section' => 'server']) . '#backgroundjobs',
  447. ];
  448. }
  449. protected function getCronErrors() {
  450. $errors = json_decode($this->config->getAppValue('core', 'cronErrors', ''), true);
  451. if (is_array($errors)) {
  452. return $errors;
  453. }
  454. return [];
  455. }
  456. protected function isPhpMailerUsed(): bool {
  457. return $this->config->getSystemValue('mail_smtpmode', 'php') === 'php';
  458. }
  459. protected function hasOpcacheLoaded(): bool {
  460. return function_exists('opcache_get_status');
  461. }
  462. /**
  463. * @return DataResponse
  464. */
  465. public function check() {
  466. return new DataResponse(
  467. [
  468. 'isGetenvServerWorking' => !empty(getenv('PATH')),
  469. 'isReadOnlyConfig' => $this->isReadOnlyConfig(),
  470. 'hasValidTransactionIsolationLevel' => $this->hasValidTransactionIsolationLevel(),
  471. 'outdatedCaches' => $this->getOutdatedCaches(),
  472. 'hasFileinfoInstalled' => $this->hasFileinfoInstalled(),
  473. 'hasWorkingFileLocking' => $this->hasWorkingFileLocking(),
  474. 'suggestedOverwriteCliURL' => $this->getSuggestedOverwriteCliURL(),
  475. 'cronInfo' => $this->getLastCronInfo(),
  476. 'cronErrors' => $this->getCronErrors(),
  477. 'serverHasInternetConnection' => $this->isInternetConnectionWorking(),
  478. 'isMemcacheConfigured' => $this->isMemcacheConfigured(),
  479. 'memcacheDocs' => $this->urlGenerator->linkToDocs('admin-performance'),
  480. 'isUrandomAvailable' => $this->isUrandomAvailable(),
  481. 'securityDocs' => $this->urlGenerator->linkToDocs('admin-security'),
  482. 'isUsedTlsLibOutdated' => $this->isUsedTlsLibOutdated(),
  483. 'phpSupported' => $this->isPhpSupported(),
  484. 'forwardedForHeadersWorking' => $this->forwardedForHeadersWorking(),
  485. 'reverseProxyDocs' => $this->urlGenerator->linkToDocs('admin-reverse-proxy'),
  486. 'isCorrectMemcachedPHPModuleInstalled' => $this->isCorrectMemcachedPHPModuleInstalled(),
  487. 'hasPassedCodeIntegrityCheck' => $this->checker->hasPassedCheck(),
  488. 'codeIntegrityCheckerDocumentation' => $this->urlGenerator->linkToDocs('admin-code-integrity'),
  489. 'isOpcacheProperlySetup' => $this->isOpcacheProperlySetup(),
  490. 'hasOpcacheLoaded' => $this->hasOpcacheLoaded(),
  491. 'phpOpcacheDocumentation' => $this->urlGenerator->linkToDocs('admin-php-opcache'),
  492. 'isSettimelimitAvailable' => $this->isSettimelimitAvailable(),
  493. 'hasFreeTypeSupport' => $this->hasFreeTypeSupport(),
  494. 'missingIndexes' => $this->hasMissingIndexes(),
  495. 'isSqliteUsed' => $this->isSqliteUsed(),
  496. 'databaseConversionDocumentation' => $this->urlGenerator->linkToDocs('admin-db-conversion'),
  497. 'isPhpMailerUsed' => $this->isPhpMailerUsed(),
  498. 'mailSettingsDocumentation' => $this->urlGenerator->getAbsoluteURL('index.php/settings/admin')
  499. ]
  500. );
  501. }
  502. }