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.

TemplateLayout.php 13KB

8 years ago
8 years ago
8 years ago
8 years ago
Add code integrity check This PR implements the base foundation of the code signing and integrity check. In this PR implemented is the signing and verification logic, as well as commands to sign single apps or the core repository. Furthermore, there is a basic implementation to display problems with the code integrity on the update screen. Code signing basically happens the following way: - There is a ownCloud Root Certificate authority stored `resources/codesigning/root.crt` (in this PR I also ship the private key which we obviously need to change before a release :wink:). This certificate is not intended to be used for signing directly and only is used to sign new certificates. - Using the `integrity:sign-core` and `integrity:sign-app` commands developers can sign either the core release or a single app. The core release needs to be signed with a certificate that has a CN of `core`, apps need to be signed with a certificate that either has a CN of `core` (shipped apps!) or the AppID. - The command generates a signature.json file of the following format: ```json { "hashes": { "/filename.php": "2401fed2eea6f2c1027c482a633e8e25cd46701f811e2d2c10dc213fd95fa60e350bccbbebdccc73a042b1a2799f673fbabadc783284cc288e4f1a1eacb74e3d", "/lib/base.php": "55548cc16b457cd74241990cc9d3b72b6335f2e5f45eee95171da024087d114fcbc2effc3d5818a6d5d55f2ae960ab39fd0414d0c542b72a3b9e08eb21206dd9" }, "certificate": "-----BEGIN CERTIFICATE-----MIIBvTCCASagAwIBAgIUPvawyqJwCwYazcv7iz16TWxfeUMwDQYJKoZIhvcNAQEF\nBQAwIzEhMB8GA1UECgwYb3duQ2xvdWQgQ29kZSBTaWduaW5nIENBMB4XDTE1MTAx\nNDEzMTcxMFoXDTE2MTAxNDEzMTcxMFowEzERMA8GA1UEAwwIY29udGFjdHMwgZ8w\nDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBANoQesGdCW0L2L+a2xITYipixkScrIpB\nkX5Snu3fs45MscDb61xByjBSlFgR4QI6McoCipPw4SUr28EaExVvgPSvqUjYLGps\nfiv0Cvgquzbx/X3mUcdk9LcFo1uWGtrTfkuXSKX41PnJGTr6RQWGIBd1V52q1qbC\nJKkfzyeMeuQfAgMBAAEwDQYJKoZIhvcNAQEFBQADgYEAvF/KIhRMQ3tYTmgHWsiM\nwDMgIDb7iaHF0fS+/Nvo4PzoTO/trev6tMyjLbJ7hgdCpz/1sNzE11Cibf6V6dsz\njCE9invP368Xv0bTRObRqeSNsGogGl5ceAvR0c9BG+NRIKHcly3At3gLkS2791bC\niG+UxI/MNcWV0uJg9S63LF8=\n-----END CERTIFICATE-----", "signature": "U29tZVNpZ25lZERhdGFFeGFtcGxl" } ``` `hashes` is an array of all files in the folder with their corresponding SHA512 hashes (this is actually quite cheap to calculate), the `certificate` is the certificate used for signing. It has to be issued by the ownCloud Root Authority and it's CN needs to be permitted to perform the required action. The `signature` is then a signature of the `hashes` which can be verified using the `certificate`. Steps to do in other PRs, this is already a quite huge one: - Add nag screen in case the code check fails to ensure that administrators are aware of this. - Add code verification also to OCC upgrade and unify display code more. - Add enforced code verification to apps shipped from the appstore with a level of "official" - Add enfocrced code verification to apps shipped from the appstore that were already signed in a previous release - Add some developer documentation on how devs can request their own certificate - Check when installing ownCloud - Add support for CRLs to allow revoking certificates **Note:** The upgrade checks are only run when the instance has a defined release channel of `stable` (defined in `version.php`). If you want to test this, you need to change the channel thus and then generate the core signature: ``` ➜ master git:(add-integrity-checker) ✗ ./occ integrity:sign-core --privateKey=resources/codesigning/core.key --certificate=resources/codesigning/core.crt Successfully signed "core" ``` Then increase the version and you should see something like the following: ![2015-11-04_12-02-57](https://cloud.githubusercontent.com/assets/878997/10936336/6adb1d14-82ec-11e5-8f06-9a74801c9abf.png) As you can see a failed code check will not prevent the further update. It will instead just be a notice to the admin. In a next step we will add some nag screen. For packaging stable releases this requires the following additional steps as a last action before zipping: 1. Run `./occ integrity:sign-core` once 2. Run `./occ integrity:sign-app` _for each_ app. However, this can be simply automated using a simple foreach on the apps folder.
8 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Bart Visscher <bartv@thisnet.nl>
  6. * @author Christopher Schäpers <kondou@ts.unde.re>
  7. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  8. * @author Clark Tomlinson <fallen013@gmail.com>
  9. * @author Daniel Calviño Sánchez <danxuliu@gmail.com>
  10. * @author Guillaume COMPAGNON <gcompagnon@outlook.com>
  11. * @author Hendrik Leppelsack <hendrik@leppelsack.de>
  12. * @author Joas Schilling <coding@schilljs.com>
  13. * @author John Molakvoæ <skjnldsv@protonmail.com>
  14. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  15. * @author Julius Haertl <jus@bitgrid.net>
  16. * @author Julius Härtl <jus@bitgrid.net>
  17. * @author Lukas Reschke <lukas@statuscode.ch>
  18. * @author Michael Gapczynski <GapczynskiM@gmail.com>
  19. * @author Morris Jobke <hey@morrisjobke.de>
  20. * @author Nils <git@to.nilsschnabel.de>
  21. * @author Remco Brenninkmeijer <requist1@starmail.nl>
  22. * @author Robin Appelman <robin@icewind.nl>
  23. * @author Robin McCorkell <robin@mccorkell.me.uk>
  24. * @author Roeland Jago Douma <roeland@famdouma.nl>
  25. * @author Thomas Citharel <nextcloud@tcit.fr>
  26. * @author Thomas Müller <thomas.mueller@tmit.eu>
  27. *
  28. * @license AGPL-3.0
  29. *
  30. * This code is free software: you can redistribute it and/or modify
  31. * it under the terms of the GNU Affero General Public License, version 3,
  32. * as published by the Free Software Foundation.
  33. *
  34. * This program is distributed in the hope that it will be useful,
  35. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  36. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  37. * GNU Affero General Public License for more details.
  38. *
  39. * You should have received a copy of the GNU Affero General Public License, version 3,
  40. * along with this program. If not, see <http://www.gnu.org/licenses/>
  41. *
  42. */
  43. namespace OC;
  44. use bantu\IniGetWrapper\IniGetWrapper;
  45. use OC\Search\SearchQuery;
  46. use OC\Template\JSCombiner;
  47. use OC\Template\JSConfigHelper;
  48. use OC\Template\SCSSCacher;
  49. use OCP\App\IAppManager;
  50. use OCP\AppFramework\Http\TemplateResponse;
  51. use OCP\Defaults;
  52. use OCP\IConfig;
  53. use OCP\IInitialStateService;
  54. use OCP\INavigationManager;
  55. use OCP\IUserSession;
  56. use OCP\Support\Subscription\IRegistry;
  57. use OCP\UserStatus\IManager as IUserStatusManager;
  58. use OCP\Util;
  59. class TemplateLayout extends \OC_Template {
  60. private static $versionHash = '';
  61. /** @var IConfig */
  62. private $config;
  63. /** @var IInitialStateService */
  64. private $initialState;
  65. /** @var INavigationManager */
  66. private $navigationManager;
  67. /**
  68. * @param string $renderAs
  69. * @param string $appId application id
  70. */
  71. public function __construct($renderAs, $appId = '') {
  72. /** @var IConfig */
  73. $this->config = \OC::$server->get(IConfig::class);
  74. /** @var IInitialStateService */
  75. $this->initialState = \OC::$server->get(IInitialStateService::class);
  76. // Decide which page we show
  77. if ($renderAs === TemplateResponse::RENDER_AS_USER) {
  78. /** @var INavigationManager */
  79. $this->navigationManager = \OC::$server->get(INavigationManager::class);
  80. parent::__construct('core', 'layout.user');
  81. if (in_array(\OC_App::getCurrentApp(), ['settings','admin', 'help']) !== false) {
  82. $this->assign('bodyid', 'body-settings');
  83. } else {
  84. $this->assign('bodyid', 'body-user');
  85. }
  86. $this->initialState->provideInitialState('core', 'active-app', $this->navigationManager->getActiveEntry());
  87. $this->initialState->provideInitialState('unified-search', 'limit-default', SearchQuery::LIMIT_DEFAULT);
  88. Util::addScript('core', 'dist/unified-search', 'core');
  89. // Add navigation entry
  90. $this->assign('application', '');
  91. $this->assign('appid', $appId);
  92. $navigation = $this->navigationManager->getAll();
  93. $this->assign('navigation', $navigation);
  94. $settingsNavigation = $this->navigationManager->getAll('settings');
  95. $this->assign('settingsnavigation', $settingsNavigation);
  96. foreach ($navigation as $entry) {
  97. if ($entry['active']) {
  98. $this->assign('application', $entry['name']);
  99. break;
  100. }
  101. }
  102. foreach ($settingsNavigation as $entry) {
  103. if ($entry['active']) {
  104. $this->assign('application', $entry['name']);
  105. break;
  106. }
  107. }
  108. $userDisplayName = false;
  109. $user = \OC::$server->get(IUserSession::class)->getUser();
  110. if ($user) {
  111. $userDisplayName = $user->getDisplayName();
  112. }
  113. $this->assign('user_displayname', $userDisplayName);
  114. $this->assign('user_uid', \OC_User::getUser());
  115. if ($user === null) {
  116. $this->assign('userAvatarSet', false);
  117. $this->assign('userStatus', false);
  118. } else {
  119. $this->assign('userAvatarSet', true);
  120. $this->assign('userAvatarVersion', $this->config->getUserValue(\OC_User::getUser(), 'avatar', 'version', 0));
  121. if (\OC::$server->get(IAppManager::class)->isEnabledForUser('user_status')) {
  122. $userStatusManager = \OC::$server->get(IUserStatusManager::class);
  123. $userStatuses = $userStatusManager->getUserStatuses([$user->getUID()]);
  124. if (array_key_exists($user->getUID(), $userStatuses)) {
  125. $this->assign('userStatus', $userStatuses[$user->getUID()]);
  126. } else {
  127. $this->assign('userStatus', false);
  128. }
  129. } else {
  130. $this->assign('userStatus', false);
  131. }
  132. }
  133. // check if app menu icons should be inverted
  134. try {
  135. /** @var \OCA\Theming\Util $util */
  136. $util = \OC::$server->query(\OCA\Theming\Util::class);
  137. $this->assign('themingInvertMenu', $util->invertTextColor(\OC::$server->getThemingDefaults()->getColorPrimary()));
  138. } catch (\OCP\AppFramework\QueryException $e) {
  139. $this->assign('themingInvertMenu', false);
  140. } catch (\OCP\AutoloadNotAllowedException $e) {
  141. $this->assign('themingInvertMenu', false);
  142. }
  143. } elseif ($renderAs === TemplateResponse::RENDER_AS_ERROR) {
  144. parent::__construct('core', 'layout.guest', '', false);
  145. $this->assign('bodyid', 'body-login');
  146. $this->assign('user_displayname', '');
  147. $this->assign('user_uid', '');
  148. } elseif ($renderAs === TemplateResponse::RENDER_AS_GUEST) {
  149. parent::__construct('core', 'layout.guest');
  150. \OC_Util::addStyle('guest');
  151. $this->assign('bodyid', 'body-login');
  152. $userDisplayName = false;
  153. $user = \OC::$server->get(IUserSession::class)->getUser();
  154. if ($user) {
  155. $userDisplayName = $user->getDisplayName();
  156. }
  157. $this->assign('user_displayname', $userDisplayName);
  158. $this->assign('user_uid', \OC_User::getUser());
  159. } elseif ($renderAs === TemplateResponse::RENDER_AS_PUBLIC) {
  160. parent::__construct('core', 'layout.public');
  161. $this->assign('appid', $appId);
  162. $this->assign('bodyid', 'body-public');
  163. /** @var IRegistry $subscription */
  164. $subscription = \OC::$server->query(IRegistry::class);
  165. $showSimpleSignup = $this->config->getSystemValueBool('simpleSignUpLink.shown', true);
  166. if ($showSimpleSignup && $subscription->delegateHasValidSubscription()) {
  167. $showSimpleSignup = false;
  168. }
  169. $this->assign('showSimpleSignUpLink', $showSimpleSignup);
  170. } else {
  171. parent::__construct('core', 'layout.base');
  172. }
  173. // Send the language and the locale to our layouts
  174. $lang = \OC::$server->getL10NFactory()->findLanguage();
  175. $locale = \OC::$server->getL10NFactory()->findLocale($lang);
  176. $lang = str_replace('_', '-', $lang);
  177. $this->assign('language', $lang);
  178. $this->assign('locale', $locale);
  179. if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
  180. if (empty(self::$versionHash)) {
  181. $v = \OC_App::getAppVersions();
  182. $v['core'] = implode('.', \OCP\Util::getVersion());
  183. self::$versionHash = substr(md5(implode(',', $v)), 0, 8);
  184. }
  185. } else {
  186. self::$versionHash = md5('not installed');
  187. }
  188. // Add the js files
  189. $jsFiles = self::findJavascriptFiles(array_merge(\OC_Util::$scripts, Util::getScripts()));
  190. $this->assign('jsfiles', []);
  191. if ($this->config->getSystemValue('installed', false) && $renderAs != TemplateResponse::RENDER_AS_ERROR) {
  192. // this is on purpose outside of the if statement below so that the initial state is prefilled (done in the getConfig() call)
  193. // see https://github.com/nextcloud/server/pull/22636 for details
  194. $jsConfigHelper = new JSConfigHelper(
  195. \OC::$server->getL10N('lib'),
  196. \OC::$server->query(Defaults::class),
  197. \OC::$server->getAppManager(),
  198. \OC::$server->getSession(),
  199. \OC::$server->getUserSession()->getUser(),
  200. $this->config,
  201. \OC::$server->getGroupManager(),
  202. \OC::$server->get(IniGetWrapper::class),
  203. \OC::$server->getURLGenerator(),
  204. \OC::$server->getCapabilitiesManager(),
  205. \OC::$server->query(IInitialStateService::class)
  206. );
  207. $config = $jsConfigHelper->getConfig();
  208. if (\OC::$server->getContentSecurityPolicyNonceManager()->browserSupportsCspV3()) {
  209. $this->assign('inline_ocjs', $config);
  210. } else {
  211. $this->append('jsfiles', \OC::$server->getURLGenerator()->linkToRoute('core.OCJS.getConfig', ['v' => self::$versionHash]));
  212. }
  213. }
  214. foreach ($jsFiles as $info) {
  215. $web = $info[1];
  216. $file = $info[2];
  217. $this->append('jsfiles', $web.'/'.$file . $this->getVersionHashSuffix());
  218. }
  219. try {
  220. $pathInfo = \OC::$server->getRequest()->getPathInfo();
  221. } catch (\Exception $e) {
  222. $pathInfo = '';
  223. }
  224. // Do not initialise scss appdata until we have a fully installed instance
  225. // Do not load scss for update, errors, installation or login page
  226. if (\OC::$server->getSystemConfig()->getValue('installed', false)
  227. && !\OCP\Util::needUpgrade()
  228. && $pathInfo !== ''
  229. && !preg_match('/^\/login/', $pathInfo)
  230. && $renderAs !== TemplateResponse::RENDER_AS_ERROR
  231. ) {
  232. $cssFiles = self::findStylesheetFiles(\OC_Util::$styles);
  233. } else {
  234. // If we ignore the scss compiler,
  235. // we need to load the guest css fallback
  236. \OC_Util::addStyle('guest');
  237. $cssFiles = self::findStylesheetFiles(\OC_Util::$styles, false);
  238. }
  239. $this->assign('cssfiles', []);
  240. $this->assign('printcssfiles', []);
  241. $this->assign('versionHash', self::$versionHash);
  242. foreach ($cssFiles as $info) {
  243. $web = $info[1];
  244. $file = $info[2];
  245. if (substr($file, -strlen('print.css')) === 'print.css') {
  246. $this->append('printcssfiles', $web.'/'.$file . $this->getVersionHashSuffix());
  247. } else {
  248. $suffix = $this->getVersionHashSuffix($web, $file);
  249. if (strpos($file, '?v=') == false) {
  250. $this->append('cssfiles', $web.'/'.$file . $suffix);
  251. } else {
  252. $this->append('cssfiles', $web.'/'.$file . '-' . substr($suffix, 3));
  253. }
  254. }
  255. }
  256. $this->assign('initialStates', $this->initialState->getInitialStates());
  257. }
  258. /**
  259. * @param string $path
  260. * @param string $file
  261. * @return string
  262. */
  263. protected function getVersionHashSuffix($path = false, $file = false) {
  264. if ($this->config->getSystemValue('debug', false)) {
  265. // allows chrome workspace mapping in debug mode
  266. return "";
  267. }
  268. $themingSuffix = '';
  269. $v = [];
  270. if ($this->config->getSystemValue('installed', false)) {
  271. if (\OC::$server->getAppManager()->isInstalled('theming')) {
  272. $themingSuffix = '-' . $this->config->getAppValue('theming', 'cachebuster', '0');
  273. }
  274. $v = \OC_App::getAppVersions();
  275. }
  276. // Try the webroot path for a match
  277. if ($path !== false && $path !== '') {
  278. $appName = $this->getAppNamefromPath($path);
  279. if (array_key_exists($appName, $v)) {
  280. $appVersion = $v[$appName];
  281. return '?v=' . substr(md5($appVersion), 0, 8) . $themingSuffix;
  282. }
  283. }
  284. // fallback to the file path instead
  285. if ($file !== false && $file !== '') {
  286. $appName = $this->getAppNamefromPath($file);
  287. if (array_key_exists($appName, $v)) {
  288. $appVersion = $v[$appName];
  289. return '?v=' . substr(md5($appVersion), 0, 8) . $themingSuffix;
  290. }
  291. }
  292. return '?v=' . self::$versionHash . $themingSuffix;
  293. }
  294. /**
  295. * @param array $styles
  296. * @return array
  297. */
  298. public static function findStylesheetFiles($styles, $compileScss = true) {
  299. // Read the selected theme from the config file
  300. $theme = \OC_Util::getTheme();
  301. if ($compileScss) {
  302. $SCSSCacher = \OC::$server->query(SCSSCacher::class);
  303. } else {
  304. $SCSSCacher = null;
  305. }
  306. $locator = new \OC\Template\CSSResourceLocator(
  307. \OC::$server->getLogger(),
  308. $theme,
  309. [ \OC::$SERVERROOT => \OC::$WEBROOT ],
  310. [ \OC::$SERVERROOT => \OC::$WEBROOT ],
  311. $SCSSCacher
  312. );
  313. $locator->find($styles);
  314. return $locator->getResources();
  315. }
  316. /**
  317. * @param string $path
  318. * @return string|boolean
  319. */
  320. public function getAppNamefromPath($path) {
  321. if ($path !== '' && is_string($path)) {
  322. $pathParts = explode('/', $path);
  323. if ($pathParts[0] === 'css') {
  324. // This is a scss request
  325. return $pathParts[1];
  326. }
  327. return end($pathParts);
  328. }
  329. return false;
  330. }
  331. /**
  332. * @param array $scripts
  333. * @return array
  334. */
  335. public static function findJavascriptFiles($scripts) {
  336. // Read the selected theme from the config file
  337. $theme = \OC_Util::getTheme();
  338. $locator = new \OC\Template\JSResourceLocator(
  339. \OC::$server->getLogger(),
  340. $theme,
  341. [ \OC::$SERVERROOT => \OC::$WEBROOT ],
  342. [ \OC::$SERVERROOT => \OC::$WEBROOT ],
  343. \OC::$server->query(JSCombiner::class)
  344. );
  345. $locator->find($scripts);
  346. return $locator->getResources();
  347. }
  348. /**
  349. * Converts the absolute file path to a relative path from \OC::$SERVERROOT
  350. * @param string $filePath Absolute path
  351. * @return string Relative path
  352. * @throws \Exception If $filePath is not under \OC::$SERVERROOT
  353. */
  354. public static function convertToRelativePath($filePath) {
  355. $relativePath = explode(\OC::$SERVERROOT, $filePath);
  356. if (count($relativePath) !== 2) {
  357. throw new \Exception('$filePath is not under the \OC::$SERVERROOT');
  358. }
  359. return $relativePath[1];
  360. }
  361. }