public function preDispatch(Zend_Controller_Request_Abstract $request) { if (!isset($_SERVER['HTTP_USER_AGENT']) || isset($_SERVER['HTTP_USER_AGENT']) && false === strpos($_SERVER['HTTP_USER_AGENT'], 'sanmax-crawler-bot')) { return; } $config = array('accept_schemes' => 'basic', 'realm' => 'crawler', 'digest_domains' => '/', 'nonce_timeout' => 3600); $adapter = new Zend_Auth_Adapter_Http($config); $basicResolver = new Zend_Auth_Adapter_Http_Resolver_File(APPLICATION_PATH . '/var/bot-basic'); $adapter->setBasicResolver($basicResolver); $response = Zend_Controller_Front::getInstance()->getResponse(); $adapter->setRequest($request); $adapter->setResponse($response); $auth = Zend_Auth::getInstance(); $result = $auth->authenticate($adapter); if (!$result->isValid()) { $response->sendHeaders(); exit; } $user = new SxCms_User(); $gMapper = new SxCms_Group_DataMapper(); $groups = $gMapper->getAll(); foreach ($groups as $group) { $user->addGroup($group); } $storage = $auth->getStorage(); $storage->write($user); $front = Zend_Controller_Front::getInstance(); $front->setParam('isBot', true); $mvc = Zend_Layout::getMvcInstance(); $view = $mvc->getView(); $view->isBot = true; return; }
/** * Provides basic httpd security for the soap calls * * @return void * * This function forces basic http security. I wish we could do this site wide with digest domains but it doesn't seem * to work properly in Zend at the moment. So this function is called by the actions we want to protect. Dirty :( */ protected function enforceSecurity($passwdFilePath = '/configs/soap_password.txt') { $config = array('accept_schemes' => 'basic', 'realm' => 'HomeLet API', 'nonce_timeout' => 3600); // Don't request authentication if this is the KeyHouse server // TEMPORARY FIX - SECURITY ISSUE // TODO: Remove me! if ($_SERVER['REMOTE_ADDR'] != '82.44.126.148') { $adapter = new Zend_Auth_Adapter_Http($config); $resolver = new Zend_Auth_Adapter_Http_Resolver_File(APPLICATION_PATH . $passwdFilePath); $adapter->setBasicResolver($resolver); $storage = new Zend_Auth_Storage_NonPersistent(); Zend_Auth::getInstance()->setStorage($storage); $response = Zend_Controller_Front::getInstance()->getResponse(); $response = new Zend_Controller_Response_Http(); $request = new Zend_Controller_Request_Http(); $adapter->setRequest($request); $adapter->setResponse($response); $result = Zend_Auth::getInstance()->authenticate($adapter); $response->sendHeaders(); if (!$result->isValid()) { // Bad userame/password, or cancelled password prompt die('Invalid username/password'); } } }
/** * authenticates request * * @access protected */ protected function _authorize() { $config = array('accept_schemes' => 'basic', 'realm' => 'trade-capture'); $adapter = new Zend_Auth_Adapter_Http($config); $options = $this->_getConfigOptions(); $basic_resolver_file = $options['auth']['file']['basic']; $basic_resolver = new Zend_Auth_Adapter_Http_Resolver_File(); $basic_resolver->setFile($basic_resolver_file); $request = $this->getRequest(); $response = $this->getResponse(); $adapter->setBasicResolver($basic_resolver); $adapter->setRequest($request); $adapter->setResponse($response); $result = $adapter->authenticate(); if (!$result->isValid()) { $request->setActionName('unauth'); } }
/** * Secures the API access to only requests that authenticate using the * HomeLet REST API realm. Based on SOAP modules's index controller's * security. * * @return void */ protected function _enforceSecurity() { $response = Zend_Controller_Front::getInstance()->getResponse(); $request = Zend_Controller_Front::getInstance()->getRequest(); // Ensure REST access is allowed if (!$this->_params->security->allowRestAccess) { $response->clearHeaders(); $response->setHttpResponseCode(403); $response->sendHeaders(); die('RESTful access disabled'); } $config = array('accept_schemes' => 'basic', 'realm' => 'HomeLet REST API', 'nonce_timeout' => 3600); $adapter = new Zend_Auth_Adapter_Http($config); $resolver = new Zend_Auth_Adapter_Http_Resolver_File(APPLICATION_PATH . '/configs/rest_password.txt'); $adapter->setBasicResolver($resolver); $storage = new Zend_Auth_Storage_NonPersistent(); Zend_Auth::getInstance()->setStorage($storage); $adapter->setRequest($request); $adapter->setResponse($response); $result = Zend_Auth::getInstance()->authenticate($adapter); // Ensure we're running over SSL if ($request->getScheme() != 'https') { $response->clearHeaders(); $response->setHttpResponseCode(403); $response->sendHeaders(); die('Insecure connection scheme'); } // Bad userame/password, or cancelled password prompt if (!$result->isValid()) { $response->clearHeaders(); $response->setHttpResponseCode(401); $response->setHeader('WWW-Authenticate', "{$config['accept_schemes']} realm=\"{$config['realm']}\""); $response->sendHeaders(); die('Invalid username/password'); } $response->sendHeaders(); }
/** * Acts like a client sending the given Authenticate header value. * * @param string $clientHeader Authenticate header value * @param string $scheme Which authentication scheme to use * @return array Containing the result, the response headers, and the status */ public function _doAuth($clientHeader, $scheme) { // Set up stub request and response objects $request = $this->getMock('Zend_Controller_Request_Http'); $response = new Zend_Controller_Response_Http(); $response->setHttpResponseCode(200); $response->headersSentThrowsException = false; // Set stub method return values $request->expects($this->any())->method('getRequestUri')->will($this->returnValue('/')); $request->expects($this->any())->method('getMethod')->will($this->returnValue('GET')); $request->expects($this->any())->method('getServer')->will($this->returnValue('PHPUnit')); $request->expects($this->any())->method('getHeader')->will($this->returnValue($clientHeader)); // Select an Authentication scheme switch ($scheme) { case 'basic': $use = $this->_basicConfig; break; case 'digest': $use = $this->_digestConfig; break; case 'both': default: $use = $this->_bothConfig; } // Create the HTTP Auth adapter $a = new Zend_Auth_Adapter_Http($use); $a->setBasicResolver($this->_basicResolver); $a->setDigestResolver($this->_digestResolver); // Send the authentication request $a->setRequest($request); $a->setResponse($response); $result = $a->authenticate(); $return = array('result' => $result, 'status' => $response->getHttpResponseCode(), 'headers' => $response->getHeaders()); return $return; }
public function testNoResolvers() { $request = $this->getMock('Zend_Controller_Request_Http'); $response = $this->getMock('Zend_Controller_Response_Http'); // Stub request for Basic auth $request->expects($this->any()) ->method('getHeader') ->will($this->returnValue('Basic other stuff not tested')); // Once for Basic try { $a = new Zend_Auth_Adapter_Http($this->_basicConfig); $a->setRequest($request); $a->setResponse($response); $result = $a->authenticate(); $this->fail("Tried Basic authentication without a resolver.\n" . array_shift($result->getMessages())); } catch (Zend_Auth_Adapter_Exception $e) { // Good, it threw an exception unset($a); } // Stub request for Digest auth $request->expects($this->any()) ->method('getHeader') ->will($this->returnValue('Digest other stuff not tested')); // Once for Digest try { $a = new Zend_Auth_Adapter_Http($this->_digestConfig); $a->setRequest($request); $a->setResponse($response); $result = $a->authenticate(); $this->fail("Tried Digest authentication without a resolver.\n" . array_shift($result->getMessages())); } catch (Zend_Auth_Adapter_Exception $e) { // Good, it threw an exception unset($a); } }
/** * @param $path * @param bool $partial * @return array|bool */ public function match($path, $partial = false) { // this allows the usage of UTF8 URLs and within static routes $path = urldecode($path); $front = \Zend_Controller_Front::getInstance(); $matchFound = false; $config = Config::getSystemConfig(); $routeingDefaults = Tool::getRoutingDefaults(); $params = array_merge($_GET, $_POST); $params = array_merge($routeingDefaults, $params); // set the original path $originalPath = $path; // check for password protection (http auth) if ($config->general->http_auth) { $username = $config->general->http_auth->username; $password = $config->general->http_auth->password; if ($username && $password) { $adapter = new \Zend_Auth_Adapter_Http(array("accept_schemes" => "basic", "realm" => $_SERVER["HTTP_HOST"])); $basicResolver = new \Pimcore\Helper\Auth\Adapter\Http\ResolverStatic($username, $password); $adapter->setBasicResolver($basicResolver); $adapter->setRequest($front->getRequest()); $adapter->setResponse($front->getResponse()); $result = $adapter->authenticate(); if (!$result->isValid()) { // Bad userame/password, or canceled password prompt echo "Authentication Required"; $front->getResponse()->sendResponse(); exit; } } } // check for a registered site try { // do not initialize a site if it is a "special" admin request if (!Tool::isFrontentRequestByAdmin()) { $domain = Tool::getHostname(); $site = \Zend_Registry::isRegistered("pimcore_site") ? \Zend_Registry::get("pimcore_site") : Site::getByDomain($domain); $path = $site->getRootPath() . $path; \Zend_Registry::set("pimcore_site", $site); } } catch (\Exception $e) { } // test if there is a suitable redirect with override = all (=> priority = 99) if (!$matchFound) { $this->checkForRedirect(true); } // do not allow requests including /index.php/ => SEO // this is after the first redirect check, to allow redirects in index.php?xxx if (preg_match("@^/index.php(.*)@", $_SERVER["REQUEST_URI"], $matches) && strtolower($_SERVER["REQUEST_METHOD"]) == "get") { $redirectUrl = $matches[1]; $redirectUrl = ltrim($redirectUrl, "/"); $redirectUrl = "/" . $redirectUrl; header("Location: " . $redirectUrl, true, 301); exit; } // redirect to the main domain if specified try { $hostRedirect = null; if ($config->general->redirect_to_maindomain && $config->general->domain && $config->general->domain != Tool::getHostname() && !Site::isSiteRequest() && !Tool::isFrontentRequestByAdmin()) { $hostRedirect = $config->general->domain; } if (Site::isSiteRequest()) { $site = Site::getCurrentSite(); if ($site->getRedirectToMainDomain() && $site->getMainDomain() != Tool::getHostname()) { $hostRedirect = $site->getMainDomain(); } } if ($hostRedirect && !isset($_GET["pimcore_disable_host_redirect"])) { $url = ($front->getRequest()->isSecure() ? "https" : "http") . "://" . $hostRedirect . $_SERVER["REQUEST_URI"]; header("HTTP/1.1 301 Moved Permanently"); header("Location: " . $url, true, 301); // log all redirects to the redirect log \Pimcore\Log\Simple::log("redirect", Tool::getAnonymizedClientIp() . " \t Host-Redirect Source: " . $_SERVER["REQUEST_URI"] . " -> " . $url); exit; } } catch (\Exception $e) { } // check for direct definition of controller/action if (!empty($_REQUEST["controller"]) && !empty($_REQUEST["action"])) { $matchFound = true; //$params["document"] = $this->getNearestDocumentByPath($path); } // you can also call a page by it's ID /?pimcore_document=XXXX if (!$matchFound) { if (!empty($params["pimcore_document"]) || !empty($params["pdid"])) { $doc = Document::getById($params["pimcore_document"] ? $params["pimcore_document"] : $params["pdid"]); if ($doc instanceof Document) { $path = $doc->getFullPath(); } } } // test if there is a suitable page if (!$matchFound) { try { $document = Document::getByPath($path); // check for a pretty url inside a site if (!$document && Site::isSiteRequest()) { $documentService = new Document\Service(); $sitePrettyDocId = $documentService->getDocumentIdByPrettyUrlInSite(Site::getCurrentSite(), $originalPath); if ($sitePrettyDocId) { if ($sitePrettyDoc = Document::getById($sitePrettyDocId)) { $document = $sitePrettyDoc; // undo the modification of the path by the site detection (prefixing with site root path) // this is not necessary when using pretty-urls and will cause problems when validating the // prettyUrl later (redirecting to the prettyUrl in the case the page was called by the real path) $path = $originalPath; } } } // check for a parent hardlink with childs if (!$document instanceof Document) { $hardlinkedParentDocument = $this->getNearestDocumentByPath($path, true); if ($hardlinkedParentDocument instanceof Document\Hardlink) { if ($hardLinkedDocument = Document\Hardlink\Service::getChildByPath($hardlinkedParentDocument, $path)) { $document = $hardLinkedDocument; } } } // check for direct hardlink if ($document instanceof Document\Hardlink) { $hardlinkParentDocument = $document; $document = Document\Hardlink\Service::wrap($hardlinkParentDocument); } if ($document instanceof Document) { if (in_array($document->getType(), self::getDirectRouteDocumentTypes())) { if (Tool::isFrontentRequestByAdmin() || $document->isPublished()) { // check for a pretty url, and if the document is called by that, otherwise redirect to pretty url if ($document instanceof Document\Page && !$document instanceof Document\Hardlink\Wrapper\WrapperInterface && $document->getPrettyUrl() && !Tool::isFrontentRequestByAdmin()) { if (rtrim(strtolower($document->getPrettyUrl()), " /") != rtrim(strtolower($originalPath), "/")) { $redirectUrl = $document->getPrettyUrl(); if ($_SERVER["QUERY_STRING"]) { $redirectUrl .= "?" . $_SERVER["QUERY_STRING"]; } header("Location: " . $redirectUrl, true, 301); exit; } } $params["document"] = $document; if ($controller = $document->getController()) { $params["controller"] = $controller; $params["action"] = "index"; } if ($action = $document->getAction()) { $params["action"] = $action; } if ($module = $document->getModule()) { $params["module"] = $module; } // check for a trailing slash in path, if exists, redirect to this page without the slash // the only reason for this is: SEO, Analytics, ... there is no system specific reason, pimcore would work also with a trailing slash without problems // use $originalPath because of the sites // only do redirecting with GET requests if (strtolower($_SERVER["REQUEST_METHOD"]) == "get") { if ($config->documents->allowtrailingslash) { if ($config->documents->allowtrailingslash == "no") { if (substr($originalPath, strlen($originalPath) - 1, 1) == "/" && $originalPath != "/") { $redirectUrl = rtrim($originalPath, "/"); if ($_SERVER["QUERY_STRING"]) { $redirectUrl .= "?" . $_SERVER["QUERY_STRING"]; } header("Location: " . $redirectUrl, true, 301); exit; } } } if ($config->documents->allowcapitals) { if ($config->documents->allowcapitals == "no") { if (strtolower($originalPath) != $originalPath) { $redirectUrl = strtolower($originalPath); if ($_SERVER["QUERY_STRING"]) { $redirectUrl .= "?" . $_SERVER["QUERY_STRING"]; } header("Location: " . $redirectUrl, true, 301); exit; } } } } $matchFound = true; } } else { if ($document->getType() == "link") { // if the document is a link just redirect to the location/href of the link header("Location: " . $document->getHref(), true, 301); exit; } } } } catch (\Exception $e) { // no suitable page found $foo = "bar"; } } // test if there is a suitable static route if (!$matchFound) { try { $cacheKey = "system_route_staticroute"; if (!($routes = Cache::load($cacheKey))) { $list = new Staticroute\Listing(); $list->setOrderKey("priority"); $list->setOrder("DESC"); $routes = $list->load(); Cache::save($routes, $cacheKey, array("system", "staticroute", "route"), null, 998); } foreach ($routes as $route) { if (!$matchFound) { $routeParams = $route->match($originalPath, $params); if ($routeParams) { $params = $routeParams; // try to get nearest document to the route $document = $this->getNearestDocumentByPath($path, false, array("page", "snippet", "hardlink")); if ($document instanceof Document\Hardlink) { $document = Document\Hardlink\Service::wrap($document); } $params["document"] = $document; $matchFound = true; Staticroute::setCurrentRoute($route); // add the route object also as parameter to the request object, this is needed in // Pimcore_Controller_Action_Frontend::getRenderScript() // to determine if a call to an action was made through a staticroute or not // more on that infos see Pimcore_Controller_Action_Frontend::getRenderScript() $params["pimcore_request_source"] = "staticroute"; break; } } } } catch (\Exception $e) { // no suitable route found } } // test if there is a suitable redirect if (!$matchFound) { $this->checkForRedirect(false); } if (!$matchFound) { return false; } // remove pimcore magic parameters unset($params["pimcore_outputfilters_disabled"]); unset($params["pimcore_document"]); unset($params["nocache"]); return $params; }
public function preDispatch() { $this->_startTime = microtime(true); // use plain text error reporting ini_set('html_errors', 0); // login procedure // can handler digest or basic authentication but won't send // WWW-Authenticate header challenging clients to use those. // Instead will have the client as a anonymous user ('default') unless // they authenticate with basic, digest or create a session // get the Authorization header for checking header based authentication // methods such as basic and digest $headerAuthType = strtolower(strstr(strstr($this->getRequest()->getHeader('Authorization'), 'Authorization: '), ' ', true)); // set up auth adapter, check if basic, or digest are appropriate, if // not use session based if ('basic' == $headerAuthType) { // start up basic auth if requested $config = array( 'accept_schemes' => 'basic', 'realm' => 'App', 'digest_domains' => '/', 'nonce_timeout' => 3600, ); $authAdapter = new Zend_Auth_Adapter_Http($config); $basicResolver = new Rest_Auth_Adapter_Http_Resolver_RestDb('basic'); $authAdapter->setBasicResolver($basicResolver); $authAdapter->setRequest($this->getRequest()); $authAdapter->setResponse($this->getResponse()); } elseif ('digest' == $headerAuthType) { // start up digest auth if requested $config = array( 'accept_schemes' => 'digest', 'realm' => 'App', 'digest_domains' => '/', 'nonce_timeout' => 3600, ); $authAdapter = new Zend_Auth_Adapter_Http($config); $digestResolver = new Rest_Auth_Adapter_Http_Resolver_RestDb('digest'); $authAdapter->setDigestResolver($digestResolver); $authAdapter->setRequest($this->getRequest()); $authAdapter->setResponse($this->getResponse()); } else { // use session authentication, note that session authentication will // never result in inValid because if a session doesn't exist, a // session for a default user will be created // note: session credentials are set up by posting to a session // resource $authAdapter = new Rest_Auth_Adapter_RestSessionDb(); } require_once 'Zend/Auth.php'; $result = Zend_Auth::getInstance()->authenticate($authAdapter); // if a client has invalid credentials with a basic or digest // authentication, the Zend_Auth_Adapter_Http will challenge them on it if (!$result->isValid()) { // Bad userame/password, or canceled password prompt // Authentication failed; print the reasons why $this->getResponse()->setHttpResponseCode(401); $this->view->data = $result->getMessages(); // cancel the action but post dispatch will be executed $this->setCancelAction(true); return; } if ('Basic' == $headerAuthType || 'Digest' == $headerAuthType) { require_once 'models/Handler/Session.php'; $handler = new Default_Model_Handler_Session(); $handler->post(array('user_id' => $result->getIdentity()->id)); } }
/** * Implements HTTP Basic auth */ public function preDispatch() { parent::preDispatch(); $action = strtolower($this->getRequest()->getActionName()); if (in_array($action, $this->authActions)) { $auth = \Zend_Auth::getInstance(); $this->auth = $auth; if (!$auth->hasIdentity()) { $config = array('accept_schemes' => 'basic', 'realm' => GEMS_PROJECT_NAME, 'nonce_timeout' => 3600); $adapter = new \Zend_Auth_Adapter_Http($config); $basicResolver = new \Zend_Auth_Adapter_Http_Resolver_File(); //This is a basic resolver, use username:realm:password //@@TODO: move to a better db stored authentication system $basicResolver->setFile(GEMS_ROOT_DIR . '/var/settings/pwd.txt'); $adapter->setBasicResolver($basicResolver); $request = $this->getRequest(); $response = $this->getResponse(); assert($request instanceof \Zend_Controller_Request_Http); assert($response instanceof \Zend_Controller_Response_Http); $adapter->setRequest($request); $adapter->setResponse($response); $result = $auth->authenticate($adapter); if (!$result->isValid()) { $adapter->getResponse()->sendResponse(); print 'Unauthorized'; exit; } } } }
/** * Initiate shopware auth resource * database adapter by default * * @param Enlight_Event_EventArgs $args * @return null|\Zend_Auth */ public function onInitResourceAuth(Enlight_Event_EventArgs $args) { if (!$this->isApiCall) { return; } $adapter = new Zend_Auth_Adapter_Http(array('accept_schemes' => 'digest', 'realm' => 'Shopware4 REST-API', 'digest_domains' => '/', 'nonce_timeout' => 3600)); $adapter->setDigestResolver(new \ShopwarePlugins\RestApi\Components\StaticResolver($this->get('models'))); $adapter->setRequest($this->request); $adapter->setResponse($this->response); $resource = Shopware_Components_Auth::getInstance(); $storage = new Zend_Auth_Storage_NonPersistent(); $resource->setBaseAdapter($adapter); $resource->addAdapter($adapter); $resource->setStorage($storage); return $resource; }