nextcloud/lib/private/TemplateLayout.php

384 lines
12 KiB
PHP
Raw Normal View History

<?php
2015-03-26 13:44:34 +03:00
/**
2016-07-21 18:07:57 +03:00
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
2015-03-26 13:44:34 +03:00
* @author Bart Visscher <bartv@thisnet.nl>
* @author Christopher Schäpers <kondou@ts.unde.re>
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
2015-03-26 13:44:34 +03:00
* @author Clark Tomlinson <fallen013@gmail.com>
* @author Daniel Calviño Sánchez <danxuliu@gmail.com>
* @author Guillaume COMPAGNON <gcompagnon@outlook.com>
2016-05-26 20:56:05 +03:00
* @author Hendrik Leppelsack <hendrik@leppelsack.de>
2016-07-21 18:07:57 +03:00
* @author Joas Schilling <coding@schilljs.com>
* @author John Molakvoæ (skjnldsv) <skjnldsv@protonmail.com>
* @author Jörn Friedrich Dreyer <jfd@butonic.de>
* @author Julius Haertl <jus@bitgrid.net>
* @author Julius Härtl <jus@bitgrid.net>
2016-05-26 20:56:05 +03:00
* @author Lukas Reschke <lukas@statuscode.ch>
2015-03-26 13:44:34 +03:00
* @author Michael Gapczynski <GapczynskiM@gmail.com>
2015-06-25 12:43:55 +03:00
* @author Morris Jobke <hey@morrisjobke.de>
* @author Nils <git@to.nilsschnabel.de>
2015-03-26 13:44:34 +03:00
* @author Remco Brenninkmeijer <requist1@starmail.nl>
2016-07-21 19:13:36 +03:00
* @author Robin Appelman <robin@icewind.nl>
2016-01-12 17:02:16 +03:00
* @author Robin McCorkell <robin@mccorkell.me.uk>
2016-07-21 18:07:57 +03:00
* @author Roeland Jago Douma <roeland@famdouma.nl>
* @author Thomas Citharel <nextcloud@tcit.fr>
2015-03-26 13:44:34 +03:00
* @author Thomas Müller <thomas.mueller@tmit.eu>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
2015-03-26 13:44:34 +03:00
*
*/
2016-01-07 11:31:11 +03:00
namespace OC;
use bantu\IniGetWrapper\IniGetWrapper;
use OC\Search\SearchQuery;
use OC\Template\JSCombiner;
use OC\Template\JSConfigHelper;
use OC\Template\SCSSCacher;
use OCP\AppFramework\Http\TemplateResponse;
use OCP\Defaults;
use OCP\IConfig;
use OCP\IInitialStateService;
use OCP\INavigationManager;
use OCP\Support\Subscription\IRegistry;
use OCP\Util;
2016-01-07 11:31:11 +03:00
class TemplateLayout extends \OC_Template {
private static $versionHash = '';
/** @var IConfig */
private $config;
/** @var IInitialStateService */
private $initialState;
/** @var INavigationManager */
private $navigationManager;
/**
* @param string $renderAs
* @param string $appId application id
*/
public function __construct($renderAs, $appId = '') {
/** @var IConfig */
$this->config = \OC::$server->get(IConfig::class);
/** @var IInitialStateService */
$this->initialState = \OC::$server->get(IInitialStateService::class);
if (\OC_Util::isIe()) {
Util::addStyle('ie');
}
// Decide which page we show
if ($renderAs === TemplateResponse::RENDER_AS_USER) {
/** @var INavigationManager */
$this->navigationManager = \OC::$server->get(INavigationManager::class);
parent::__construct('core', 'layout.user');
if (in_array(\OC_App::getCurrentApp(), ['settings','admin', 'help']) !== false) {
2013-02-28 01:55:39 +04:00
$this->assign('bodyid', 'body-settings');
} else {
2013-02-28 01:55:39 +04:00
$this->assign('bodyid', 'body-user');
}
$this->initialState->provideInitialState('core', 'active-app', $this->navigationManager->getActiveEntry());
$this->initialState->provideInitialState('unified-search', 'limit-default', SearchQuery::LIMIT_DEFAULT);
Util::addScript('dist/unified-search', null, true);
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.
2015-11-03 22:26:06 +03:00
// Add navigation entry
$this->assign('application', '');
$this->assign('appid', $appId);
$navigation = $this->navigationManager->getAll();
$this->assign('navigation', $navigation);
$settingsNavigation = $this->navigationManager->getAll('settings');
$this->assign('settingsnavigation', $settingsNavigation);
foreach ($navigation as $entry) {
if ($entry['active']) {
$this->assign('application', $entry['name']);
break;
}
}
foreach ($settingsNavigation as $entry) {
2015-06-11 18:39:34 +03:00
if ($entry['active']) {
$this->assign('application', $entry['name']);
2015-06-11 18:39:34 +03:00
break;
}
}
2016-01-07 11:31:11 +03:00
$userDisplayName = \OC_User::getDisplayName();
$this->assign('user_displayname', $userDisplayName);
2016-01-07 11:31:11 +03:00
$this->assign('user_uid', \OC_User::getUser());
2016-01-07 11:31:11 +03:00
if (\OC_User::getUser() === false) {
$this->assign('userAvatarSet', false);
} else {
$this->assign('userAvatarSet', true);
$this->assign('userAvatarVersion', $this->config->getUserValue(\OC_User::getUser(), 'avatar', 'version', 0));
}
// check if app menu icons should be inverted
try {
/** @var \OCA\Theming\Util $util */
$util = \OC::$server->query(\OCA\Theming\Util::class);
$this->assign('themingInvertMenu', $util->invertTextColor(\OC::$server->getThemingDefaults()->getColorPrimary()));
} catch (\OCP\AppFramework\QueryException $e) {
$this->assign('themingInvertMenu', false);
} catch (\OCP\AutoloadNotAllowedException $e) {
$this->assign('themingInvertMenu', false);
}
} elseif ($renderAs === TemplateResponse::RENDER_AS_ERROR) {
parent::__construct('core', 'layout.guest', '', false);
$this->assign('bodyid', 'body-login');
$this->assign('user_displayname', '');
$this->assign('user_uid', '');
} elseif ($renderAs === TemplateResponse::RENDER_AS_GUEST) {
parent::__construct('core', 'layout.guest');
\OC_Util::addStyle('guest');
$this->assign('bodyid', 'body-login');
$userDisplayName = \OC_User::getDisplayName();
$this->assign('user_displayname', $userDisplayName);
$this->assign('user_uid', \OC_User::getUser());
} elseif ($renderAs === TemplateResponse::RENDER_AS_PUBLIC) {
parent::__construct('core', 'layout.public');
$this->assign('appid', $appId);
$this->assign('bodyid', 'body-public');
/** @var IRegistry $subscription */
$subscription = \OC::$server->query(IRegistry::class);
$showSimpleSignup = $this->config->getSystemValueBool('simpleSignUpLink.shown', true);
if ($showSimpleSignup && $subscription->delegateHasValidSubscription()) {
$showSimpleSignup = false;
}
$this->assign('showSimpleSignUpLink', $showSimpleSignup);
} else {
parent::__construct('core', 'layout.base');
}
// Send the language and the locale to our layouts
$lang = \OC::$server->getL10NFactory()->findLanguage();
$locale = \OC::$server->getL10NFactory()->findLocale($lang);
$lang = str_replace('_', '-', $lang);
$this->assign('language', $lang);
$this->assign('locale', $locale);
if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
2016-01-26 11:05:10 +03:00
if (empty(self::$versionHash)) {
$v = \OC_App::getAppVersions();
$v['core'] = implode('.', \OCP\Util::getVersion());
self::$versionHash = substr(md5(implode(',', $v)), 0, 8);
2016-01-26 11:05:10 +03:00
}
} else {
self::$versionHash = md5('not installed');
}
// Add the js files
$jsFiles = self::findJavascriptFiles(\OC_Util::$scripts);
$this->assign('jsfiles', []);
if ($this->config->getSystemValue('installed', false) && $renderAs != TemplateResponse::RENDER_AS_ERROR) {
// this is on purpose outside of the if statement below so that the initial state is prefilled (done in the getConfig() call)
// see https://github.com/nextcloud/server/pull/22636 for details
$jsConfigHelper = new JSConfigHelper(
\OC::$server->getL10N('lib'),
\OC::$server->query(Defaults::class),
\OC::$server->getAppManager(),
\OC::$server->getSession(),
\OC::$server->getUserSession()->getUser(),
$this->config,
\OC::$server->getGroupManager(),
\OC::$server->get(IniGetWrapper::class),
\OC::$server->getURLGenerator(),
\OC::$server->getCapabilitiesManager(),
\OC::$server->query(IInitialStateService::class)
);
$config = $jsConfigHelper->getConfig();
if (\OC::$server->getContentSecurityPolicyNonceManager()->browserSupportsCspV3()) {
$this->assign('inline_ocjs', $config);
} else {
$this->append('jsfiles', \OC::$server->getURLGenerator()->linkToRoute('core.OCJS.getConfig', ['v' => self::$versionHash]));
}
}
foreach ($jsFiles as $info) {
$web = $info[1];
$file = $info[2];
$this->append('jsfiles', $web.'/'.$file . $this->getVersionHashSuffix());
}
try {
$pathInfo = \OC::$server->getRequest()->getPathInfo();
} catch (\Exception $e) {
$pathInfo = '';
}
// Do not initialise scss appdata until we have a fully installed instance
// Do not load scss for update, errors, installation or login page
if (\OC::$server->getSystemConfig()->getValue('installed', false)
&& !\OCP\Util::needUpgrade()
&& $pathInfo !== ''
&& !preg_match('/^\/login/', $pathInfo)
&& $renderAs !== TemplateResponse::RENDER_AS_ERROR
) {
$cssFiles = self::findStylesheetFiles(\OC_Util::$styles);
} else {
// If we ignore the scss compiler,
// we need to load the guest css fallback
\OC_Util::addStyle('guest');
$cssFiles = self::findStylesheetFiles(\OC_Util::$styles, false);
}
$this->assign('cssfiles', []);
$this->assign('printcssfiles', []);
2016-08-18 13:34:55 +03:00
$this->assign('versionHash', self::$versionHash);
foreach ($cssFiles as $info) {
$web = $info[1];
$file = $info[2];
2015-06-10 13:16:45 +03:00
if (substr($file, -strlen('print.css')) === 'print.css') {
$this->append('printcssfiles', $web.'/'.$file . $this->getVersionHashSuffix());
} else {
$suffix = $this->getVersionHashSuffix($web, $file);
if (strpos($file, '?v=') == false) {
$this->append('cssfiles', $web.'/'.$file . $suffix);
} else {
$this->append('cssfiles', $web.'/'.$file . '-' . substr($suffix, 3));
}
}
}
$this->assign('initialStates', $this->initialState->getInitialStates());
}
/**
* @param string $path
* @param string $file
* @return string
*/
protected function getVersionHashSuffix($path = false, $file = false) {
if ($this->config->getSystemValue('debug', false)) {
// allows chrome workspace mapping in debug mode
return "";
}
$themingSuffix = '';
$v = [];
if ($this->config->getSystemValue('installed', false)) {
if (\OC::$server->getAppManager()->isInstalled('theming')) {
$themingSuffix = '-' . $this->config->getAppValue('theming', 'cachebuster', '0');
}
$v = \OC_App::getAppVersions();
}
// Try the webroot path for a match
if ($path !== false && $path !== '') {
$appName = $this->getAppNamefromPath($path);
if (array_key_exists($appName, $v)) {
$appVersion = $v[$appName];
return '?v=' . substr(md5($appVersion), 0, 8) . $themingSuffix;
}
}
// fallback to the file path instead
if ($file !== false && $file !== '') {
$appName = $this->getAppNamefromPath($file);
if (array_key_exists($appName, $v)) {
$appVersion = $v[$appName];
return '?v=' . substr(md5($appVersion), 0, 8) . $themingSuffix;
}
}
return '?v=' . self::$versionHash . $themingSuffix;
}
2014-04-21 17:44:54 +04:00
/**
* @param array $styles
2014-04-21 17:44:54 +04:00
* @return array
*/
public static function findStylesheetFiles($styles, $compileScss = true) {
// Read the selected theme from the config file
2016-01-07 11:31:11 +03:00
$theme = \OC_Util::getTheme();
if ($compileScss) {
$SCSSCacher = \OC::$server->query(SCSSCacher::class);
} else {
$SCSSCacher = null;
}
$locator = new \OC\Template\CSSResourceLocator(
2016-01-07 11:31:11 +03:00
\OC::$server->getLogger(),
$theme,
[ \OC::$SERVERROOT => \OC::$WEBROOT ],
[ \OC::$SERVERROOT => \OC::$WEBROOT ],
$SCSSCacher
);
$locator->find($styles);
return $locator->getResources();
}
/**
* @param string $path
* @return string|boolean
*/
public function getAppNamefromPath($path) {
if ($path !== '' && is_string($path)) {
$pathParts = explode('/', $path);
if ($pathParts[0] === 'css') {
// This is a scss request
return $pathParts[1];
}
return end($pathParts);
}
return false;
}
2014-04-21 17:44:54 +04:00
/**
* @param array $scripts
2014-04-21 17:44:54 +04:00
* @return array
*/
public static function findJavascriptFiles($scripts) {
// Read the selected theme from the config file
2016-01-07 11:31:11 +03:00
$theme = \OC_Util::getTheme();
$locator = new \OC\Template\JSResourceLocator(
2016-01-07 11:31:11 +03:00
\OC::$server->getLogger(),
$theme,
[ \OC::$SERVERROOT => \OC::$WEBROOT ],
[ \OC::$SERVERROOT => \OC::$WEBROOT ],
\OC::$server->query(JSCombiner::class)
);
$locator->find($scripts);
return $locator->getResources();
}
/**
* Converts the absolute file path to a relative path from \OC::$SERVERROOT
* @param string $filePath Absolute path
* @return string Relative path
2016-01-07 11:31:11 +03:00
* @throws \Exception If $filePath is not under \OC::$SERVERROOT
*/
public static function convertToRelativePath($filePath) {
$relativePath = explode(\OC::$SERVERROOT, $filePath);
if (count($relativePath) !== 2) {
throw new \Exception('$filePath is not under the \OC::$SERVERROOT');
}
return $relativePath[1];
}
}