} //something went wrong, but we do have a valid uri to redirect to. $errorParameters['error_uri'] = SimpleSAML\Utils\HTTP::addURLParameters(SimpleSAML_Module::getModuleURL('oauth2server/authorization/error.php'), $errorParameters); if (isset($_REQUEST['state'])) { $errorParameters['state'] = $_REQUEST['state']; } unset($errorParameters['error_code_internal']); unset($errorParameters['error_parameters_internal']); sspmod_oauth2server_Utility_Uri::redirectUri(sspmod_oauth2server_Utility_Uri::addQueryParametersToUrl($returnUri, $errorParameters)); } else { if (is_string(parse_url($returnUri, PHP_URL_FRAGMENT))) { $errorParameters = \sspmod_oauth2server_Utility_Uri::buildErrorResponse('invalid_redirect_uri', 'fragments are not allowed in redirect_uri: ' . $returnUri, 'FRAGMENT_REDIRECT_URI', array('REDIRECT_URI' => $returnUri, 'FRAGMENT' => parse_url($returnUri, PHP_URL_FRAGMENT))); } else { // this is not a proper error code used only internally $errorParameters = \sspmod_oauth2server_Utility_Uri::buildErrorResponse('invalid_redirect_uri', 'illegal redirect_uri: ' . $returnUri, 'INVALID_REDIRECT_URI', array('REDIRECT_URI' => $returnUri)); } } } else { $errorParameters = \sspmod_oauth2server_Utility_Uri::buildErrorResponse('server_error', 'no redirection uri associated with client id', 'NO_REDIRECT_URI', array()); } } else { if (isset($_REQUEST['client_id'])) { $errorParameters = \sspmod_oauth2server_Utility_Uri::buildErrorResponse('unauthorized_client', 'unauthorized_client: ' . $_REQUEST['client_id'], 'UNAUTHORIZED_CLIENT', array('CLIENT_ID' => $_REQUEST['client_id'])); } else { $errorParameters = \sspmod_oauth2server_Utility_Uri::buildErrorResponse('missing_client', 'missing client id', 'MISSING_CLIENT_ID', array()); } } //something went wrong, and we do not have a valid uri to redirect to. $error_uri = SimpleSAML\Utils\HTTP::addURLParameters(SimpleSAML_Module::getModuleURL('oauth2server/authorization/error.php'), $errorParameters); SimpleSAML\Utils\HTTP::redirectTrustedURL($error_uri);
/** * Marks the user as logged in with the specified authority. * * If the user already has logged in, the user will be logged out first. * * @param string $authority The authority the user logged in with. * @param array|null $data The authentication data for this authority. * * @throws \SimpleSAML\Error\CannotSetCookie If the authentication token cannot be set for some reason. */ public function doLogin($authority, array $data = null) { assert('is_string($authority)'); assert('is_array($data) || is_null($data)'); SimpleSAML\Logger::debug('Session: doLogin("' . $authority . '")'); $this->markDirty(); if (isset($this->authData[$authority])) { // we are already logged in, log the user out first $this->doLogout($authority); } if ($data === null) { $data = array(); } $data['Authority'] = $authority; $globalConfig = SimpleSAML_Configuration::getInstance(); if (!isset($data['AuthnInstant'])) { $data['AuthnInstant'] = time(); } $maxSessionExpire = time() + $globalConfig->getInteger('session.duration', 8 * 60 * 60); if (!isset($data['Expire']) || $data['Expire'] > $maxSessionExpire) { // unset, or beyond our session lifetime. Clamp it to our maximum session lifetime $data['Expire'] = $maxSessionExpire; } // check if we have non-serializable attribute values foreach ($data['Attributes'] as $attribute => $values) { foreach ($values as $idx => $value) { if (is_string($value) || is_int($value)) { continue; } // at this point, this should be a DOMNodeList object... if (!is_a($value, 'DOMNodeList')) { continue; } /* @var \DOMNodeList $value */ if ($value->length === 0) { continue; } // create an AttributeValue object and save it to 'RawAttributes', using same attribute name and index $attrval = new \SAML2\XML\saml\AttributeValue($value->item(0)->parentNode); $data['RawAttributes'][$attribute][$idx] = $attrval; } } $this->authData[$authority] = $data; $this->authToken = SimpleSAML\Utils\Random::generateID(); $sessionHandler = SimpleSAML_SessionHandler::getSessionHandler(); if (!$this->transient && (!empty($data['RememberMe']) || $this->rememberMeExpire) && $globalConfig->getBoolean('session.rememberme.enable', false)) { $this->setRememberMeExpire(); } else { try { SimpleSAML\Utils\HTTP::setCookie($globalConfig->getString('session.authtoken.cookiename', 'SimpleSAMLAuthToken'), $this->authToken, $sessionHandler->getCookieParams()); } catch (SimpleSAML\Error\CannotSetCookie $e) { /* * Something went wrong when setting the auth token. We cannot recover from this, so we better log a * message and throw an exception. The user is not properly logged in anyway, so clear all login * information from the session. */ unset($this->authToken); unset($this->authData[$authority]); \SimpleSAML\Logger::error('Cannot set authentication token cookie: ' . $e->getMessage()); throw $e; } } }
} } else { // wrong token type $errorCode = 401; $response = array('error' => 'invalid_token', 'error_description' => 'Only Bearer tokens are supported'); $response['error_uri'] = SimpleSAML\Utils\HTTP::addURLParameters(SimpleSAML_Module::getModuleURL('oauth2server/resource/error.php'), array('error_code_internal' => 'UNSUPPORTED_ACCESS_TOKEN', 'error_parameters_internal' => array('TOKEN_ID' => $accessTokenId))); } } else { // error missing token $errorCode = 401; $response = array(); } } } else { $errorCode = 403; $response = array('error' => 'invalid_request', 'error_description' => 'resource owner end point not enabled'); $response['error_uri'] = SimpleSAML\Utils\HTTP::addURLParameters(SimpleSAML_Module::getModuleURL('oauth2server/resource/error.php'), array('error_code_internal' => 'DISABLED', 'error_parameters_internal' => array())); } header('X-PHP-Response-Code: ' . $errorCode, true, $errorCode); if ($errorCode !== 200) { $authHeader = "WWW-Authenticate: Bearer "; if (array_key_exists('error', $response)) { $authHeader .= 'error="' . $response['error'] . '",error_description="' . $response['error_description'] . '",' . 'error_uri="' . urlencode($response['error_uri']) . '"'; if (array_key_exists('scope', $response)) { $authHeader .= ',scope="' . $response['scope'] . '"'; } } header($authHeader, true, $errorCode); } else { echo count($response) > 0 ? json_encode($response) : '{}'; }
/** * Ask the user to log out before being able to log in again with a different identity provider. Note that this * method is intended for instances of SimpleSAMLphp running as a SAML proxy, and therefore acting both as an SP * and an IdP at the same time. * * This method will never return. * * @param array $state The state array. The following keys must be defined in the array: * - 'saml:sp:IdPMetadata': a SimpleSAML_Configuration object containing the metadata of the IdP that authenticated * the user in the current session. * - 'saml:sp:AuthId': the identifier of the current authentication source. * - 'core:IdP': the identifier of the local IdP. * - 'SPMetadata': an array with the metadata of this local SP. * * @throws SimpleSAML_Error_NoPassive In case the authentication request was passive. */ public static function askForIdPChange(array &$state) { assert('array_key_exists("saml:sp:IdPMetadata", $state)'); assert('array_key_exists("saml:sp:AuthId", $state)'); assert('array_key_exists("core:IdP", $state)'); assert('array_key_exists("SPMetadata", $state)'); if (isset($state['isPassive']) && (bool) $state['isPassive']) { // passive request, we cannot authenticate the user throw new SimpleSAML_Error_NoPassive('Reauthentication required'); } // save the state WITHOUT a restart URL, so that we don't try an IdP-initiated login if something goes wrong $id = SimpleSAML_Auth_State::saveState($state, 'saml:proxy:invalid_idp', true); $url = SimpleSAML\Module::getModuleURL('saml/proxy/invalid_session.php'); SimpleSAML\Utils\HTTP::redirectTrustedURL($url, array('AuthState' => $id)); assert('false'); }
$ticketStore = new $ticketStoreClass($casconfig); $ticketFactoryClass = SimpleSAML_Module::resolveClass('casserver:TicketFactory', 'Cas_Ticket'); $ticketFactory = new $ticketFactoryClass($casconfig); $serviceTicket = $ticketStore->getTicket($_GET['ticket']); if (!is_null($serviceTicket) && ($ticketFactory->isServiceTicket($serviceTicket) || $ticketFactory->isProxyTicket($serviceTicket) && $method == 'proxyValidate')) { $ticketStore->deleteTicket($_GET['ticket']); $attributes = $serviceTicket['attributes']; if (!$ticketFactory->isExpired($serviceTicket) && sanitize($serviceTicket['service']) == sanitize($_GET['service']) && (!$forceAuthn || $serviceTicket['forceAuthn'])) { $protocol->setAttributes($attributes); if (isset($_GET['pgtUrl'])) { $sessionTicket = $ticketStore->getTicket($serviceTicket['sessionId']); $pgtUrl = $_GET['pgtUrl']; if (!is_null($sessionTicket) && $ticketFactory->isSessionTicket($sessionTicket) && !$ticketFactory->isExpired($sessionTicket)) { $proxyGrantingTicket = $ticketFactory->createProxyGrantingTicket(array('userName' => $serviceTicket['userName'], 'attributes' => $attributes, 'forceAuthn' => false, 'proxies' => array_merge(array($_GET['service']), $serviceTicket['proxies']), 'sessionId' => $serviceTicket['sessionId'])); try { SimpleSAML\Utils\HTTP::fetch($pgtUrl . '?pgtIou=' . $proxyGrantingTicket['iou'] . '&pgtId=' . $proxyGrantingTicket['id']); $protocol->setProxyGrantingTicketIOU($proxyGrantingTicket['iou']); $ticketStore->addTicket($proxyGrantingTicket); } catch (Exception $e) { } } } echo $protocol->getValidateSuccessResponse($serviceTicket['userName']); } else { if ($ticketFactory->isExpired($serviceTicket)) { $message = 'Ticket ' . var_export($_GET['ticket'], true) . ' has expired'; SimpleSAML_Logger::debug('casserver:' . $message); echo $protocol->getValidateFailureResponse('INVALID_TICKET', $message); } else { if (sanitize($serviceTicket['service']) != sanitize($_GET['service'])) { $message = 'Mismatching service parameters: expected ' . var_export($serviceTicket['service'], true) . ' but was: ' . var_export($_GET['service'], true);
} $skipLogoutPage = $casconfig->getValue('skip_logout_page', false); if ($skipLogoutPage && !array_key_exists('url', $_GET)) { $message = 'Required URL query parameter [url] not provided. (CAS Server)'; SimpleSAML_Logger::debug('casserver:' . $message); throw new Exception($message); } /* Load simpleSAMLphp metadata */ $as = new SimpleSAML_Auth_Simple($casconfig->getValue('authsource')); $session = SimpleSAML_Session::getSession(); if (!is_null($session)) { $ticketStoreConfig = $casconfig->getValue('ticketstore', array('class' => 'casserver:FileSystemTicketStore')); $ticketStoreClass = SimpleSAML_Module::resolveClass($ticketStoreConfig['class'], 'Cas_Ticket'); $ticketStore = new $ticketStoreClass($casconfig); $ticketStore->deleteTicket($session->getSessionId()); } if ($as->isAuthenticated()) { SimpleSAML_Logger::debug('casserver: performing a real logout'); if ($casconfig->getValue('skip_logout_page', false)) { $as->logout($_GET['url']); } else { $as->logout(SimpleSAML\Utils\HTTP::addURLParameters(SimpleSAML_Module::getModuleURL('casserver/loggedOut.php'), array_key_exists('url', $_GET) ? array('url' => $_GET['url']) : array())); } } else { SimpleSAML_Logger::debug('casserver: no session to log out of, performing redirect'); if ($casconfig->getValue('skip_logout_page', false)) { SimpleSAML\Utils\HTTP::redirectTrustedURL(SimpleSAML\Utils\HTTP::addURLParameters($_GET['url'], array())); } else { SimpleSAML\Utils\HTTP::redirectTrustedURL(SimpleSAML\Utils\HTTP::addURLParameters(SimpleSAML_Module::getModuleURL('casserver/loggedOut.php'), array_key_exists('url', $_GET) ? array('url' => $_GET['url']) : array())); } }
$tokenStore->removeAuthorizationCode($_REQUEST['tokenId']); SimpleSAML\Utils\HTTP::redirectTrustedURL(SimpleSAML_Module::getModuleURL('oauth2server/manage/status.php')); } } else { if (array_search($_REQUEST['tokenId'], $user['refreshTokens']) !== false) { $token = $tokenStore->getRefreshToken($_REQUEST['tokenId']); if (is_array($token) && isset($_POST['revoke'])) { $tokenStore->removeRefreshToken($_REQUEST['tokenId']); SimpleSAML\Utils\HTTP::redirectTrustedURL(SimpleSAML_Module::getModuleURL('oauth2server/manage/status.php')); } } else { if (array_search($_REQUEST['tokenId'], $user['accessTokens']) !== false) { $token = $tokenStore->getAccessToken($_REQUEST['tokenId']); if (is_array($token) && isset($_POST['revoke'])) { $tokenStore->removeAccessToken($_REQUEST['tokenId']); SimpleSAML\Utils\HTTP::redirectTrustedURL(SimpleSAML_Module::getModuleURL('oauth2server/manage/status.php')); } } } } } $globalConfig = SimpleSAML_Configuration::getInstance(); $t = new SimpleSAML_XHTML_Template($globalConfig, 'oauth2server:manage/token.php'); foreach ($config->getValue('scopes', array()) as $scope => $translations) { $t->includeInlineTranslation('{oauth2server:oauth2server:' . $scope . '}', $translations); } if (isset($token)) { $clientStore = new sspmod_oauth2server_OAuth2_ClientStore($config); $client = $clientStore->getClient($token['clientId']); if (!is_null($client)) { $t->data['token'] = $token;
} } else { $response = \sspmod_oauth2server_Utility_Uri::buildErrorResponse('invalid_request', 'missing client id', 'MISSING_CLIENT_ID', array()); $errorCode = 400; } } else { $response = \sspmod_oauth2server_Utility_Uri::buildErrorResponse('unsupported_grant_type', 'unsupported grant type: ' . $_POST['grant_type'], 'UNSUPPORTED_GRANT_TYPE', array('GRANT_TYPE' => $_POST['grant_type'])); $errorCode = 400; } } else { $response = \sspmod_oauth2server_Utility_Uri::buildErrorResponse('invalid_request', 'missing grant type', 'MISSING_GRANT_TYPE', array()); $errorCode = 400; } } elseif ($_SERVER['REQUEST_METHOD'] != 'OPTIONS') { //dont freak over the damn ajax options pre-flight requests $response = \sspmod_oauth2server_Utility_Uri::buildErrorResponse('invalid_request', 'http(s) POST required', 'MUST_POST', array()); $errorCode = 400; } header('X-PHP-Response-Code: ' . $errorCode, true, $errorCode); if ($errorCode === 401) { header("WWW-Authenticate: Basic realm=\"OAuth 2.0\"", true, $errorCode); } if (!is_null($response)) { if (array_key_exists('error', $response)) { $error_uri = SimpleSAML\Utils\HTTP::addURLParameters(SimpleSAML_Module::getModuleURL('oauth2server/authorization/error.php'), $response); $response['error_uri'] = $error_uri; unset($response['error_code_internal']); unset($response['error_parameters_internal']); } echo json_encode($response); }
if (is_string($_GET['language'])) { $parameters['language'] = $_GET['language']; } } } if (isset($_GET['service'])) { $attributes = $as->getAttributes(); $casUsernameAttribute = $casconfig->getValue('attrname', 'eduPersonPrincipalName'); $userName = $attributes[$casUsernameAttribute][0]; if ($casconfig->getValue('attributes', true)) { $attributesToTransfer = $casconfig->getValue('attributes_to_transfer', array()); if (sizeof($attributesToTransfer) > 0) { $casAttributes = array(); foreach ($attributesToTransfer as $key) { if (array_key_exists($key, $attributes)) { $casAttributes[$key] = $attributes[$key]; } } } else { $casAttributes = $attributes; } } else { $casAttributes = array(); } $serviceTicket = $ticketFactory->createServiceTicket(array('service' => $_GET['service'], 'forceAuthn' => $forceAuthn, 'userName' => $userName, 'attributes' => $casAttributes, 'proxies' => array(), 'sessionId' => $sessionTicket['id'])); $ticketStore->addTicket($serviceTicket); $parameters['ticket'] = $serviceTicket['id']; SimpleSAML\Utils\HTTP::redirectTrustedURL(SimpleSAML\Utils\HTTP::addURLParameters($_GET['service'], $parameters)); } else { SimpleSAML\Utils\HTTP::redirectTrustedURL(SimpleSAML\Utils\HTTP::addURLParameters(SimpleSAML_Module::getModuleURL('casserver/loggedIn.php'), $parameters)); }
echo $this->t('{oauth2server:oauth2server:client_description}'); ?> </th> <th><?php echo $this->t('{oauth2server:oauth2server:client_expire}'); ?> </th> </tr> <?php foreach ($this->data['clients'] as $client) { ?> <tr> <td> <a href="<?php echo htmlentities(SimpleSAML\Utils\HTTP::addURLParameters($this->data['clientForm'], array('clientId' => $client['id']))); ?> "> <?php echo htmlspecialchars($client['id']); ?> </a> </td> <td> <?php echo $this->t('{oauth2server:oauth2server:client_description_' . $client['id'] . '}'); ?> </td> <td><?php echo htmlspecialchars(date("Y-m-d H:i:s", $client['expire'])); ?>
/** * Retrieve the absolute path pointing to the SimpleSAMLphp installation. * * The path is guaranteed to start and end with a slash ('/'). E.g.: /simplesaml/ * * @return string The absolute path where SimpleSAMLphp can be reached in the web server. * * @throws SimpleSAML\Error\CriticalConfigurationError If the format of 'baseurlpath' is incorrect. */ public function getBasePath() { $baseURL = $this->getString('baseurlpath', 'simplesaml/'); if (preg_match('#^https?://[^/]*(?:/(.+/?)?)?$#', $baseURL, $matches)) { // we have a full url, we need to strip the path if (!array_key_exists(1, $matches)) { // absolute URL without path return '/'; } return '/' . rtrim($matches[1], '/') . "/"; } elseif ($baseURL === '' || $baseURL === '/') { // root directory of site return '/'; } elseif (preg_match('#^/?((?:[^/\\s]+/?)+)#', $baseURL, $matches)) { // local path only return '/' . rtrim($matches[1], '/') . '/'; } else { /* * Invalid 'baseurlpath'. We cannot recover from this, so throw a critical exception and try to be graceful * with the configuration. Use a guessed base path instead of the one provided. */ $c = $this->toArray(); $c['baseurlpath'] = SimpleSAML\Utils\HTTP::guessBasePath(); throw new SimpleSAML\Error\CriticalConfigurationError('Incorrect format for option \'baseurlpath\'. Value is: "' . $this->getString('baseurlpath', 'simplesaml/') . '". Valid format is in the form' . ' [(http|https)://(hostname|fqdn)[:port]]/[path/to/simplesaml/].', $this->filename, $c); } }