checker.php 18 KB

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