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.

411 lines
14 KiB

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.
10 years ago
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. namespace OC;
  8. use bantu\IniGetWrapper\IniGetWrapper;
  9. use OC\AppFramework\Http\Request;
  10. use OC\Authentication\Token\IProvider;
  11. use OC\Files\FilenameValidator;
  12. use OC\Search\SearchQuery;
  13. use OC\Template\CSSResourceLocator;
  14. use OC\Template\JSConfigHelper;
  15. use OC\Template\JSResourceLocator;
  16. use OCP\App\IAppManager;
  17. use OCP\AppFramework\Http\TemplateResponse;
  18. use OCP\Defaults;
  19. use OCP\IConfig;
  20. use OCP\IInitialStateService;
  21. use OCP\INavigationManager;
  22. use OCP\IRequest;
  23. use OCP\IURLGenerator;
  24. use OCP\IUserSession;
  25. use OCP\L10N\IFactory;
  26. use OCP\Support\Subscription\IRegistry;
  27. use OCP\Util;
  28. class TemplateLayout extends \OC_Template {
  29. private static $versionHash = '';
  30. /** @var string[] */
  31. private static $cacheBusterCache = [];
  32. /** @var CSSResourceLocator|null */
  33. public static $cssLocator = null;
  34. /** @var JSResourceLocator|null */
  35. public static $jsLocator = null;
  36. private IConfig $config;
  37. private IAppManager $appManager;
  38. private InitialStateService $initialState;
  39. private INavigationManager $navigationManager;
  40. /**
  41. * @param string $renderAs
  42. * @param string $appId application id
  43. */
  44. public function __construct($renderAs, $appId = '') {
  45. $this->config = \OCP\Server::get(IConfig::class);
  46. $this->appManager = \OCP\Server::get(IAppManager::class);
  47. $this->initialState = \OCP\Server::get(InitialStateService::class);
  48. $this->navigationManager = \OCP\Server::get(INavigationManager::class);
  49. // Add fallback theming variables if not rendered as user
  50. if ($renderAs !== TemplateResponse::RENDER_AS_USER) {
  51. // TODO cache generated default theme if enabled for fallback if server is erroring ?
  52. Util::addStyle('theming', 'default');
  53. }
  54. // Decide which page we show
  55. if ($renderAs === TemplateResponse::RENDER_AS_USER) {
  56. parent::__construct('core', 'layout.user');
  57. if (in_array(\OC_App::getCurrentApp(), ['settings','admin', 'help']) !== false) {
  58. $this->assign('bodyid', 'body-settings');
  59. } else {
  60. $this->assign('bodyid', 'body-user');
  61. }
  62. $this->initialState->provideInitialState('core', 'active-app', $this->navigationManager->getActiveEntry());
  63. $this->initialState->provideInitialState('core', 'apps', array_values($this->navigationManager->getAll()));
  64. if ($this->config->getSystemValueBool('unified_search.enabled', false) || !$this->config->getSystemValueBool('enable_non-accessible_features', true)) {
  65. $this->initialState->provideInitialState('unified-search', 'limit-default', (int)$this->config->getAppValue('core', 'unified-search.limit-default', (string)SearchQuery::LIMIT_DEFAULT));
  66. $this->initialState->provideInitialState('unified-search', 'min-search-length', (int)$this->config->getAppValue('core', 'unified-search.min-search-length', (string)1));
  67. $this->initialState->provideInitialState('unified-search', 'live-search', $this->config->getAppValue('core', 'unified-search.live-search', 'yes') === 'yes');
  68. Util::addScript('core', 'legacy-unified-search', 'core');
  69. } else {
  70. Util::addScript('core', 'unified-search', 'core');
  71. }
  72. // Set body data-theme
  73. $this->assign('enabledThemes', []);
  74. if ($this->appManager->isEnabledForUser('theming') && class_exists('\OCA\Theming\Service\ThemesService')) {
  75. /** @var \OCA\Theming\Service\ThemesService */
  76. $themesService = \OC::$server->get(\OCA\Theming\Service\ThemesService::class);
  77. $this->assign('enabledThemes', $themesService->getEnabledThemes());
  78. }
  79. // Set logo link target
  80. $logoUrl = $this->config->getSystemValueString('logo_url', '');
  81. $this->assign('logoUrl', $logoUrl);
  82. // Set default app name
  83. $defaultApp = $this->appManager->getDefaultAppForUser();
  84. $defaultAppInfo = $this->appManager->getAppInfo($defaultApp);
  85. $l10n = \OC::$server->get(IFactory::class)->get($defaultApp);
  86. $this->assign('defaultAppName', $l10n->t($defaultAppInfo['name']));
  87. // Add navigation entry
  88. $this->assign('application', '');
  89. $this->assign('appid', $appId);
  90. $navigation = $this->navigationManager->getAll();
  91. $this->assign('navigation', $navigation);
  92. $settingsNavigation = $this->navigationManager->getAll('settings');
  93. $this->initialState->provideInitialState('core', 'settingsNavEntries', $settingsNavigation);
  94. foreach ($navigation as $entry) {
  95. if ($entry['active']) {
  96. $this->assign('application', $entry['name']);
  97. break;
  98. }
  99. }
  100. foreach ($settingsNavigation as $entry) {
  101. if ($entry['active']) {
  102. $this->assign('application', $entry['name']);
  103. break;
  104. }
  105. }
  106. $userDisplayName = false;
  107. $user = \OC::$server->get(IUserSession::class)->getUser();
  108. if ($user) {
  109. $userDisplayName = $user->getDisplayName();
  110. }
  111. $this->assign('user_displayname', $userDisplayName);
  112. $this->assign('user_uid', \OC_User::getUser());
  113. if ($user === null) {
  114. $this->assign('userAvatarSet', false);
  115. $this->assign('userStatus', false);
  116. } else {
  117. $this->assign('userAvatarSet', true);
  118. $this->assign('userAvatarVersion', $this->config->getUserValue(\OC_User::getUser(), 'avatar', 'version', 0));
  119. }
  120. } elseif ($renderAs === TemplateResponse::RENDER_AS_ERROR) {
  121. parent::__construct('core', 'layout.guest', '', false);
  122. $this->assign('bodyid', 'body-login');
  123. $this->assign('user_displayname', '');
  124. $this->assign('user_uid', '');
  125. } elseif ($renderAs === TemplateResponse::RENDER_AS_GUEST) {
  126. parent::__construct('core', 'layout.guest');
  127. \OC_Util::addStyle('guest');
  128. $this->assign('bodyid', 'body-login');
  129. $userDisplayName = false;
  130. $user = \OC::$server->get(IUserSession::class)->getUser();
  131. if ($user) {
  132. $userDisplayName = $user->getDisplayName();
  133. }
  134. $this->assign('user_displayname', $userDisplayName);
  135. $this->assign('user_uid', \OC_User::getUser());
  136. } elseif ($renderAs === TemplateResponse::RENDER_AS_PUBLIC) {
  137. parent::__construct('core', 'layout.public');
  138. $this->assign('appid', $appId);
  139. $this->assign('bodyid', 'body-public');
  140. // Set body data-theme
  141. $this->assign('enabledThemes', []);
  142. if ($this->appManager->isEnabledForUser('theming') && class_exists('\OCA\Theming\Service\ThemesService')) {
  143. /** @var \OCA\Theming\Service\ThemesService $themesService */
  144. $themesService = \OC::$server->get(\OCA\Theming\Service\ThemesService::class);
  145. $this->assign('enabledThemes', $themesService->getEnabledThemes());
  146. }
  147. // Set logo link target
  148. $logoUrl = $this->config->getSystemValueString('logo_url', '');
  149. $this->assign('logoUrl', $logoUrl);
  150. /** @var IRegistry $subscription */
  151. $subscription = \OCP\Server::get(IRegistry::class);
  152. $showSimpleSignup = $this->config->getSystemValueBool('simpleSignUpLink.shown', true);
  153. if ($showSimpleSignup && $subscription->delegateHasValidSubscription()) {
  154. $showSimpleSignup = false;
  155. }
  156. $defaultSignUpLink = 'https://nextcloud.com/signup/';
  157. $signUpLink = $this->config->getSystemValueString('registration_link', $defaultSignUpLink);
  158. if ($signUpLink !== $defaultSignUpLink) {
  159. $showSimpleSignup = true;
  160. }
  161. if ($this->appManager->isEnabledForUser('registration')) {
  162. $urlGenerator = \OCP\Server::get(IURLGenerator::class);
  163. $signUpLink = $urlGenerator->getAbsoluteURL('/index.php/apps/registration/');
  164. }
  165. $this->assign('showSimpleSignUpLink', $showSimpleSignup);
  166. $this->assign('signUpLink', $signUpLink);
  167. } else {
  168. parent::__construct('core', 'layout.base');
  169. }
  170. // Send the language and the locale to our layouts
  171. $lang = \OC::$server->get(IFactory::class)->findLanguage();
  172. $locale = \OC::$server->get(IFactory::class)->findLocale($lang);
  173. $lang = str_replace('_', '-', $lang);
  174. $this->assign('language', $lang);
  175. $this->assign('locale', $locale);
  176. if ($this->config->getSystemValueBool('installed', false)) {
  177. if (empty(self::$versionHash)) {
  178. $v = \OC_App::getAppVersions();
  179. $v['core'] = implode('.', \OCP\Util::getVersion());
  180. self::$versionHash = substr(md5(implode(',', $v)), 0, 8);
  181. }
  182. } else {
  183. self::$versionHash = md5('not installed');
  184. }
  185. // Add the js files
  186. // TODO: remove deprecated OC_Util injection
  187. $jsFiles = self::findJavascriptFiles(array_merge(\OC_Util::$scripts, Util::getScripts()));
  188. $this->assign('jsfiles', []);
  189. if ($this->config->getSystemValueBool('installed', false) && $renderAs != TemplateResponse::RENDER_AS_ERROR) {
  190. // this is on purpose outside of the if statement below so that the initial state is prefilled (done in the getConfig() call)
  191. // see https://github.com/nextcloud/server/pull/22636 for details
  192. $jsConfigHelper = new JSConfigHelper(
  193. \OCP\Util::getL10N('lib'),
  194. \OCP\Server::get(Defaults::class),
  195. $this->appManager,
  196. \OC::$server->getSession(),
  197. \OC::$server->getUserSession()->getUser(),
  198. $this->config,
  199. \OC::$server->getGroupManager(),
  200. \OC::$server->get(IniGetWrapper::class),
  201. \OC::$server->getURLGenerator(),
  202. \OC::$server->get(CapabilitiesManager::class),
  203. \OCP\Server::get(IInitialStateService::class),
  204. \OCP\Server::get(IProvider::class),
  205. \OCP\Server::get(FilenameValidator::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. && $pathInfo !== false
  230. && !preg_match('/^\/login/', $pathInfo)
  231. && $renderAs !== TemplateResponse::RENDER_AS_ERROR
  232. ) {
  233. $cssFiles = self::findStylesheetFiles(\OC_Util::$styles);
  234. } else {
  235. // If we ignore the scss compiler,
  236. // we need to load the guest css fallback
  237. \OC_Util::addStyle('guest');
  238. $cssFiles = self::findStylesheetFiles(\OC_Util::$styles);
  239. }
  240. $this->assign('cssfiles', []);
  241. $this->assign('printcssfiles', []);
  242. $this->initialState->provideInitialState('core', 'versionHash', self::$versionHash);
  243. foreach ($cssFiles as $info) {
  244. $web = $info[1];
  245. $file = $info[2];
  246. if (str_ends_with($file, 'print.css')) {
  247. $this->append('printcssfiles', $web.'/'.$file . $this->getVersionHashSuffix());
  248. } else {
  249. $suffix = $this->getVersionHashSuffix($web, $file);
  250. if (!str_contains($file, '?v=')) {
  251. $this->append('cssfiles', $web.'/'.$file . $suffix);
  252. } else {
  253. $this->append('cssfiles', $web.'/'.$file . '-' . substr($suffix, 3));
  254. }
  255. }
  256. }
  257. $request = \OCP\Server::get(IRequest::class);
  258. if ($request->isUserAgent([Request::USER_AGENT_CLIENT_IOS, Request::USER_AGENT_SAFARI, Request::USER_AGENT_SAFARI_MOBILE])) {
  259. // Prevent auto zoom with iOS but still allow user zoom
  260. // On chrome (and others) this does not work (will also disable user zoom)
  261. $this->assign('viewport_maximum_scale', '1.0');
  262. }
  263. $this->assign('initialStates', $this->initialState->getInitialStates());
  264. $this->assign('id-app-content', $renderAs === TemplateResponse::RENDER_AS_USER ? '#app-content' : '#content');
  265. $this->assign('id-app-navigation', $renderAs === TemplateResponse::RENDER_AS_USER ? '#app-navigation' : null);
  266. }
  267. protected function getVersionHashSuffix(string $path = '', string $file = ''): string {
  268. if ($this->config->getSystemValueBool('debug', false)) {
  269. // allows chrome workspace mapping in debug mode
  270. return "";
  271. }
  272. if ($this->config->getSystemValueBool('installed', false) === false) {
  273. // if not installed just return the version hash
  274. return '?v=' . self::$versionHash;
  275. }
  276. $hash = false;
  277. // Try the web-root first
  278. if ($path !== '') {
  279. $hash = $this->getVersionHashByPath($path);
  280. }
  281. // If not found try the file
  282. if ($hash === false && $file !== '') {
  283. $hash = $this->getVersionHashByPath($file);
  284. }
  285. // As a last resort we use the server version hash
  286. if ($hash === false) {
  287. $hash = self::$versionHash;
  288. }
  289. // The theming app is force-enabled thus the cache buster is always available
  290. $themingSuffix = '-' . $this->config->getAppValue('theming', 'cachebuster', '0');
  291. return '?v=' . $hash . $themingSuffix;
  292. }
  293. private function getVersionHashByPath(string $path): string|false {
  294. if (array_key_exists($path, self::$cacheBusterCache) === false) {
  295. // Not yet cached, so lets find the cache buster string
  296. $appId = $this->getAppNamefromPath($path);
  297. if ($appId === false) {
  298. // No app Id could be guessed
  299. return false;
  300. }
  301. $appVersion = $this->appManager->getAppVersion($appId);
  302. // For shipped apps the app version is not a single source of truth, we rather also need to consider the Nextcloud version
  303. if ($this->appManager->isShipped($appId)) {
  304. $appVersion .= '-' . self::$versionHash;
  305. }
  306. $hash = substr(md5($appVersion), 0, 8);
  307. self::$cacheBusterCache[$path] = $hash;
  308. }
  309. return self::$cacheBusterCache[$path];
  310. }
  311. /**
  312. * @param array $styles
  313. * @return array
  314. */
  315. public static function findStylesheetFiles($styles) {
  316. if (!self::$cssLocator) {
  317. self::$cssLocator = \OCP\Server::get(CSSResourceLocator::class);
  318. }
  319. self::$cssLocator->find($styles);
  320. return self::$cssLocator->getResources();
  321. }
  322. /**
  323. * @return string|false
  324. */
  325. public function getAppNamefromPath(string $path) {
  326. if ($path !== '') {
  327. $pathParts = explode('/', $path);
  328. if ($pathParts[0] === 'css') {
  329. // This is a scss request
  330. return $pathParts[1];
  331. }
  332. return end($pathParts);
  333. }
  334. return false;
  335. }
  336. /**
  337. * @param array $scripts
  338. * @return array
  339. */
  340. public static function findJavascriptFiles($scripts) {
  341. if (!self::$jsLocator) {
  342. self::$jsLocator = \OCP\Server::get(JSResourceLocator::class);
  343. }
  344. self::$jsLocator->find($scripts);
  345. return self::$jsLocator->getResources();
  346. }
  347. /**
  348. * Converts the absolute file path to a relative path from \OC::$SERVERROOT
  349. * @param string $filePath Absolute path
  350. * @return string Relative path
  351. * @throws \Exception If $filePath is not under \OC::$SERVERROOT
  352. */
  353. public static function convertToRelativePath($filePath) {
  354. $relativePath = explode(\OC::$SERVERROOT, $filePath);
  355. if (count($relativePath) !== 2) {
  356. throw new \Exception('$filePath is not under the \OC::$SERVERROOT');
  357. }
  358. return $relativePath[1];
  359. }
  360. }