From 04e240227636e5c722c191dd78b6fcaa2a660e75 Mon Sep 17 00:00:00 2001 From: Lucas Bickel Date: Tue, 18 Jul 2017 20:39:53 +0200 Subject: [PATCH] Fix non default local CORS URL case I cleaned up the CORSHandler code a bit more and also rewrote the helper to use the framework to access the request properly and took care of also grabbing the request schema from the server. --- airtime_mvc/application/common/CORSHelper.php | 33 ++++++++++++++++--- airtime_mvc/application/forms/Login.php | 2 +- 2 files changed, 30 insertions(+), 5 deletions(-) diff --git a/airtime_mvc/application/common/CORSHelper.php b/airtime_mvc/application/common/CORSHelper.php index 86dc00c29..04c9d8c38 100644 --- a/airtime_mvc/application/common/CORSHelper.php +++ b/airtime_mvc/application/common/CORSHelper.php @@ -7,8 +7,9 @@ class CORSHelper { //Chrome sends the Origin header for all requests, so we whitelist the webserver's hostname as well. $origin = $request->getHeader('Origin'); + if ((!(preg_match("/https?:\/\/localhost/", $origin) === 1)) && ($origin != "") && - (!in_array($origin, self::getAllowedOrigins()))) + (!in_array($origin, self::getAllowedOrigins($request)))) { //Don't allow CORS from other domains to prevent XSS. throw new Zend_Controller_Action_Exception('Forbidden', 403); @@ -19,14 +20,38 @@ class CORSHelper } } - public static function getAllowedOrigins() + /** + * Get all allowed origins + * + * @param Request $request request object + */ + public static function getAllowedOrigins($request) { $allowedCorsUrls = array_map( function($v) { return trim($v); }, explode(PHP_EOL, Application_Model_Preference::GetAllowedCorsUrls()) ); + + // always allow the configured server in (as reported by the server and not what is i baseUrl) + $scheme = $request->getServer('REQUEST_SCHEME'); + $host = $request->getServer('SERVER_NAME'); + $port = $request->getServer('SERVER_PORT'); + + $portString = ''; + if ( + $scheme == 'https' && $port != 443 || + $scheme == 'http' && $port != 80 + ) { + $portString = sprintf(':%s', $port); + } + $requestedUrl = sprintf( + '%s://%s%s', + $scheme, + $host, + $portString + ); return array_merge($allowedCorsUrls, array( - "http://" . $_SERVER['SERVER_NAME'], - "https://" . $_SERVER['SERVER_NAME'])); + $requestedUrl + )); } } diff --git a/airtime_mvc/application/forms/Login.php b/airtime_mvc/application/forms/Login.php index 926570b41..fd99e0537 100644 --- a/airtime_mvc/application/forms/Login.php +++ b/airtime_mvc/application/forms/Login.php @@ -16,7 +16,7 @@ class Application_Form_Login extends Zend_Form if ($request) { $refererUrl = $request->getHeader('referer'); $originIsSafe = false; - foreach (CORSHelper::getAllowedOrigins() as $safeOrigin) { + foreach (CORSHelper::getAllowedOrigins($request) as $safeOrigin) { if ($this->startsWith($safeOrigin, $refererUrl)) { $originIsSafe = true; break;