You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Installer.php 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. * @copyright Copyright (c) 2016, Lukas Reschke <lukas@statuscode.ch>
  5. *
  6. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  7. * @author Brice Maron <brice@bmaron.net>
  8. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  9. * @author Daniel Kesselberg <mail@danielkesselberg.de>
  10. * @author Frank Karlitschek <frank@karlitschek.de>
  11. * @author Georg Ehrke <oc.list@georgehrke.com>
  12. * @author Joas Schilling <coding@schilljs.com>
  13. * @author John Molakvoæ (skjnldsv) <skjnldsv@protonmail.com>
  14. * @author Julius Härtl <jus@bitgrid.net>
  15. * @author Kamil Domanski <kdomanski@kdemail.net>
  16. * @author Lukas Reschke <lukas@statuscode.ch>
  17. * @author Markus Staab <markus.staab@redaxo.de>
  18. * @author Morris Jobke <hey@morrisjobke.de>
  19. * @author Robin Appelman <robin@icewind.nl>
  20. * @author Roeland Jago Douma <roeland@famdouma.nl>
  21. * @author root "root@oc.(none)"
  22. * @author Thomas Müller <thomas.mueller@tmit.eu>
  23. * @author Thomas Tanghus <thomas@tanghus.net>
  24. *
  25. * @license AGPL-3.0
  26. *
  27. * This code is free software: you can redistribute it and/or modify
  28. * it under the terms of the GNU Affero General Public License, version 3,
  29. * as published by the Free Software Foundation.
  30. *
  31. * This program is distributed in the hope that it will be useful,
  32. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  33. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  34. * GNU Affero General Public License for more details.
  35. *
  36. * You should have received a copy of the GNU Affero General Public License, version 3,
  37. * along with this program. If not, see <http://www.gnu.org/licenses/>
  38. *
  39. */
  40. namespace OC;
  41. use Doctrine\DBAL\Exception\TableExistsException;
  42. use OC\App\AppStore\Bundles\Bundle;
  43. use OC\App\AppStore\Fetcher\AppFetcher;
  44. use OC\AppFramework\Bootstrap\Coordinator;
  45. use OC\Archive\TAR;
  46. use OC\DB\Connection;
  47. use OC_App;
  48. use OC_DB;
  49. use OC_Helper;
  50. use OCP\Http\Client\IClientService;
  51. use OCP\IConfig;
  52. use OCP\ILogger;
  53. use OCP\ITempManager;
  54. use phpseclib\File\X509;
  55. /**
  56. * This class provides the functionality needed to install, update and remove apps
  57. */
  58. class Installer {
  59. /** @var AppFetcher */
  60. private $appFetcher;
  61. /** @var IClientService */
  62. private $clientService;
  63. /** @var ITempManager */
  64. private $tempManager;
  65. /** @var ILogger */
  66. private $logger;
  67. /** @var IConfig */
  68. private $config;
  69. /** @var array - for caching the result of app fetcher */
  70. private $apps = null;
  71. /** @var bool|null - for caching the result of the ready status */
  72. private $isInstanceReadyForUpdates = null;
  73. /** @var bool */
  74. private $isCLI;
  75. /**
  76. * @param AppFetcher $appFetcher
  77. * @param IClientService $clientService
  78. * @param ITempManager $tempManager
  79. * @param ILogger $logger
  80. * @param IConfig $config
  81. */
  82. public function __construct(
  83. AppFetcher $appFetcher,
  84. IClientService $clientService,
  85. ITempManager $tempManager,
  86. ILogger $logger,
  87. IConfig $config,
  88. bool $isCLI
  89. ) {
  90. $this->appFetcher = $appFetcher;
  91. $this->clientService = $clientService;
  92. $this->tempManager = $tempManager;
  93. $this->logger = $logger;
  94. $this->config = $config;
  95. $this->isCLI = $isCLI;
  96. }
  97. /**
  98. * Installs an app that is located in one of the app folders already
  99. *
  100. * @param string $appId App to install
  101. * @param bool $forceEnable
  102. * @throws \Exception
  103. * @return string app ID
  104. */
  105. public function installApp(string $appId, bool $forceEnable = false): string {
  106. $app = \OC_App::findAppInDirectories($appId);
  107. if ($app === false) {
  108. throw new \Exception('App not found in any app directory');
  109. }
  110. $basedir = $app['path'].'/'.$appId;
  111. $info = OC_App::getAppInfo($basedir.'/appinfo/info.xml', true);
  112. $l = \OC::$server->getL10N('core');
  113. if (!is_array($info)) {
  114. throw new \Exception(
  115. $l->t('App "%s" cannot be installed because appinfo file cannot be read.',
  116. [$appId]
  117. )
  118. );
  119. }
  120. $ignoreMaxApps = $this->config->getSystemValue('app_install_overwrite', []);
  121. $ignoreMax = $forceEnable || in_array($appId, $ignoreMaxApps, true);
  122. $version = implode('.', \OCP\Util::getVersion());
  123. if (!\OC_App::isAppCompatible($version, $info, $ignoreMax)) {
  124. throw new \Exception(
  125. // TODO $l
  126. $l->t('App "%s" cannot be installed because it is not compatible with this version of the server.',
  127. [$info['name']]
  128. )
  129. );
  130. }
  131. // check for required dependencies
  132. \OC_App::checkAppDependencies($this->config, $l, $info, $ignoreMax);
  133. /** @var Coordinator $coordinator */
  134. $coordinator = \OC::$server->get(Coordinator::class);
  135. $coordinator->runLazyRegistration($appId);
  136. \OC_App::registerAutoloading($appId, $basedir);
  137. $previousVersion = $this->config->getAppValue($info['id'], 'installed_version', false);
  138. if ($previousVersion) {
  139. OC_App::executeRepairSteps($appId, $info['repair-steps']['pre-migration']);
  140. }
  141. //install the database
  142. if (is_file($basedir.'/appinfo/database.xml')) {
  143. if (\OC::$server->getConfig()->getAppValue($info['id'], 'installed_version') === null) {
  144. OC_DB::createDbFromStructure($basedir.'/appinfo/database.xml');
  145. } else {
  146. OC_DB::updateDbFromStructure($basedir.'/appinfo/database.xml');
  147. }
  148. } else {
  149. $ms = new \OC\DB\MigrationService($info['id'], \OC::$server->get(Connection::class));
  150. $ms->migrate('latest', true);
  151. }
  152. if ($previousVersion) {
  153. OC_App::executeRepairSteps($appId, $info['repair-steps']['post-migration']);
  154. }
  155. \OC_App::setupBackgroundJobs($info['background-jobs']);
  156. //run appinfo/install.php
  157. self::includeAppScript($basedir . '/appinfo/install.php');
  158. $appData = OC_App::getAppInfo($appId);
  159. OC_App::executeRepairSteps($appId, $appData['repair-steps']['install']);
  160. //set the installed version
  161. \OC::$server->getConfig()->setAppValue($info['id'], 'installed_version', OC_App::getAppVersion($info['id'], false));
  162. \OC::$server->getConfig()->setAppValue($info['id'], 'enabled', 'no');
  163. //set remote/public handlers
  164. foreach ($info['remote'] as $name => $path) {
  165. \OC::$server->getConfig()->setAppValue('core', 'remote_'.$name, $info['id'].'/'.$path);
  166. }
  167. foreach ($info['public'] as $name => $path) {
  168. \OC::$server->getConfig()->setAppValue('core', 'public_'.$name, $info['id'].'/'.$path);
  169. }
  170. OC_App::setAppTypes($info['id']);
  171. return $info['id'];
  172. }
  173. /**
  174. * Updates the specified app from the appstore
  175. *
  176. * @param string $appId
  177. * @param bool [$allowUnstable] Allow unstable releases
  178. * @return bool
  179. */
  180. public function updateAppstoreApp($appId, $allowUnstable = false) {
  181. if ($this->isUpdateAvailable($appId, $allowUnstable)) {
  182. try {
  183. $this->downloadApp($appId, $allowUnstable);
  184. } catch (\Exception $e) {
  185. $this->logger->logException($e, [
  186. 'level' => ILogger::ERROR,
  187. 'app' => 'core',
  188. ]);
  189. return false;
  190. }
  191. return OC_App::updateApp($appId);
  192. }
  193. return false;
  194. }
  195. /**
  196. * Split the certificate file in individual certs
  197. *
  198. * @param string $cert
  199. * @return string[]
  200. */
  201. private function splitCerts(string $cert): array {
  202. preg_match_all('([\-]{3,}[\S\ ]+?[\-]{3,}[\S\s]+?[\-]{3,}[\S\ ]+?[\-]{3,})', $cert, $matches);
  203. return $matches[0];
  204. }
  205. /**
  206. * Downloads an app and puts it into the app directory
  207. *
  208. * @param string $appId
  209. * @param bool [$allowUnstable]
  210. *
  211. * @throws \Exception If the installation was not successful
  212. */
  213. public function downloadApp($appId, $allowUnstable = false) {
  214. $appId = strtolower($appId);
  215. $apps = $this->appFetcher->get($allowUnstable);
  216. foreach ($apps as $app) {
  217. if ($app['id'] === $appId) {
  218. // Load the certificate
  219. $certificate = new X509();
  220. $rootCrt = file_get_contents(__DIR__ . '/../../resources/codesigning/root.crt');
  221. $rootCrts = $this->splitCerts($rootCrt);
  222. foreach ($rootCrts as $rootCrt) {
  223. $certificate->loadCA($rootCrt);
  224. }
  225. $loadedCertificate = $certificate->loadX509($app['certificate']);
  226. // Verify if the certificate has been revoked
  227. $crl = new X509();
  228. foreach ($rootCrts as $rootCrt) {
  229. $crl->loadCA($rootCrt);
  230. }
  231. $crl->loadCRL(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crl'));
  232. if ($crl->validateSignature() !== true) {
  233. throw new \Exception('Could not validate CRL signature');
  234. }
  235. $csn = $loadedCertificate['tbsCertificate']['serialNumber']->toString();
  236. $revoked = $crl->getRevoked($csn);
  237. if ($revoked !== false) {
  238. throw new \Exception(
  239. sprintf(
  240. 'Certificate "%s" has been revoked',
  241. $csn
  242. )
  243. );
  244. }
  245. // Verify if the certificate has been issued by the Nextcloud Code Authority CA
  246. if ($certificate->validateSignature() !== true) {
  247. throw new \Exception(
  248. sprintf(
  249. 'App with id %s has a certificate not issued by a trusted Code Signing Authority',
  250. $appId
  251. )
  252. );
  253. }
  254. // Verify if the certificate is issued for the requested app id
  255. $certInfo = openssl_x509_parse($app['certificate']);
  256. if (!isset($certInfo['subject']['CN'])) {
  257. throw new \Exception(
  258. sprintf(
  259. 'App with id %s has a cert with no CN',
  260. $appId
  261. )
  262. );
  263. }
  264. if ($certInfo['subject']['CN'] !== $appId) {
  265. throw new \Exception(
  266. sprintf(
  267. 'App with id %s has a cert issued to %s',
  268. $appId,
  269. $certInfo['subject']['CN']
  270. )
  271. );
  272. }
  273. // Download the release
  274. $tempFile = $this->tempManager->getTemporaryFile('.tar.gz');
  275. $timeout = $this->isCLI ? 0 : 120;
  276. $client = $this->clientService->newClient();
  277. $client->get($app['releases'][0]['download'], ['sink' => $tempFile, 'timeout' => $timeout]);
  278. // Check if the signature actually matches the downloaded content
  279. $certificate = openssl_get_publickey($app['certificate']);
  280. $verified = (bool)openssl_verify(file_get_contents($tempFile), base64_decode($app['releases'][0]['signature']), $certificate, OPENSSL_ALGO_SHA512);
  281. openssl_free_key($certificate);
  282. if ($verified === true) {
  283. // Seems to match, let's proceed
  284. $extractDir = $this->tempManager->getTemporaryFolder();
  285. $archive = new TAR($tempFile);
  286. if ($archive) {
  287. if (!$archive->extract($extractDir)) {
  288. $errorMessage = 'Could not extract app ' . $appId;
  289. $archiveError = $archive->getError();
  290. if ($archiveError instanceof \PEAR_Error) {
  291. $errorMessage .= ': ' . $archiveError->getMessage();
  292. }
  293. throw new \Exception($errorMessage);
  294. }
  295. $allFiles = scandir($extractDir);
  296. $folders = array_diff($allFiles, ['.', '..']);
  297. $folders = array_values($folders);
  298. if (count($folders) > 1) {
  299. throw new \Exception(
  300. sprintf(
  301. 'Extracted app %s has more than 1 folder',
  302. $appId
  303. )
  304. );
  305. }
  306. // Check if appinfo/info.xml has the same app ID as well
  307. $loadEntities = libxml_disable_entity_loader(false);
  308. $xml = simplexml_load_file($extractDir . '/' . $folders[0] . '/appinfo/info.xml');
  309. libxml_disable_entity_loader($loadEntities);
  310. if ((string)$xml->id !== $appId) {
  311. throw new \Exception(
  312. sprintf(
  313. 'App for id %s has a wrong app ID in info.xml: %s',
  314. $appId,
  315. (string)$xml->id
  316. )
  317. );
  318. }
  319. // Check if the version is lower than before
  320. $currentVersion = OC_App::getAppVersion($appId);
  321. $newVersion = (string)$xml->version;
  322. if (version_compare($currentVersion, $newVersion) === 1) {
  323. throw new \Exception(
  324. sprintf(
  325. 'App for id %s has version %s and tried to update to lower version %s',
  326. $appId,
  327. $currentVersion,
  328. $newVersion
  329. )
  330. );
  331. }
  332. $baseDir = OC_App::getInstallPath() . '/' . $appId;
  333. // Remove old app with the ID if existent
  334. OC_Helper::rmdirr($baseDir);
  335. // Move to app folder
  336. if (@mkdir($baseDir)) {
  337. $extractDir .= '/' . $folders[0];
  338. OC_Helper::copyr($extractDir, $baseDir);
  339. }
  340. OC_Helper::copyr($extractDir, $baseDir);
  341. OC_Helper::rmdirr($extractDir);
  342. return;
  343. } else {
  344. throw new \Exception(
  345. sprintf(
  346. 'Could not extract app with ID %s to %s',
  347. $appId,
  348. $extractDir
  349. )
  350. );
  351. }
  352. } else {
  353. // Signature does not match
  354. throw new \Exception(
  355. sprintf(
  356. 'App with id %s has invalid signature',
  357. $appId
  358. )
  359. );
  360. }
  361. }
  362. }
  363. throw new \Exception(
  364. sprintf(
  365. 'Could not download app %s',
  366. $appId
  367. )
  368. );
  369. }
  370. /**
  371. * Check if an update for the app is available
  372. *
  373. * @param string $appId
  374. * @param bool $allowUnstable
  375. * @return string|false false or the version number of the update
  376. */
  377. public function isUpdateAvailable($appId, $allowUnstable = false) {
  378. if ($this->isInstanceReadyForUpdates === null) {
  379. $installPath = OC_App::getInstallPath();
  380. if ($installPath === false || $installPath === null) {
  381. $this->isInstanceReadyForUpdates = false;
  382. } else {
  383. $this->isInstanceReadyForUpdates = true;
  384. }
  385. }
  386. if ($this->isInstanceReadyForUpdates === false) {
  387. return false;
  388. }
  389. if ($this->isInstalledFromGit($appId) === true) {
  390. return false;
  391. }
  392. if ($this->apps === null) {
  393. $this->apps = $this->appFetcher->get($allowUnstable);
  394. }
  395. foreach ($this->apps as $app) {
  396. if ($app['id'] === $appId) {
  397. $currentVersion = OC_App::getAppVersion($appId);
  398. if (!isset($app['releases'][0]['version'])) {
  399. return false;
  400. }
  401. $newestVersion = $app['releases'][0]['version'];
  402. if ($currentVersion !== '0' && version_compare($newestVersion, $currentVersion, '>')) {
  403. return $newestVersion;
  404. } else {
  405. return false;
  406. }
  407. }
  408. }
  409. return false;
  410. }
  411. /**
  412. * Check if app has been installed from git
  413. * @param string $name name of the application to remove
  414. * @return boolean
  415. *
  416. * The function will check if the path contains a .git folder
  417. */
  418. private function isInstalledFromGit($appId) {
  419. $app = \OC_App::findAppInDirectories($appId);
  420. if ($app === false) {
  421. return false;
  422. }
  423. $basedir = $app['path'].'/'.$appId;
  424. return file_exists($basedir.'/.git/');
  425. }
  426. /**
  427. * Check if app is already downloaded
  428. * @param string $name name of the application to remove
  429. * @return boolean
  430. *
  431. * The function will check if the app is already downloaded in the apps repository
  432. */
  433. public function isDownloaded($name) {
  434. foreach (\OC::$APPSROOTS as $dir) {
  435. $dirToTest = $dir['path'];
  436. $dirToTest .= '/';
  437. $dirToTest .= $name;
  438. $dirToTest .= '/';
  439. if (is_dir($dirToTest)) {
  440. return true;
  441. }
  442. }
  443. return false;
  444. }
  445. /**
  446. * Removes an app
  447. * @param string $appId ID of the application to remove
  448. * @return boolean
  449. *
  450. *
  451. * This function works as follows
  452. * -# call uninstall repair steps
  453. * -# removing the files
  454. *
  455. * The function will not delete preferences, tables and the configuration,
  456. * this has to be done by the function oc_app_uninstall().
  457. */
  458. public function removeApp($appId) {
  459. if ($this->isDownloaded($appId)) {
  460. if (\OC::$server->getAppManager()->isShipped($appId)) {
  461. return false;
  462. }
  463. $appDir = OC_App::getInstallPath() . '/' . $appId;
  464. OC_Helper::rmdirr($appDir);
  465. return true;
  466. } else {
  467. \OCP\Util::writeLog('core', 'can\'t remove app '.$appId.'. It is not installed.', ILogger::ERROR);
  468. return false;
  469. }
  470. }
  471. /**
  472. * Installs the app within the bundle and marks the bundle as installed
  473. *
  474. * @param Bundle $bundle
  475. * @throws \Exception If app could not get installed
  476. */
  477. public function installAppBundle(Bundle $bundle) {
  478. $appIds = $bundle->getAppIdentifiers();
  479. foreach ($appIds as $appId) {
  480. if (!$this->isDownloaded($appId)) {
  481. $this->downloadApp($appId);
  482. }
  483. $this->installApp($appId);
  484. $app = new OC_App();
  485. $app->enable($appId);
  486. }
  487. $bundles = json_decode($this->config->getAppValue('core', 'installed.bundles', json_encode([])), true);
  488. $bundles[] = $bundle->getIdentifier();
  489. $this->config->setAppValue('core', 'installed.bundles', json_encode($bundles));
  490. }
  491. /**
  492. * Installs shipped apps
  493. *
  494. * This function installs all apps found in the 'apps' directory that should be enabled by default;
  495. * @param bool $softErrors When updating we ignore errors and simply log them, better to have a
  496. * working ownCloud at the end instead of an aborted update.
  497. * @return array Array of error messages (appid => Exception)
  498. */
  499. public static function installShippedApps($softErrors = false) {
  500. $appManager = \OC::$server->getAppManager();
  501. $config = \OC::$server->getConfig();
  502. $errors = [];
  503. foreach (\OC::$APPSROOTS as $app_dir) {
  504. if ($dir = opendir($app_dir['path'])) {
  505. while (false !== ($filename = readdir($dir))) {
  506. if ($filename[0] !== '.' and is_dir($app_dir['path']."/$filename")) {
  507. if (file_exists($app_dir['path']."/$filename/appinfo/info.xml")) {
  508. if ($config->getAppValue($filename, "installed_version", null) === null) {
  509. $info = OC_App::getAppInfo($filename);
  510. $enabled = isset($info['default_enable']);
  511. if (($enabled || in_array($filename, $appManager->getAlwaysEnabledApps()))
  512. && $config->getAppValue($filename, 'enabled') !== 'no') {
  513. if ($softErrors) {
  514. try {
  515. Installer::installShippedApp($filename);
  516. } catch (HintException $e) {
  517. if ($e->getPrevious() instanceof TableExistsException) {
  518. $errors[$filename] = $e;
  519. continue;
  520. }
  521. throw $e;
  522. }
  523. } else {
  524. Installer::installShippedApp($filename);
  525. }
  526. $config->setAppValue($filename, 'enabled', 'yes');
  527. }
  528. }
  529. }
  530. }
  531. }
  532. closedir($dir);
  533. }
  534. }
  535. return $errors;
  536. }
  537. /**
  538. * install an app already placed in the app folder
  539. * @param string $app id of the app to install
  540. * @return integer
  541. */
  542. public static function installShippedApp($app) {
  543. //install the database
  544. $appPath = OC_App::getAppPath($app);
  545. \OC_App::registerAutoloading($app, $appPath);
  546. if (is_file("$appPath/appinfo/database.xml")) {
  547. try {
  548. OC_DB::createDbFromStructure("$appPath/appinfo/database.xml");
  549. } catch (TableExistsException $e) {
  550. throw new HintException(
  551. 'Failed to enable app ' . $app,
  552. 'Please ask for help via one of our <a href="https://nextcloud.com/support/" target="_blank" rel="noreferrer noopener">support channels</a>.',
  553. 0, $e
  554. );
  555. }
  556. } else {
  557. $ms = new \OC\DB\MigrationService($app, \OC::$server->get(Connection::class));
  558. $ms->migrate('latest', true);
  559. }
  560. //run appinfo/install.php
  561. self::includeAppScript("$appPath/appinfo/install.php");
  562. $info = OC_App::getAppInfo($app);
  563. if (is_null($info)) {
  564. return false;
  565. }
  566. \OC_App::setupBackgroundJobs($info['background-jobs']);
  567. OC_App::executeRepairSteps($app, $info['repair-steps']['install']);
  568. $config = \OC::$server->getConfig();
  569. $config->setAppValue($app, 'installed_version', OC_App::getAppVersion($app));
  570. if (array_key_exists('ocsid', $info)) {
  571. $config->setAppValue($app, 'ocsid', $info['ocsid']);
  572. }
  573. //set remote/public handlers
  574. foreach ($info['remote'] as $name => $path) {
  575. $config->setAppValue('core', 'remote_'.$name, $app.'/'.$path);
  576. }
  577. foreach ($info['public'] as $name => $path) {
  578. $config->setAppValue('core', 'public_'.$name, $app.'/'.$path);
  579. }
  580. OC_App::setAppTypes($info['id']);
  581. return $info['id'];
  582. }
  583. /**
  584. * @param string $script
  585. */
  586. private static function includeAppScript($script) {
  587. if (file_exists($script)) {
  588. include $script;
  589. }
  590. }
  591. }