Checker.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright Copyright (c) 2016, ownCloud, Inc.
  5. *
  6. * @author Joas Schilling <coding@schilljs.com>
  7. * @author Lukas Reschke <lukas@statuscode.ch>
  8. * @author Roeland Jago Douma <roeland@famdouma.nl>
  9. * @author Victor Dubiniuk <dubiniuk@owncloud.com>
  10. * @author Vincent Petry <pvince81@owncloud.com>
  11. *
  12. * @license AGPL-3.0
  13. *
  14. * This code is free software: you can redistribute it and/or modify
  15. * it under the terms of the GNU Affero General Public License, version 3,
  16. * as published by the Free Software Foundation.
  17. *
  18. * This program is distributed in the hope that it will be useful,
  19. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  20. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  21. * GNU Affero General Public License for more details.
  22. *
  23. * You should have received a copy of the GNU Affero General Public License, version 3,
  24. * along with this program. If not, see <http://www.gnu.org/licenses/>
  25. *
  26. */
  27. namespace OC\IntegrityCheck;
  28. use OC\IntegrityCheck\Exceptions\InvalidSignatureException;
  29. use OC\IntegrityCheck\Helpers\AppLocator;
  30. use OC\IntegrityCheck\Helpers\EnvironmentHelper;
  31. use OC\IntegrityCheck\Helpers\FileAccessHelper;
  32. use OC\IntegrityCheck\Iterator\ExcludeFileByNameFilterIterator;
  33. use OC\IntegrityCheck\Iterator\ExcludeFoldersByPathFilterIterator;
  34. use OCP\App\IAppManager;
  35. use OCP\ICache;
  36. use OCP\ICacheFactory;
  37. use OCP\IConfig;
  38. use OCP\ITempManager;
  39. use phpseclib\Crypt\RSA;
  40. use phpseclib\File\X509;
  41. /**
  42. * Class Checker handles the code signing using X.509 and RSA. ownCloud ships with
  43. * a public root certificate certificate that allows to issue new certificates that
  44. * will be trusted for signing code. The CN will be used to verify that a certificate
  45. * given to a third-party developer may not be used for other applications. For
  46. * example the author of the application "calendar" would only receive a certificate
  47. * only valid for this application.
  48. *
  49. * @package OC\IntegrityCheck
  50. */
  51. class Checker {
  52. const CACHE_KEY = 'oc.integritycheck.checker';
  53. /** @var EnvironmentHelper */
  54. private $environmentHelper;
  55. /** @var AppLocator */
  56. private $appLocator;
  57. /** @var FileAccessHelper */
  58. private $fileAccessHelper;
  59. /** @var IConfig */
  60. private $config;
  61. /** @var ICache */
  62. private $cache;
  63. /** @var IAppManager */
  64. private $appManager;
  65. /** @var ITempManager */
  66. private $tempManager;
  67. /**
  68. * @param EnvironmentHelper $environmentHelper
  69. * @param FileAccessHelper $fileAccessHelper
  70. * @param AppLocator $appLocator
  71. * @param IConfig $config
  72. * @param ICacheFactory $cacheFactory
  73. * @param IAppManager $appManager
  74. * @param ITempManager $tempManager
  75. */
  76. public function __construct(EnvironmentHelper $environmentHelper,
  77. FileAccessHelper $fileAccessHelper,
  78. AppLocator $appLocator,
  79. IConfig $config = null,
  80. ICacheFactory $cacheFactory,
  81. IAppManager $appManager = null,
  82. ITempManager $tempManager) {
  83. $this->environmentHelper = $environmentHelper;
  84. $this->fileAccessHelper = $fileAccessHelper;
  85. $this->appLocator = $appLocator;
  86. $this->config = $config;
  87. $this->cache = $cacheFactory->createDistributed(self::CACHE_KEY);
  88. $this->appManager = $appManager;
  89. $this->tempManager = $tempManager;
  90. }
  91. /**
  92. * Whether code signing is enforced or not.
  93. *
  94. * @return bool
  95. */
  96. public function isCodeCheckEnforced(): bool {
  97. $notSignedChannels = [ '', 'git'];
  98. if (\in_array($this->environmentHelper->getChannel(), $notSignedChannels, true)) {
  99. return false;
  100. }
  101. /**
  102. * This config option is undocumented and supposed to be so, it's only
  103. * applicable for very specific scenarios and we should not advertise it
  104. * too prominent. So please do not add it to config.sample.php.
  105. */
  106. $isIntegrityCheckDisabled = false;
  107. if ($this->config !== null) {
  108. $isIntegrityCheckDisabled = $this->config->getSystemValue('integrity.check.disabled', false);
  109. }
  110. if ($isIntegrityCheckDisabled === true) {
  111. return false;
  112. }
  113. return true;
  114. }
  115. /**
  116. * Enumerates all files belonging to the folder. Sensible defaults are excluded.
  117. *
  118. * @param string $folderToIterate
  119. * @param string $root
  120. * @return \RecursiveIteratorIterator
  121. * @throws \Exception
  122. */
  123. private function getFolderIterator(string $folderToIterate, string $root = ''): \RecursiveIteratorIterator {
  124. $dirItr = new \RecursiveDirectoryIterator(
  125. $folderToIterate,
  126. \RecursiveDirectoryIterator::SKIP_DOTS
  127. );
  128. if($root === '') {
  129. $root = \OC::$SERVERROOT;
  130. }
  131. $root = rtrim($root, '/');
  132. $excludeGenericFilesIterator = new ExcludeFileByNameFilterIterator($dirItr);
  133. $excludeFoldersIterator = new ExcludeFoldersByPathFilterIterator($excludeGenericFilesIterator, $root);
  134. return new \RecursiveIteratorIterator(
  135. $excludeFoldersIterator,
  136. \RecursiveIteratorIterator::SELF_FIRST
  137. );
  138. }
  139. /**
  140. * Returns an array of ['filename' => 'SHA512-hash-of-file'] for all files found
  141. * in the iterator.
  142. *
  143. * @param \RecursiveIteratorIterator $iterator
  144. * @param string $path
  145. * @return array Array of hashes.
  146. */
  147. private function generateHashes(\RecursiveIteratorIterator $iterator,
  148. string $path): array {
  149. $hashes = [];
  150. $copiedWebserverSettingFiles = false;
  151. $tmpFolder = '';
  152. $baseDirectoryLength = \strlen($path);
  153. foreach($iterator as $filename => $data) {
  154. /** @var \DirectoryIterator $data */
  155. if($data->isDir()) {
  156. continue;
  157. }
  158. $relativeFileName = substr($filename, $baseDirectoryLength);
  159. $relativeFileName = ltrim($relativeFileName, '/');
  160. // Exclude signature.json files in the appinfo and root folder
  161. if($relativeFileName === 'appinfo/signature.json') {
  162. continue;
  163. }
  164. // Exclude signature.json files in the appinfo and core folder
  165. if($relativeFileName === 'core/signature.json') {
  166. continue;
  167. }
  168. // The .user.ini and the .htaccess file of ownCloud can contain some
  169. // custom modifications such as for example the maximum upload size
  170. // to ensure that this will not lead to false positives this will
  171. // copy the file to a temporary folder and reset it to the default
  172. // values.
  173. if($filename === $this->environmentHelper->getServerRoot() . '/.htaccess'
  174. || $filename === $this->environmentHelper->getServerRoot() . '/.user.ini') {
  175. if(!$copiedWebserverSettingFiles) {
  176. $tmpFolder = rtrim($this->tempManager->getTemporaryFolder(), '/');
  177. copy($this->environmentHelper->getServerRoot() . '/.htaccess', $tmpFolder . '/.htaccess');
  178. copy($this->environmentHelper->getServerRoot() . '/.user.ini', $tmpFolder . '/.user.ini');
  179. \OC_Files::setUploadLimit(
  180. \OCP\Util::computerFileSize('511MB'),
  181. [
  182. '.htaccess' => $tmpFolder . '/.htaccess',
  183. '.user.ini' => $tmpFolder . '/.user.ini',
  184. ]
  185. );
  186. }
  187. }
  188. // The .user.ini file can contain custom modifications to the file size
  189. // as well.
  190. if($filename === $this->environmentHelper->getServerRoot() . '/.user.ini') {
  191. $fileContent = file_get_contents($tmpFolder . '/.user.ini');
  192. $hashes[$relativeFileName] = hash('sha512', $fileContent);
  193. continue;
  194. }
  195. // The .htaccess file in the root folder of ownCloud can contain
  196. // custom content after the installation due to the fact that dynamic
  197. // content is written into it at installation time as well. This
  198. // includes for example the 404 and 403 instructions.
  199. // Thus we ignore everything below the first occurrence of
  200. // "#### DO NOT CHANGE ANYTHING ABOVE THIS LINE ####" and have the
  201. // hash generated based on this.
  202. if($filename === $this->environmentHelper->getServerRoot() . '/.htaccess') {
  203. $fileContent = file_get_contents($tmpFolder . '/.htaccess');
  204. $explodedArray = explode('#### DO NOT CHANGE ANYTHING ABOVE THIS LINE ####', $fileContent);
  205. if(\count($explodedArray) === 2) {
  206. $hashes[$relativeFileName] = hash('sha512', $explodedArray[0]);
  207. continue;
  208. }
  209. }
  210. $hashes[$relativeFileName] = hash_file('sha512', $filename);
  211. }
  212. return $hashes;
  213. }
  214. /**
  215. * Creates the signature data
  216. *
  217. * @param array $hashes
  218. * @param X509 $certificate
  219. * @param RSA $privateKey
  220. * @return array
  221. */
  222. private function createSignatureData(array $hashes,
  223. X509 $certificate,
  224. RSA $privateKey): array {
  225. ksort($hashes);
  226. $privateKey->setSignatureMode(RSA::SIGNATURE_PSS);
  227. $privateKey->setMGFHash('sha512');
  228. // See https://tools.ietf.org/html/rfc3447#page-38
  229. $privateKey->setSaltLength(0);
  230. $signature = $privateKey->sign(json_encode($hashes));
  231. return [
  232. 'hashes' => $hashes,
  233. 'signature' => base64_encode($signature),
  234. 'certificate' => $certificate->saveX509($certificate->currentCert),
  235. ];
  236. }
  237. /**
  238. * Write the signature of the app in the specified folder
  239. *
  240. * @param string $path
  241. * @param X509 $certificate
  242. * @param RSA $privateKey
  243. * @throws \Exception
  244. */
  245. public function writeAppSignature($path,
  246. X509 $certificate,
  247. RSA $privateKey) {
  248. $appInfoDir = $path . '/appinfo';
  249. try {
  250. $this->fileAccessHelper->assertDirectoryExists($appInfoDir);
  251. $iterator = $this->getFolderIterator($path);
  252. $hashes = $this->generateHashes($iterator, $path);
  253. $signature = $this->createSignatureData($hashes, $certificate, $privateKey);
  254. $this->fileAccessHelper->file_put_contents(
  255. $appInfoDir . '/signature.json',
  256. json_encode($signature, JSON_PRETTY_PRINT)
  257. );
  258. } catch (\Exception $e){
  259. if (!$this->fileAccessHelper->is_writable($appInfoDir)) {
  260. throw new \Exception($appInfoDir . ' is not writable');
  261. }
  262. throw $e;
  263. }
  264. }
  265. /**
  266. * Write the signature of core
  267. *
  268. * @param X509 $certificate
  269. * @param RSA $rsa
  270. * @param string $path
  271. * @throws \Exception
  272. */
  273. public function writeCoreSignature(X509 $certificate,
  274. RSA $rsa,
  275. $path) {
  276. $coreDir = $path . '/core';
  277. try {
  278. $this->fileAccessHelper->assertDirectoryExists($coreDir);
  279. $iterator = $this->getFolderIterator($path, $path);
  280. $hashes = $this->generateHashes($iterator, $path);
  281. $signatureData = $this->createSignatureData($hashes, $certificate, $rsa);
  282. $this->fileAccessHelper->file_put_contents(
  283. $coreDir . '/signature.json',
  284. json_encode($signatureData, JSON_PRETTY_PRINT)
  285. );
  286. } catch (\Exception $e){
  287. if (!$this->fileAccessHelper->is_writable($coreDir)) {
  288. throw new \Exception($coreDir . ' is not writable');
  289. }
  290. throw $e;
  291. }
  292. }
  293. /**
  294. * Verifies the signature for the specified path.
  295. *
  296. * @param string $signaturePath
  297. * @param string $basePath
  298. * @param string $certificateCN
  299. * @return array
  300. * @throws InvalidSignatureException
  301. * @throws \Exception
  302. */
  303. private function verify(string $signaturePath, string $basePath, string $certificateCN): array {
  304. if(!$this->isCodeCheckEnforced()) {
  305. return [];
  306. }
  307. $content = $this->fileAccessHelper->file_get_contents($signaturePath);
  308. $signatureData = null;
  309. if (\is_string($content)) {
  310. $signatureData = json_decode($content, true);
  311. }
  312. if(!\is_array($signatureData)) {
  313. throw new InvalidSignatureException('Signature data not found.');
  314. }
  315. $expectedHashes = $signatureData['hashes'];
  316. ksort($expectedHashes);
  317. $signature = base64_decode($signatureData['signature']);
  318. $certificate = $signatureData['certificate'];
  319. // Check if certificate is signed by Nextcloud Root Authority
  320. $x509 = new \phpseclib\File\X509();
  321. $rootCertificatePublicKey = $this->fileAccessHelper->file_get_contents($this->environmentHelper->getServerRoot().'/resources/codesigning/root.crt');
  322. $x509->loadCA($rootCertificatePublicKey);
  323. $x509->loadX509($certificate);
  324. if(!$x509->validateSignature()) {
  325. throw new InvalidSignatureException('Certificate is not valid.');
  326. }
  327. // Verify if certificate has proper CN. "core" CN is always trusted.
  328. if($x509->getDN(X509::DN_OPENSSL)['CN'] !== $certificateCN && $x509->getDN(X509::DN_OPENSSL)['CN'] !== 'core') {
  329. throw new InvalidSignatureException(
  330. sprintf('Certificate is not valid for required scope. (Requested: %s, current: CN=%s)', $certificateCN, $x509->getDN(true)['CN'])
  331. );
  332. }
  333. // Check if the signature of the files is valid
  334. $rsa = new \phpseclib\Crypt\RSA();
  335. $rsa->loadKey($x509->currentCert['tbsCertificate']['subjectPublicKeyInfo']['subjectPublicKey']);
  336. $rsa->setSignatureMode(RSA::SIGNATURE_PSS);
  337. $rsa->setMGFHash('sha512');
  338. // See https://tools.ietf.org/html/rfc3447#page-38
  339. $rsa->setSaltLength(0);
  340. if(!$rsa->verify(json_encode($expectedHashes), $signature)) {
  341. throw new InvalidSignatureException('Signature could not get verified.');
  342. }
  343. // Fixes for the updater as shipped with ownCloud 9.0.x: The updater is
  344. // replaced after the code integrity check is performed.
  345. //
  346. // Due to this reason we exclude the whole updater/ folder from the code
  347. // integrity check.
  348. if($basePath === $this->environmentHelper->getServerRoot()) {
  349. foreach($expectedHashes as $fileName => $hash) {
  350. if(strpos($fileName, 'updater/') === 0) {
  351. unset($expectedHashes[$fileName]);
  352. }
  353. }
  354. }
  355. // Compare the list of files which are not identical
  356. $currentInstanceHashes = $this->generateHashes($this->getFolderIterator($basePath), $basePath);
  357. $differencesA = array_diff($expectedHashes, $currentInstanceHashes);
  358. $differencesB = array_diff($currentInstanceHashes, $expectedHashes);
  359. $differences = array_unique(array_merge($differencesA, $differencesB));
  360. $differenceArray = [];
  361. foreach($differences as $filename => $hash) {
  362. // Check if file should not exist in the new signature table
  363. if(!array_key_exists($filename, $expectedHashes)) {
  364. $differenceArray['EXTRA_FILE'][$filename]['expected'] = '';
  365. $differenceArray['EXTRA_FILE'][$filename]['current'] = $hash;
  366. continue;
  367. }
  368. // Check if file is missing
  369. if(!array_key_exists($filename, $currentInstanceHashes)) {
  370. $differenceArray['FILE_MISSING'][$filename]['expected'] = $expectedHashes[$filename];
  371. $differenceArray['FILE_MISSING'][$filename]['current'] = '';
  372. continue;
  373. }
  374. // Check if hash does mismatch
  375. if($expectedHashes[$filename] !== $currentInstanceHashes[$filename]) {
  376. $differenceArray['INVALID_HASH'][$filename]['expected'] = $expectedHashes[$filename];
  377. $differenceArray['INVALID_HASH'][$filename]['current'] = $currentInstanceHashes[$filename];
  378. continue;
  379. }
  380. // Should never happen.
  381. throw new \Exception('Invalid behaviour in file hash comparison experienced. Please report this error to the developers.');
  382. }
  383. return $differenceArray;
  384. }
  385. /**
  386. * Whether the code integrity check has passed successful or not
  387. *
  388. * @return bool
  389. */
  390. public function hasPassedCheck(): bool {
  391. $results = $this->getResults();
  392. if(empty($results)) {
  393. return true;
  394. }
  395. return false;
  396. }
  397. /**
  398. * @return array
  399. */
  400. public function getResults(): array {
  401. $cachedResults = $this->cache->get(self::CACHE_KEY);
  402. if(!\is_null($cachedResults)) {
  403. return json_decode($cachedResults, true);
  404. }
  405. if ($this->config !== null) {
  406. return json_decode($this->config->getAppValue('core', self::CACHE_KEY, '{}'), true);
  407. }
  408. return [];
  409. }
  410. /**
  411. * Stores the results in the app config as well as cache
  412. *
  413. * @param string $scope
  414. * @param array $result
  415. */
  416. private function storeResults(string $scope, array $result) {
  417. $resultArray = $this->getResults();
  418. unset($resultArray[$scope]);
  419. if(!empty($result)) {
  420. $resultArray[$scope] = $result;
  421. }
  422. if ($this->config !== null) {
  423. $this->config->setAppValue('core', self::CACHE_KEY, json_encode($resultArray));
  424. }
  425. $this->cache->set(self::CACHE_KEY, json_encode($resultArray));
  426. }
  427. /**
  428. *
  429. * Clean previous results for a proper rescanning. Otherwise
  430. */
  431. private function cleanResults() {
  432. $this->config->deleteAppValue('core', self::CACHE_KEY);
  433. $this->cache->remove(self::CACHE_KEY);
  434. }
  435. /**
  436. * Verify the signature of $appId. Returns an array with the following content:
  437. * [
  438. * 'FILE_MISSING' =>
  439. * [
  440. * 'filename' => [
  441. * 'expected' => 'expectedSHA512',
  442. * 'current' => 'currentSHA512',
  443. * ],
  444. * ],
  445. * 'EXTRA_FILE' =>
  446. * [
  447. * 'filename' => [
  448. * 'expected' => 'expectedSHA512',
  449. * 'current' => 'currentSHA512',
  450. * ],
  451. * ],
  452. * 'INVALID_HASH' =>
  453. * [
  454. * 'filename' => [
  455. * 'expected' => 'expectedSHA512',
  456. * 'current' => 'currentSHA512',
  457. * ],
  458. * ],
  459. * ]
  460. *
  461. * Array may be empty in case no problems have been found.
  462. *
  463. * @param string $appId
  464. * @param string $path Optional path. If none is given it will be guessed.
  465. * @return array
  466. */
  467. public function verifyAppSignature(string $appId, string $path = ''): array {
  468. try {
  469. if($path === '') {
  470. $path = $this->appLocator->getAppPath($appId);
  471. }
  472. $result = $this->verify(
  473. $path . '/appinfo/signature.json',
  474. $path,
  475. $appId
  476. );
  477. } catch (\Exception $e) {
  478. $result = [
  479. 'EXCEPTION' => [
  480. 'class' => \get_class($e),
  481. 'message' => $e->getMessage(),
  482. ],
  483. ];
  484. }
  485. $this->storeResults($appId, $result);
  486. return $result;
  487. }
  488. /**
  489. * Verify the signature of core. Returns an array with the following content:
  490. * [
  491. * 'FILE_MISSING' =>
  492. * [
  493. * 'filename' => [
  494. * 'expected' => 'expectedSHA512',
  495. * 'current' => 'currentSHA512',
  496. * ],
  497. * ],
  498. * 'EXTRA_FILE' =>
  499. * [
  500. * 'filename' => [
  501. * 'expected' => 'expectedSHA512',
  502. * 'current' => 'currentSHA512',
  503. * ],
  504. * ],
  505. * 'INVALID_HASH' =>
  506. * [
  507. * 'filename' => [
  508. * 'expected' => 'expectedSHA512',
  509. * 'current' => 'currentSHA512',
  510. * ],
  511. * ],
  512. * ]
  513. *
  514. * Array may be empty in case no problems have been found.
  515. *
  516. * @return array
  517. */
  518. public function verifyCoreSignature(): array {
  519. try {
  520. $result = $this->verify(
  521. $this->environmentHelper->getServerRoot() . '/core/signature.json',
  522. $this->environmentHelper->getServerRoot(),
  523. 'core'
  524. );
  525. } catch (\Exception $e) {
  526. $result = [
  527. 'EXCEPTION' => [
  528. 'class' => \get_class($e),
  529. 'message' => $e->getMessage(),
  530. ],
  531. ];
  532. }
  533. $this->storeResults('core', $result);
  534. return $result;
  535. }
  536. /**
  537. * Verify the core code of the instance as well as all applicable applications
  538. * and store the results.
  539. */
  540. public function runInstanceVerification() {
  541. $this->cleanResults();
  542. $this->verifyCoreSignature();
  543. $appIds = $this->appLocator->getAllApps();
  544. foreach($appIds as $appId) {
  545. // If an application is shipped a valid signature is required
  546. $isShipped = $this->appManager->isShipped($appId);
  547. $appNeedsToBeChecked = false;
  548. if ($isShipped) {
  549. $appNeedsToBeChecked = true;
  550. } elseif ($this->fileAccessHelper->file_exists($this->appLocator->getAppPath($appId) . '/appinfo/signature.json')) {
  551. // Otherwise only if the application explicitly ships a signature.json file
  552. $appNeedsToBeChecked = true;
  553. }
  554. if($appNeedsToBeChecked) {
  555. $this->verifyAppSignature($appId);
  556. }
  557. }
  558. }
  559. }