diff options
author | Lukas Reschke <lukas@statuscode.ch> | 2016-07-20 17:37:30 +0200 |
---|---|---|
committer | Lukas Reschke <lukas@statuscode.ch> | 2016-07-20 18:37:57 +0200 |
commit | a299fa38a9172f16e4bc48d4bd4f9807cec2f737 (patch) | |
tree | abd17d7cc5eabc8acf7cb5b1acb30a12abe1581e /lib | |
parent | 7cdf6402ff9a0e07866ca8bcfcffd0e0897b646a (diff) | |
download | nextcloud-server-a299fa38a9172f16e4bc48d4bd4f9807cec2f737.tar.gz nextcloud-server-a299fa38a9172f16e4bc48d4bd4f9807cec2f737.zip |
[master] Port Same-Site Cookies to master
Fixes https://github.com/nextcloud/server/issues/50
Diffstat (limited to 'lib')
-rw-r--r-- | lib/base.php | 80 | ||||
-rw-r--r-- | lib/private/AppFramework/Http/Request.php | 40 | ||||
-rw-r--r-- | lib/private/AppFramework/Middleware/Security/Exceptions/StrictCookieMissingException.php | 36 | ||||
-rw-r--r-- | lib/private/AppFramework/Middleware/Security/SecurityMiddleware.php | 11 | ||||
-rw-r--r-- | lib/private/legacy/eventsource.php | 4 | ||||
-rw-r--r-- | lib/private/legacy/json.php | 5 | ||||
-rw-r--r-- | lib/public/IRequest.php | 18 | ||||
-rw-r--r-- | lib/public/Util.php | 5 |
8 files changed, 198 insertions, 1 deletions
diff --git a/lib/base.php b/lib/base.php index be9de93f73f..afa13cd1047 100644 --- a/lib/base.php +++ b/lib/base.php @@ -469,6 +469,84 @@ class OC { @ini_set('gd.jpeg_ignore_warning', 1); } + /** + * Send the same site cookies + */ + private static function sendSameSiteCookies() { + $cookieParams = session_get_cookie_params(); + $secureCookie = ($cookieParams['secure'] === true) ? 'secure; ' : ''; + $policies = [ + 'lax', + 'strict', + ]; + foreach($policies as $policy) { + header( + sprintf( + 'Set-Cookie: nc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s', + $policy, + $cookieParams['path'], + $policy + ), + false + ); + } + } + + /** + * Same Site cookie to further mitigate CSRF attacks. This cookie has to + * be set in every request if cookies are sent to add a second level of + * defense against CSRF. + * + * If the cookie is not sent this will set the cookie and reload the page. + * We use an additional cookie since we want to protect logout CSRF and + * also we can't directly interfere with PHP's session mechanism. + */ + private static function performSameSiteCookieProtection() { + if(count($_COOKIE) > 0) { + $request = \OC::$server->getRequest(); + $requestUri = $request->getScriptName(); + $processingScript = explode('/', $requestUri); + $processingScript = $processingScript[count($processingScript)-1]; + // FIXME: In a SAML scenario we don't get any strict or lax cookie + // send for the ACS endpoint. Since we have some legacy code in Nextcloud + // (direct PHP files) the enforcement of lax cookies is performed here + // instead of the middleware. + // + // This means we cannot exclude some routes from the cookie validation, + // which normally is not a problem but is a little bit cumbersome for + // this use-case. + // Once the old legacy PHP endpoints have been removed we can move + // the verification into a middleware and also adds some exemptions. + // + // Questions about this code? Ask Lukas ;-) + $currentUrl = substr(explode('?',$request->getRequestUri(), 2)[0], strlen(\OC::$WEBROOT)); + if($currentUrl === '/index.php/apps/user_saml/saml/acs') { + return; + } + // For the "index.php" endpoint only a lax cookie is required. + if($processingScript === 'index.php') { + if(!$request->passesLaxCookieCheck()) { + self::sendSameSiteCookies(); + header('Location: '.$_SERVER['REQUEST_URI']); + exit(); + } + } else { + // All other endpoints require the lax and the strict cookie + if(!$request->passesStrictCookieCheck()) { + self::sendSameSiteCookies(); + // Debug mode gets access to the resources without strict cookie + // due to the fact that the SabreDAV browser also lives there. + if(!\OC::$server->getConfig()->getSystemValue('debug', false)) { + http_response_code(\OCP\AppFramework\Http::STATUS_SERVICE_UNAVAILABLE); + exit(); + } + } + } + } elseif(!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) { + self::sendSameSiteCookies(); + } + } + public static function init() { // calculate the root directories OC::$SERVERROOT = str_replace("\\", '/', substr(__DIR__, 0, -4)); @@ -572,6 +650,8 @@ class OC { ini_set('session.cookie_secure', true); } + self::performSameSiteCookieProtection(); + if (!defined('OC_CONSOLE')) { $errors = OC_Util::checkServer(\OC::$server->getConfig()); if (count($errors) > 0) { diff --git a/lib/private/AppFramework/Http/Request.php b/lib/private/AppFramework/Http/Request.php index d9cf1919252..8fc99f125b2 100644 --- a/lib/private/AppFramework/Http/Request.php +++ b/lib/private/AppFramework/Http/Request.php @@ -465,6 +465,10 @@ class Request implements \ArrayAccess, \Countable, IRequest { return false; } + if(!$this->passesStrictCookieCheck()) { + return false; + } + if (isset($this->items['get']['requesttoken'])) { $token = $this->items['get']['requesttoken']; } elseif (isset($this->items['post']['requesttoken'])) { @@ -481,6 +485,42 @@ class Request implements \ArrayAccess, \Countable, IRequest { } /** + * Checks if the strict cookie has been sent with the request if the request + * is including any cookies. + * + * @return bool + * @since 9.1.0 + */ + public function passesStrictCookieCheck() { + if(count($this->cookies) === 0) { + return true; + } + if($this->getCookie('nc_sameSiteCookiestrict') === 'true' + && $this->passesLaxCookieCheck()) { + return true; + } + return false; + } + + /** + * Checks if the lax cookie has been sent with the request if the request + * is including any cookies. + * + * @return bool + * @since 9.1.0 + */ + public function passesLaxCookieCheck() { + if(count($this->cookies) === 0) { + return true; + } + if($this->getCookie('nc_sameSiteCookielax') === 'true') { + return true; + } + return false; + } + + + /** * Returns an ID for the request, value is not guaranteed to be unique and is mostly meant for logging * If `mod_unique_id` is installed this value will be taken. * @return string diff --git a/lib/private/AppFramework/Middleware/Security/Exceptions/StrictCookieMissingException.php b/lib/private/AppFramework/Middleware/Security/Exceptions/StrictCookieMissingException.php new file mode 100644 index 00000000000..9ccaed4566f --- /dev/null +++ b/lib/private/AppFramework/Middleware/Security/Exceptions/StrictCookieMissingException.php @@ -0,0 +1,36 @@ +<?php +/** + * @author Lukas Reschke <lukas@statuscode.ch> + * + * @license GNU AGPL version 3 or any later version + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * 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 + * along with this program. If not, see <http://www.gnu.org/licenses/>. + * + */ + +namespace OC\AppFramework\Middleware\Security\Exceptions; + +use OCP\AppFramework\Http; + +/** + * Class StrictCookieMissingException is thrown when the strict cookie has not + * been sent with the request but is required. + * + * @package OC\AppFramework\Middleware\Security\Exceptions + */ +class StrictCookieMissingException extends SecurityException { + public function __construct() { + parent::__construct('Strict Cookie has not been found in request.', Http::STATUS_PRECONDITION_FAILED); + } +} diff --git a/lib/private/AppFramework/Middleware/Security/SecurityMiddleware.php b/lib/private/AppFramework/Middleware/Security/SecurityMiddleware.php index a3ece262e10..98117751e21 100644 --- a/lib/private/AppFramework/Middleware/Security/SecurityMiddleware.php +++ b/lib/private/AppFramework/Middleware/Security/SecurityMiddleware.php @@ -32,6 +32,7 @@ use OC\AppFramework\Middleware\Security\Exceptions\AppNotEnabledException; use OC\AppFramework\Middleware\Security\Exceptions\CrossSiteRequestForgeryException; use OC\AppFramework\Middleware\Security\Exceptions\NotAdminException; use OC\AppFramework\Middleware\Security\Exceptions\NotLoggedInException; +use OC\AppFramework\Middleware\Security\Exceptions\StrictCookieMissingException; use OC\AppFramework\Utility\ControllerMethodReflector; use OC\Security\CSP\ContentSecurityPolicyManager; use OCP\AppFramework\Http\ContentSecurityPolicy; @@ -134,6 +135,12 @@ class SecurityMiddleware extends Middleware { } } + // Check for strict cookie requirement + if($this->reflector->hasAnnotation('StrictCookieRequired') || !$this->reflector->hasAnnotation('NoCSRFRequired')) { + if(!$this->request->passesStrictCookieCheck()) { + throw new StrictCookieMissingException(); + } + } // CSRF check - also registers the CSRF token since the session may be closed later Util::callRegister(); if(!$this->reflector->hasAnnotation('NoCSRFRequired')) { @@ -186,7 +193,9 @@ class SecurityMiddleware extends Middleware { */ public function afterException($controller, $methodName, \Exception $exception) { if($exception instanceof SecurityException) { - + if($exception instanceof StrictCookieMissingException) { + return new RedirectResponse(\OC::$WEBROOT); + } if (stripos($this->request->getHeader('Accept'),'html') === false) { $response = new JSONResponse( array('message' => $exception->getMessage()), diff --git a/lib/private/legacy/eventsource.php b/lib/private/legacy/eventsource.php index 51040e7be7d..70e9847d237 100644 --- a/lib/private/legacy/eventsource.php +++ b/lib/private/legacy/eventsource.php @@ -76,6 +76,10 @@ class OC_EventSource implements \OCP\IEventSource { } else { header("Content-Type: text/event-stream"); } + if(!\OC::$server->getRequest()->passesStrictCookieCheck()) { + header('Location: '.\OC::$WEBROOT); + exit(); + } if (!(\OC::$server->getRequest()->passesCSRFCheck())) { $this->send('error', 'Possible CSRF attack. Connection will be closed.'); $this->close(); diff --git a/lib/private/legacy/json.php b/lib/private/legacy/json.php index 1dde63602b1..557e1d77012 100644 --- a/lib/private/legacy/json.php +++ b/lib/private/legacy/json.php @@ -79,6 +79,11 @@ class OC_JSON{ * @deprecated Use annotation based CSRF checks from the AppFramework instead */ public static function callCheck() { + if(!\OC::$server->getRequest()->passesStrictCookieCheck()) { + header('Location: '.\OC::$WEBROOT); + exit(); + } + if( !(\OC::$server->getRequest()->passesCSRFCheck())) { $l = \OC::$server->getL10N('lib'); self::error(array( 'data' => array( 'message' => $l->t('Token expired. Please reload page.'), 'error' => 'token_expired' ))); diff --git a/lib/public/IRequest.php b/lib/public/IRequest.php index 4db1c18b9c1..46e67d1415f 100644 --- a/lib/public/IRequest.php +++ b/lib/public/IRequest.php @@ -158,6 +158,24 @@ interface IRequest { public function passesCSRFCheck(); /** + * Checks if the strict cookie has been sent with the request if the request + * is including any cookies. + * + * @return bool + * @since 9.0.0 + */ + public function passesStrictCookieCheck(); + + /** + * Checks if the lax cookie has been sent with the request if the request + * is including any cookies. + * + * @return bool + * @since 9.0.0 + */ + public function passesLaxCookieCheck(); + + /** * Returns an ID for the request, value is not guaranteed to be unique and is mostly meant for logging * If `mod_unique_id` is installed this value will be taken. * diff --git a/lib/public/Util.php b/lib/public/Util.php index 687f4e78f69..9422dbac66a 100644 --- a/lib/public/Util.php +++ b/lib/public/Util.php @@ -513,6 +513,11 @@ class Util { * @deprecated 9.0.0 Use annotations based on the app framework. */ public static function callCheck() { + if(!\OC::$server->getRequest()->passesStrictCookieCheck()) { + header('Location: '.\OC::$WEBROOT); + exit(); + } + if (!(\OC::$server->getRequest()->passesCSRFCheck())) { exit(); } |