diff --git a/lib/SimpleSAML/Auth/ProcessingChain.php b/lib/SimpleSAML/Auth/ProcessingChain.php index 832ab7f707b47e0ccb0fb244fc89f989eb7ddf70..1477203f73d366b8e0aa9463e3f6b6bb92f933cc 100644 --- a/lib/SimpleSAML/Auth/ProcessingChain.php +++ b/lib/SimpleSAML/Auth/ProcessingChain.php @@ -1,4 +1,5 @@ <?php + /** * Class for implementing authentication processing chains for IdPs. * @@ -6,31 +7,38 @@ * submitting a response to a SP. Examples of additional steps can be additional authentication * checks, or attribute consent requirements. * + * @author Olav Morken, UNINETT AS. * @package SimpleSAMLphp */ class SimpleSAML_Auth_ProcessingChain { + + /** * The list of remaining filters which should be applied to the state. */ const FILTERS_INDEX = 'SimpleSAML_Auth_ProcessingChain.filters'; + /** * The stage we use for completed requests. */ const COMPLETED_STAGE = 'SimpleSAML_Auth_ProcessingChain.completed'; + /** * The request parameter we will use to pass the state identifier when we redirect after * having completed processing of the state. */ const AUTHPARAM = 'AuthProcId'; + /** * All authentication processing filters, in the order they should be applied. */ private $filters; + /** * Initialize an authentication processing chain for the given service provider * and identity provider. @@ -38,8 +46,11 @@ class SimpleSAML_Auth_ProcessingChain * @param array $idpMetadata The metadata for the IdP. * @param array $spMetadata The metadata for the SP. */ - public function __construct(array $idpMetadata, array $spMetadata, $mode = 'idp') + public function __construct($idpMetadata, $spMetadata, $mode = 'idp') { + assert(is_array($idpMetadata)); + assert(is_array($spMetadata)); + $this->filters = array(); $config = SimpleSAML_Configuration::getInstance(); @@ -60,10 +71,12 @@ class SimpleSAML_Auth_ProcessingChain self::addFilters($this->filters, $spFilters); } + SimpleSAML\Logger::debug('Filter config for ' . $idpMetadata['entityid'] . '->' . $spMetadata['entityid'] . ': ' . str_replace("\n", '', var_export($this->filters, true))); } + /** * Sort & merge filter configuration * @@ -72,8 +85,11 @@ class SimpleSAML_Auth_ProcessingChain * @param array &$target Target filter list. This list must be sorted. * @param array $src Source filters. May be unsorted. */ - private static function addFilters(array &$target, array $src) + private static function addFilters(&$target, $src) { + assert(is_array($target)); + assert(is_array($src)); + foreach ($src as $filter) { $fp = $filter->priority; @@ -89,14 +105,17 @@ class SimpleSAML_Auth_ProcessingChain } } + /** * Parse an array of authentication processing filters. * * @param array $filterSrc Array with filter configuration. * @return array Array of SimpleSAML_Auth_ProcessingFilter objects. */ - private static function parseFilterList(array $filterSrc) + private static function parseFilterList($filterSrc) { + assert(is_array($filterSrc)); + $parsedFilters = array(); foreach ($filterSrc as $priority => $filter) { @@ -115,6 +134,7 @@ class SimpleSAML_Auth_ProcessingChain return $parsedFilters; } + /** * Parse an authentication processing filter. * @@ -123,8 +143,10 @@ class SimpleSAML_Auth_ProcessingChain * definition.) * @return SimpleSAML_Auth_ProcessingFilter The parsed filter. */ - private static function parseFilter(array $config, $priority) + private static function parseFilter($config, $priority) { + assert(is_array($config)); + if (!array_key_exists('class', $config)) { throw new Exception('Authentication processing filter without name given.'); } @@ -135,6 +157,7 @@ class SimpleSAML_Auth_ProcessingChain return new $className($config, null); } + /** * Process the given state. * @@ -155,7 +178,7 @@ class SimpleSAML_Auth_ProcessingChain * * @param array &$state The state we are processing. */ - public function processState(array &$state) + public function processState(&$state) { assert(is_array($state)); assert(array_key_exists('ReturnURL', $state) || array_key_exists('ReturnCall', $state)); @@ -188,6 +211,7 @@ class SimpleSAML_Auth_ProcessingChain // Completed } + /** * Continues processing of the state. * @@ -199,8 +223,10 @@ class SimpleSAML_Auth_ProcessingChain * * @param array $state The state we are processing. */ - public static function resumeProcessing(array $state) + public static function resumeProcessing($state) { + assert(is_array($state)); + while (count($state[self::FILTERS_INDEX]) > 0) { $filter = array_shift($state[self::FILTERS_INDEX]); try { @@ -218,6 +244,7 @@ class SimpleSAML_Auth_ProcessingChain assert(array_key_exists('ReturnURL', $state) || array_key_exists('ReturnCall', $state)); assert(!array_key_exists('ReturnURL', $state) || !array_key_exists('ReturnCall', $state)); + if (array_key_exists('ReturnURL', $state)) { /* * Save state information, and redirect to the URL specified @@ -239,6 +266,7 @@ class SimpleSAML_Auth_ProcessingChain } } + /** * Process the given state passivly. * @@ -249,8 +277,9 @@ class SimpleSAML_Auth_ProcessingChain * * @param array &$state The state we are processing. */ - public function processStatePassive(array &$state) + public function processStatePassive(&$state) { + assert(is_array($state)); // Should not be set when calling this method assert(!array_key_exists('ReturnURL', $state)); diff --git a/lib/SimpleSAML/Auth/ProcessingFilter.php b/lib/SimpleSAML/Auth/ProcessingFilter.php index 9833e586e01e6cb3cc2d178b9a0895e447696871..e6126da1de01bd040d39c5a8feff6f813761b290 100644 --- a/lib/SimpleSAML/Auth/ProcessingFilter.php +++ b/lib/SimpleSAML/Auth/ProcessingFilter.php @@ -1,4 +1,6 @@ <?php + + /** * Base class for authentication processing filters. * @@ -13,10 +15,12 @@ * information in it, it should have a name on the form 'module:filter:attributename', to avoid name * collisions. * + * @author Olav Morken, UNINETT AS. * @package SimpleSAMLphp */ abstract class SimpleSAML_Auth_ProcessingFilter { + /** * Priority of this filter. * @@ -28,6 +32,7 @@ abstract class SimpleSAML_Auth_ProcessingFilter */ public $priority = 50; + /** * Constructor for a processing filter. * @@ -37,8 +42,10 @@ abstract class SimpleSAML_Auth_ProcessingFilter * @param array &$config Configuration for this filter. * @param mixed $reserved For future use. */ - public function __construct(array &$config, $reserved) + public function __construct(&$config, $reserved) { + assert(is_array($config)); + if (array_key_exists('%priority', $config)) { $this->priority = $config['%priority']; if (!is_int($this->priority)) { @@ -48,6 +55,7 @@ abstract class SimpleSAML_Auth_ProcessingFilter } } + /** * Process a request. * @@ -55,5 +63,5 @@ abstract class SimpleSAML_Auth_ProcessingFilter * * @param array &$request The request we are currently processing. */ - abstract public function process(array &$request); + abstract public function process(&$request); } diff --git a/lib/SimpleSAML/Auth/Simple.php b/lib/SimpleSAML/Auth/Simple.php index fffd73a756f47a93f5dd624e1fec4d735cccd621..9ad8e86a2d575cc8ab3a5edd289c4b4266ae8fc9 100644 --- a/lib/SimpleSAML/Auth/Simple.php +++ b/lib/SimpleSAML/Auth/Simple.php @@ -17,6 +17,7 @@ use \SimpleSAML\Utils\HTTP; */ class Simple { + /** * The id of the authentication source we are accessing. * @@ -218,6 +219,7 @@ class Simple self::logoutCompleted($params); } + /** * Called when logout operation completes. * @@ -225,8 +227,9 @@ class Simple * * @param array $state The state after the logout. */ - public static function logoutCompleted(array $state) + public static function logoutCompleted($state) { + assert(is_array($state)); assert(isset($state['ReturnTo']) || isset($state['ReturnCallback'])); if (isset($state['ReturnCallback'])) { @@ -243,6 +246,7 @@ class Simple } } + /** * Retrieve attributes of the current user. * @@ -253,6 +257,7 @@ class Simple */ public function getAttributes() { + if (!$this->isAuthenticated()) { // Not authenticated return array(); @@ -263,6 +268,7 @@ class Simple return $session->getAuthData($this->authSource, 'Attributes'); } + /** * Retrieve authentication data. * @@ -282,6 +288,7 @@ class Simple return $session->getAuthData($this->authSource, $name); } + /** * Retrieve all authentication data. * @@ -289,6 +296,7 @@ class Simple */ public function getAuthDataArray() { + if (!$this->isAuthenticated()) { return null; } @@ -297,6 +305,7 @@ class Simple return $session->getAuthState($this->authSource); } + /** * Retrieve a URL that can be used to log the user in. * @@ -321,6 +330,7 @@ class Simple return $login; } + /** * Retrieve a URL that can be used to log the user out. * @@ -345,6 +355,7 @@ class Simple return $logout; } + /** * Process a URL and modify it according to the application/baseURL configuration option, if present. * diff --git a/lib/SimpleSAML/Auth/Source.php b/lib/SimpleSAML/Auth/Source.php index 9bb14ee8bce881052cfe6b3cfcb37adcc2e483fe..44cd69a727cb0788a46837ef38a3725785c69275 100644 --- a/lib/SimpleSAML/Auth/Source.php +++ b/lib/SimpleSAML/Auth/Source.php @@ -7,10 +7,13 @@ use SimpleSAML\Auth\SourceFactory; * * An authentication source is any system which somehow authenticate the user. * + * @author Olav Morken, UNINETT AS. * @package SimpleSAMLphp */ abstract class SimpleSAML_Auth_Source { + + /** * The authentication source identifier. This identifier can be used to look up this object, for example when * returning from a login form. @@ -19,6 +22,7 @@ abstract class SimpleSAML_Auth_Source */ protected $authId; + /** * Constructor for an authentication source. * @@ -28,12 +32,16 @@ abstract class SimpleSAML_Auth_Source * @param array $info Information about this authentication source. * @param array &$config Configuration for this authentication source. */ - public function __construct(array $info, array &$config) + public function __construct($info, &$config) { + assert(is_array($info)); + assert(is_array($config)); + assert(array_key_exists('AuthId', $info)); $this->authId = $info['AuthId']; } + /** * Get sources of a specific type. * @@ -77,6 +85,7 @@ abstract class SimpleSAML_Auth_Source return $this->authId; } + /** * Process a request. * @@ -91,10 +100,11 @@ abstract class SimpleSAML_Auth_Source * * @param array &$state Information about the current authentication. */ - abstract public function authenticate(array &$state); + abstract public function authenticate(&$state); + /** - * Reauthenticate a user. + * Reauthenticate an user. * * This function is called by the IdP to give the authentication source a chance to * interact with the user even in the case when the user is already authenticated. @@ -113,6 +123,7 @@ abstract class SimpleSAML_Auth_Source } } + /** * Complete authentication. * @@ -122,8 +133,9 @@ abstract class SimpleSAML_Auth_Source * * @param array &$state Information about the current authentication. */ - public static function completeAuth(array &$state) + public static function completeAuth(&$state) { + assert(is_array($state)); assert(array_key_exists('LoginCompletedHandler', $state)); SimpleSAML_Auth_State::deleteState($state); @@ -135,6 +147,7 @@ abstract class SimpleSAML_Auth_Source assert(false); } + /** * Start authentication. * @@ -188,6 +201,7 @@ abstract class SimpleSAML_Auth_Source self::loginCompleted($state); } + /** * Called when a login operation has finished. * @@ -195,8 +209,9 @@ abstract class SimpleSAML_Auth_Source * * @param array $state The state after the login has completed. */ - public static function loginCompleted(array $state) + public static function loginCompleted($state) { + assert(is_array($state)); assert(array_key_exists('SimpleSAML_Auth_Source.Return', $state)); assert(array_key_exists('SimpleSAML_Auth_Source.id', $state)); assert(array_key_exists('Attributes', $state)); @@ -217,6 +232,7 @@ abstract class SimpleSAML_Auth_Source assert(false); } + /** * Log out from this authentication source. * @@ -230,8 +246,9 @@ abstract class SimpleSAML_Auth_Source * * @param array &$state Information about the current logout operation. */ - public function logout(array &$state) + public function logout(&$state) { + assert(is_array($state)); // default logout handler which doesn't do anything } @@ -245,8 +262,9 @@ abstract class SimpleSAML_Auth_Source * * @param array &$state Information about the current authentication. */ - public static function completeLogout(array &$state) + public static function completeLogout(&$state) { + assert(is_array($state)); assert(array_key_exists('LogoutCompletedHandler', $state)); SimpleSAML_Auth_State::deleteState($state); @@ -258,6 +276,7 @@ abstract class SimpleSAML_Auth_Source assert(false); } + /** * Create authentication source object from configuration array. * @@ -270,9 +289,10 @@ abstract class SimpleSAML_Auth_Source * @return SimpleSAML_Auth_Source The parsed authentication source. * @throws Exception If the authentication source is invalid. */ - private static function parseAuthSource($authId, array $config) + private static function parseAuthSource($authId, $config) { assert(is_string($authId)); + assert(is_array($config)); self::validateSource($config, $authId); @@ -298,6 +318,7 @@ abstract class SimpleSAML_Auth_Source return $authSource; } + /** * Retrieve authentication source. * @@ -349,13 +370,15 @@ abstract class SimpleSAML_Auth_Source ); } + /** * Called when the authentication source receives an external logout request. * * @param array $state State array for the logout operation. */ - public static function logoutCallback(array $state) + public static function logoutCallback($state) { + assert(is_array($state)); assert(array_key_exists('SimpleSAML_Auth_Source.logoutSource', $state)); $source = $state['SimpleSAML_Auth_Source.logoutSource']; @@ -372,6 +395,7 @@ abstract class SimpleSAML_Auth_Source $session->doLogout($source); } + /** * Add a logout callback association. * @@ -384,9 +408,10 @@ abstract class SimpleSAML_Auth_Source * @param string $assoc The identifier for this logout association. * @param array $state The state array passed to the authenticate-function. */ - protected function addLogoutCallback($assoc, array $state) + protected function addLogoutCallback($assoc, $state) { assert(is_string($assoc)); + assert(is_array($state)); if (!array_key_exists('LogoutCallback', $state)) { // the authentication requester doesn't have a logout callback @@ -416,6 +441,7 @@ abstract class SimpleSAML_Auth_Source ); } + /** * Call a logout callback based on association. * @@ -453,6 +479,7 @@ abstract class SimpleSAML_Auth_Source call_user_func($callback, $callbackState); } + /** * Retrieve list of authentication sources. * @@ -474,7 +501,7 @@ abstract class SimpleSAML_Auth_Source * * @throws Exception If the first element of $source is not an identifier for the auth source. */ - protected static function validateSource(array $source, $id) + protected static function validateSource($source, $id) { if (!array_key_exists(0, $source) || !is_string($source[0])) { throw new Exception( diff --git a/lib/SimpleSAML/Auth/State.php b/lib/SimpleSAML/Auth/State.php index f86657b4fa6a4d945e029aeaf9b0d4017698106a..06bee7ae8e48058d0e5f9cffd29d0fc2f857373f 100644 --- a/lib/SimpleSAML/Auth/State.php +++ b/lib/SimpleSAML/Auth/State.php @@ -1,5 +1,6 @@ <?php + /** * This is a helper class for saving and loading state information. * @@ -24,61 +25,74 @@ * be passed to the handler defined by the EXCEPTION_HANDLER_URL or EXCEPTION_HANDLER_FUNC * elements of the state array. * + * @author Olav Morken, UNINETT AS. * @package SimpleSAMLphp */ class SimpleSAML_Auth_State { + + /** * The index in the state array which contains the identifier. */ const ID = 'SimpleSAML_Auth_State.id'; + /** * The index in the cloned state array which contains the identifier of the * original state. */ const CLONE_ORIGINAL_ID = 'SimpleSAML_Auth_State.cloneOriginalId'; + /** * The index in the state array which contains the current stage. */ const STAGE = 'SimpleSAML_Auth_State.stage'; + /** * The index in the state array which contains the restart URL. */ const RESTART = 'SimpleSAML_Auth_State.restartURL'; + /** * The index in the state array which contains the exception handler URL. */ const EXCEPTION_HANDLER_URL = 'SimpleSAML_Auth_State.exceptionURL'; + /** * The index in the state array which contains the exception handler function. */ const EXCEPTION_HANDLER_FUNC = 'SimpleSAML_Auth_State.exceptionFunc'; + /** * The index in the state array which contains the exception data. */ const EXCEPTION_DATA = 'SimpleSAML_Auth_State.exceptionData'; + /** * The stage of a state with an exception. */ const EXCEPTION_STAGE = 'SimpleSAML_Auth_State.exceptionStage'; + /** * The URL parameter which contains the exception state id. */ const EXCEPTION_PARAM = 'SimpleSAML_Auth_State_exceptionId'; + /** * State timeout. */ private static $stateTimeout = null; + /** * Get the persistent authentication state from the state array. * @@ -117,6 +131,7 @@ class SimpleSAML_Auth_State return $persistent; } + /** * Retrieve the ID of a state array. * @@ -127,8 +142,9 @@ class SimpleSAML_Auth_State * * @return string Identifier which can be used to retrieve the state later. */ - public static function getStateId(array &$state, $rawId = false) + public static function getStateId(&$state, $rawId = false) { + assert(is_array($state)); assert(is_bool($rawId)); if (!array_key_exists(self::ID, $state)) { @@ -146,6 +162,7 @@ class SimpleSAML_Auth_State return $id.':'.$state[self::RESTART]; } + /** * Retrieve state timeout. * @@ -161,6 +178,7 @@ class SimpleSAML_Auth_State return self::$stateTimeout; } + /** * Save the state. * @@ -173,8 +191,9 @@ class SimpleSAML_Auth_State * * @return string Identifier which can be used to retrieve the state later. */ - public static function saveState(array &$state, $stage, $rawId = false) + public static function saveState(&$state, $stage, $rawId = false) { + assert(is_array($state)); assert(is_string($stage)); assert(is_bool($rawId)); @@ -194,6 +213,7 @@ class SimpleSAML_Auth_State return $return; } + /** * Clone the state. * @@ -219,6 +239,7 @@ class SimpleSAML_Auth_State return $clonedState; } + /** * Retrieve saved state. * @@ -287,6 +308,7 @@ class SimpleSAML_Auth_State return $state; } + /** * Delete state. * @@ -294,8 +316,10 @@ class SimpleSAML_Auth_State * * @param array &$state The state which should be deleted. */ - public static function deleteState(array &$state) + public static function deleteState(&$state) { + assert(is_array($state)); + if (!array_key_exists(self::ID, $state)) { // This state hasn't been saved return; @@ -307,6 +331,7 @@ class SimpleSAML_Auth_State $session->deleteData('SimpleSAML_Auth_State', $state[self::ID]); } + /** * Throw exception to the state exception handler. * @@ -315,8 +340,10 @@ class SimpleSAML_Auth_State * * @throws SimpleSAML_Error_Exception If there is no exception handler defined, it will just throw the $exception. */ - public static function throwException(array $state, SimpleSAML_Error_Exception $exception) + public static function throwException($state, SimpleSAML_Error_Exception $exception) { + assert(is_array($state)); + if (array_key_exists(self::EXCEPTION_HANDLER_URL, $state)) { // Save the exception $state[self::EXCEPTION_DATA] = $exception; @@ -342,6 +369,7 @@ class SimpleSAML_Auth_State } } + /** * Retrieve an exception state. * @@ -367,6 +395,7 @@ class SimpleSAML_Auth_State return $state; } + /** * Get the ID and (optionally) a URL embedded in a StateID, in the form 'id:url'. * @@ -374,6 +403,9 @@ class SimpleSAML_Auth_State * * @return array A hashed array with the ID and the URL (if any), in the 'id' and 'url' keys, respectively. If * there's no URL in the input parameter, NULL will be returned as the value for the 'url' key. + * + * @author Andreas Solberg, UNINETT AS <andreas.solberg@uninett.no> + * @author Jaime Perez, UNINETT AS <jaime.perez@uninett.no> */ public static function parseStateID($stateId) { diff --git a/modules/authX509/lib/Auth/Process/ExpiryWarning.php b/modules/authX509/lib/Auth/Process/ExpiryWarning.php index ece6156ab6bb1e1e0163109100e8d54538dd46d9..0a6fe5bf9bb48df307d7baa78ff918c83762f179 100644 --- a/modules/authX509/lib/Auth/Process/ExpiryWarning.php +++ b/modules/authX509/lib/Auth/Process/ExpiryWarning.php @@ -11,6 +11,7 @@ * ), * </code> * + * @author Joost van Dijk, SURFnet. <Joost.vanDijk@surfnet.nl> * @package SimpleSAMLphp */ class sspmod_authX509_Auth_Process_ExpiryWarning extends SimpleSAML_Auth_ProcessingFilter @@ -25,10 +26,12 @@ class sspmod_authX509_Auth_Process_ExpiryWarning extends SimpleSAML_Auth_Process * @param array $config Configuration information about this filter. * @param mixed $reserved For future use. */ - public function __construct(array $config, $reserved) + public function __construct($config, $reserved) { parent::__construct($config, $reserved); + assert(is_array($config)); + if (array_key_exists('warndaysbefore', $config)) { $this->warndaysbefore = $config['warndaysbefore']; if (!is_string($this->warndaysbefore)) { @@ -52,8 +55,10 @@ class sspmod_authX509_Auth_Process_ExpiryWarning extends SimpleSAML_Auth_Process * * @param array $state The state of the response. */ - public function process(array &$state) + public function process(&$state) { + assert(is_array($state)); + if (isset($state['isPassive']) && $state['isPassive'] === true) { // We have a passive request. Skip the warning return; diff --git a/modules/authX509/lib/Auth/Source/X509userCert.php b/modules/authX509/lib/Auth/Source/X509userCert.php index ac90b07222d272c29f48074e732463d4101797d3..36f93a48f7a11d6c1d660132a3e83622d7f42a77 100644 --- a/modules/authX509/lib/Auth/Source/X509userCert.php +++ b/modules/authX509/lib/Auth/Source/X509userCert.php @@ -35,8 +35,11 @@ class sspmod_authX509_Auth_Source_X509userCert extends SimpleSAML_Auth_Source * @param array $info Information about this authentication source. * @param array &$config Configuration for this authentication source. */ - public function __construct(array $info, array &$config) + public function __construct($info, &$config) { + assert(is_array($info)); + assert(is_array($config)); + if (isset($config['authX509:x509attributes'])) { $this->x509attributes = $config['authX509:x509attributes']; } @@ -63,7 +66,7 @@ class sspmod_authX509_Auth_Source_X509userCert extends SimpleSAML_Auth_Source * * @param array &$state Information about the current authentication. */ - public function authFailed(array &$state) + public function authFailed(&$state) { $config = SimpleSAML_Configuration::getInstance(); @@ -84,8 +87,9 @@ class sspmod_authX509_Auth_Source_X509userCert extends SimpleSAML_Auth_Source * * @param array &$state Information about the current authentication. */ - public function authenticate(array &$state) + public function authenticate(&$state) { + assert(is_array($state)); $ldapcf = $this->ldapcf; if (!isset($_SERVER['SSL_CLIENT_CERT']) || @@ -192,7 +196,7 @@ class sspmod_authX509_Auth_Source_X509userCert extends SimpleSAML_Auth_Source * * @param array &$state Information about the current authentication. */ - public function authSuccesful(array &$state) + public function authSuccesful(&$state) { SimpleSAML_Auth_Source::completeAuth($state); diff --git a/modules/authYubiKey/lib/Auth/Source/YubiKey.php b/modules/authYubiKey/lib/Auth/Source/YubiKey.php index 88607a541cbbccde9046669b1f9327f04c9e1c03..2d19aa507d2e0d52b675c254a01f37d0593e774e 100644 --- a/modules/authYubiKey/lib/Auth/Source/YubiKey.php +++ b/modules/authYubiKey/lib/Auth/Source/YubiKey.php @@ -1,4 +1,28 @@ <?php + +/* + * Copyright (C) 2009 Andreas Åkre Solberg <andreas.solberg@uninett.no> + * Copyright (C) 2009 Simon Josefsson <simon@yubico.com>. + * + * This file is part of SimpleSAMLphp + * + * SimpleSAMLphp is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public License + * as published by the Free Software Foundation; either version 3 of + * the License, or (at your option) any later version. + * + * SimpleSAMLphp 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License License along with GNU SASL Library; if not, write to the + * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + * + */ + /** * YubiKey authentication module, see http://www.yubico.com/developers/intro/ * * @@ -46,8 +70,11 @@ class sspmod_authYubiKey_Auth_Source_YubiKey extends SimpleSAML_Auth_Source * @param array $info Information about this authentication source. * @param array $config Configuration. */ - public function __construct(array $info, array $config) + public function __construct($info, $config) { + assert(is_array($info)); + assert(is_array($config)); + // Call the parent constructor first, as required by the interface parent::__construct($info, $config); @@ -69,8 +96,10 @@ class sspmod_authYubiKey_Auth_Source_YubiKey extends SimpleSAML_Auth_Source * * @param array &$state Information about the current authentication. */ - public function authenticate(array &$state) + public function authenticate(&$state) { + assert(is_array($state)); + // We are going to need the authId in order to retrieve this authentication source later $state[self::AUTHID] = $this->authId; diff --git a/modules/authcrypt/lib/Auth/Source/Hash.php b/modules/authcrypt/lib/Auth/Source/Hash.php index 2a7bb4433f79698b138187a25e7f3f385c904bee..1aca115745fddf89ddbfb2d4951cc8b827021594 100644 --- a/modules/authcrypt/lib/Auth/Source/Hash.php +++ b/modules/authcrypt/lib/Auth/Source/Hash.php @@ -1,20 +1,26 @@ <?php + + /** * Authentication source for username & hashed password. * * This class is an authentication source which stores all username/hashes in an array, * and authenticates users against this array. * + * @author Dyonisius Visser, TERENA. * @package SimpleSAMLphp */ class sspmod_authcrypt_Auth_Source_Hash extends sspmod_core_Auth_UserPassBase { + + /** * Our users, stored in an associative array. The key of the array is "<username>:<passwordhash>", * while the value of each element is a new array with the attributes for each user. */ private $users; + /** * Constructor for this authentication source. * @@ -23,8 +29,11 @@ class sspmod_authcrypt_Auth_Source_Hash extends sspmod_core_Auth_UserPassBase * * @throws Exception in case of a configuration error. */ - public function __construct(array $info, array $config) + public function __construct($info, $config) { + assert(is_array($info)); + assert(is_array($config)); + // Call the parent constructor first, as required by the interface parent::__construct($info, $config); @@ -57,6 +66,7 @@ class sspmod_authcrypt_Auth_Source_Hash extends sspmod_core_Auth_UserPassBase } } + /** * Attempt to log in using the given username and password. * diff --git a/modules/authcrypt/lib/Auth/Source/Htpasswd.php b/modules/authcrypt/lib/Auth/Source/Htpasswd.php index 56e05d0d8e526c5d9ba135b49b2c63382f705db0..84bc7ea3efdd1fc0d05d2eacaab6c4e755eada19 100644 --- a/modules/authcrypt/lib/Auth/Source/Htpasswd.php +++ b/modules/authcrypt/lib/Auth/Source/Htpasswd.php @@ -1,7 +1,9 @@ <?php + /** * Authentication source for Apache 'htpasswd' files. * + * @author Dyonisius (Dick) Visser, TERENA. * @package SimpleSAMLphp */ @@ -9,6 +11,8 @@ use WhiteHat101\Crypt\APR1_MD5; class sspmod_authcrypt_Auth_Source_Htpasswd extends sspmod_core_Auth_UserPassBase { + + /** * Our users, stored in an array, where each value is "<username>:<passwordhash>". * @@ -23,6 +27,7 @@ class sspmod_authcrypt_Auth_Source_Htpasswd extends sspmod_core_Auth_UserPassBas */ private $attributes = array(); + /** * Constructor for this authentication source. * @@ -31,8 +36,11 @@ class sspmod_authcrypt_Auth_Source_Htpasswd extends sspmod_core_Auth_UserPassBas * * @throws Exception if the htpasswd file is not readable or the static_attributes array is invalid. */ - public function __construct(array $info, array $config) + public function __construct($info, $config) { + assert(is_array($info)); + assert(is_array($config)); + // Call the parent constructor first, as required by the interface parent::__construct($info, $config); @@ -52,6 +60,7 @@ class sspmod_authcrypt_Auth_Source_Htpasswd extends sspmod_core_Auth_UserPassBas } } + /** * Attempt to log in using the given username and password. * diff --git a/modules/authfacebook/lib/Auth/Source/Facebook.php b/modules/authfacebook/lib/Auth/Source/Facebook.php index 8a7684b0ef7989e334d9d66caa4f8413fc8d82f4..865e152c38db35e7569b7678e3ea4ce627c76c56 100644 --- a/modules/authfacebook/lib/Auth/Source/Facebook.php +++ b/modules/authfacebook/lib/Auth/Source/Facebook.php @@ -1,125 +1,143 @@ <?php + /** * Authenticate using Facebook Platform. * + * @author Andreas Åkre Solberg, UNINETT AS. * @package SimpleSAMLphp */ -class sspmod_authfacebook_Auth_Source_Facebook extends SimpleSAML_Auth_Source -{ - /** - * The string used to identify our states. - */ - const STAGE_INIT = 'facebook:init'; - - /** - * The key of the AuthId field in the state. - */ - const AUTHID = 'facebook:AuthId'; - - /** - * Facebook App ID or API Key - */ - private $api_key; - - /** - * Facebook App Secret - */ - private $secret; - - /** - * Which additional data permissions to request from user - */ - private $req_perms; - - /** - * A comma-separated list of user profile fields to request. - * - * Note that some user fields require appropriate permissions. For - * example, to retrieve the user's primary email address, "email" must - * be specified in both the req_perms and the user_fields parameter. - * - * When empty, only the app-specific user id and name will be returned. - * - * See the Graph API specification for all available user fields: - * https://developers.facebook.com/docs/graph-api/reference/v2.6/user - */ - private $user_fields; - - /** - * Constructor for this authentication source. - * - * @param array $info Information about this authentication source. - * @param array $config Configuration. - */ - public function __construct(array $info, array $config) - { - // Call the parent constructor first, as required by the interface - parent::__construct($info, $config); - - $cfgParse = SimpleSAML_Configuration::loadFromArray($config, 'authsources[' . var_export($this->authId, true) . ']'); - - $this->api_key = $cfgParse->getString('api_key'); - $this->secret = $cfgParse->getString('secret'); - $this->req_perms = $cfgParse->getString('req_perms', null); - $this->user_fields = $cfgParse->getString('user_fields', null); - } - - /** - * Log-in using Facebook platform - * - * @param array &$state Information about the current authentication. - */ - public function authenticate(array &$state) { - // We are going to need the authId in order to retrieve this authentication source later - $state[self::AUTHID] = $this->authId; - SimpleSAML_Auth_State::saveState($state, self::STAGE_INIT); - - $facebook = new sspmod_authfacebook_Facebook(array('appId' => $this->api_key, 'secret' => $this->secret), $state); - $facebook->destroySession(); - - $linkback = SimpleSAML\Module::getModuleURL('authfacebook/linkback.php'); - $url = $facebook->getLoginUrl(array('redirect_uri' => $linkback, 'scope' => $this->req_perms)); - SimpleSAML_Auth_State::saveState($state, self::STAGE_INIT); - - \SimpleSAML\Utils\HTTP::redirectTrustedURL($url); - } - - public function finalStep(array &$state) { - $facebook = new sspmod_authfacebook_Facebook(array('appId' => $this->api_key, 'secret' => $this->secret), $state); - $uid = $facebook->getUser(); - - if (isset($uid) && $uid) { - try { - $info = $facebook->api("/" . $uid . ($this->user_fields ? "?fields=" . $this->user_fields : "")); - } catch (FacebookApiException $e) { - throw new SimpleSAML_Error_AuthSource($this->authId, 'Error getting user profile.', $e); - } - } - - if (!isset($info)) { - throw new SimpleSAML_Error_AuthSource($this->authId, 'Error getting user profile.'); - } - - $attributes = array(); - foreach($info AS $key => $value) { - if (is_string($value) && !empty($value)) { - $attributes['facebook.' . $key] = array((string)$value); - } - } - - if (array_key_exists('third_party_id', $info)) { - $attributes['facebook_user'] = array($info['third_party_id'] . '@facebook.com'); - } else { - $attributes['facebook_user'] = array($uid . '@facebook.com'); - } - - $attributes['facebook_targetedID'] = array('http://facebook.com!' . $uid); - $attributes['facebook_cn'] = array($info['name']); - - SimpleSAML\Logger::debug('Facebook Returned Attributes: '. implode(", ", array_keys($attributes))); - - $state['Attributes'] = $attributes; - - $facebook->destroySession(); - } +class sspmod_authfacebook_Auth_Source_Facebook extends SimpleSAML_Auth_Source { + + + /** + * The string used to identify our states. + */ + const STAGE_INIT = 'facebook:init'; + + + /** + * The key of the AuthId field in the state. + */ + const AUTHID = 'facebook:AuthId'; + + + /** + * Facebook App ID or API Key + */ + private $api_key; + + + /** + * Facebook App Secret + */ + private $secret; + + + /** + * Which additional data permissions to request from user + */ + private $req_perms; + + + /** + * A comma-separated list of user profile fields to request. + * + * Note that some user fields require appropriate permissions. For + * example, to retrieve the user's primary email address, "email" must + * be specified in both the req_perms and the user_fields parameter. + * + * When empty, only the app-specific user id and name will be returned. + * + * See the Graph API specification for all available user fields: + * https://developers.facebook.com/docs/graph-api/reference/v2.6/user + */ + private $user_fields; + + + /** + * Constructor for this authentication source. + * + * @param array $info Information about this authentication source. + * @param array $config Configuration. + */ + public function __construct($info, $config) { + assert(is_array($info)); + assert(is_array($config)); + + // Call the parent constructor first, as required by the interface + parent::__construct($info, $config); + + $cfgParse = SimpleSAML_Configuration::loadFromArray($config, 'authsources[' . var_export($this->authId, TRUE) . ']'); + + $this->api_key = $cfgParse->getString('api_key'); + $this->secret = $cfgParse->getString('secret'); + $this->req_perms = $cfgParse->getString('req_perms', NULL); + $this->user_fields = $cfgParse->getString('user_fields', NULL); + } + + + /** + * Log-in using Facebook platform + * + * @param array &$state Information about the current authentication. + */ + public function authenticate(&$state) { + assert(is_array($state)); + + // We are going to need the authId in order to retrieve this authentication source later + $state[self::AUTHID] = $this->authId; + SimpleSAML_Auth_State::saveState($state, self::STAGE_INIT); + + $facebook = new sspmod_authfacebook_Facebook(array('appId' => $this->api_key, 'secret' => $this->secret), $state); + $facebook->destroySession(); + + $linkback = SimpleSAML\Module::getModuleURL('authfacebook/linkback.php'); + $url = $facebook->getLoginUrl(array('redirect_uri' => $linkback, 'scope' => $this->req_perms)); + SimpleSAML_Auth_State::saveState($state, self::STAGE_INIT); + + \SimpleSAML\Utils\HTTP::redirectTrustedURL($url); + } + + + public function finalStep(&$state) { + assert(is_array($state)); + + $facebook = new sspmod_authfacebook_Facebook(array('appId' => $this->api_key, 'secret' => $this->secret), $state); + $uid = $facebook->getUser(); + + if (isset($uid) && $uid) { + try { + $info = $facebook->api("/" . $uid . ($this->user_fields ? "?fields=" . $this->user_fields : "")); + } catch (FacebookApiException $e) { + throw new SimpleSAML_Error_AuthSource($this->authId, 'Error getting user profile.', $e); + } + } + + if (!isset($info)) { + throw new SimpleSAML_Error_AuthSource($this->authId, 'Error getting user profile.'); + } + + $attributes = array(); + foreach($info AS $key => $value) { + if (is_string($value) && !empty($value)) { + $attributes['facebook.' . $key] = array((string)$value); + } + } + + if (array_key_exists('third_party_id', $info)) { + $attributes['facebook_user'] = array($info['third_party_id'] . '@facebook.com'); + } else { + $attributes['facebook_user'] = array($uid . '@facebook.com'); + } + + $attributes['facebook_targetedID'] = array('http://facebook.com!' . $uid); + $attributes['facebook_cn'] = array($info['name']); + + SimpleSAML\Logger::debug('Facebook Returned Attributes: '. implode(", ", array_keys($attributes))); + + $state['Attributes'] = $attributes; + + $facebook->destroySession(); + } + } diff --git a/modules/authlinkedin/lib/Auth/Source/LinkedIn.php b/modules/authlinkedin/lib/Auth/Source/LinkedIn.php index 5ef5b8ca1b394563cb6637fdda4e94edcffaa100..ff961df0c66492fe1d03c0ed10ceedb7f350aa16 100644 --- a/modules/authlinkedin/lib/Auth/Source/LinkedIn.php +++ b/modules/authlinkedin/lib/Auth/Source/LinkedIn.php @@ -5,10 +5,12 @@ require_once(dirname(dirname(dirname(dirname(dirname(__FILE__))))) . '/oauth/lib /** * Authenticate using LinkedIn. * + * @author Brook Schofield, TERENA. * @package SimpleSAMLphp */ class sspmod_authlinkedin_Auth_Source_LinkedIn extends SimpleSAML_Auth_Source { + /** * The string used to identify our states. */ @@ -30,8 +32,11 @@ class sspmod_authlinkedin_Auth_Source_LinkedIn extends SimpleSAML_Auth_Source * @param array $info Information about this authentication source. * @param array $config Configuration. */ - public function __construct(array $info, array $config) + public function __construct($info, $config) { + assert(is_array($info)); + assert(is_array($config)); + // Call the parent constructor first, as required by the interface parent::__construct($info, $config); @@ -53,14 +58,17 @@ class sspmod_authlinkedin_Auth_Source_LinkedIn extends SimpleSAML_Auth_Source } } + /** * Log-in using LinkedIn platform * Documentation at: http://developer.linkedin.com/docs/DOC-1008 * * @param array &$state Information about the current authentication. */ - public function authenticate(array &$state) + public function authenticate(&$state) { + assert(is_array($state)); + // We are going to need the authId in order to retrieve this authentication source later $state[self::AUTHID] = $this->authId; @@ -89,7 +97,8 @@ class sspmod_authlinkedin_Auth_Source_LinkedIn extends SimpleSAML_Auth_Source $consumer->getAuthorizeRequest('https://www.linkedin.com/uas/oauth/authenticate', $requestToken); } - public function finalStep(array &$state) + + public function finalStep(&$state) { $requestToken = $state['authlinkedin:requestToken']; @@ -158,7 +167,7 @@ class sspmod_authlinkedin_Auth_Source_LinkedIn extends SimpleSAML_Auth_Source * * @return array the array with the new concatenated keys */ - protected function flatten(array $array, $prefix = '') + protected function flatten($array, $prefix = '') { $result = array(); foreach ($array as $key => $value) { diff --git a/modules/authorize/lib/Auth/Process/Authorize.php b/modules/authorize/lib/Auth/Process/Authorize.php index c6c19fc6c99069e7cdf2568f1189b5659646dc64..68c5ad009f1f712359baf7878934847593e032af 100644 --- a/modules/authorize/lib/Auth/Process/Authorize.php +++ b/modules/authorize/lib/Auth/Process/Authorize.php @@ -1,129 +1,133 @@ <?php + /** * Filter to authorize only certain users. * See docs directory. * + * @author Ernesto Revilla, Yaco Sistemas SL., Ryan Panning * @package SimpleSAMLphp */ -class sspmod_authorize_Auth_Process_Authorize extends SimpleSAML_Auth_ProcessingFilter -{ - /** - * Flag to deny/unauthorize the user a attribute filter IS found - * - * @var bool - */ - protected $deny = false; - - /** - * Flag to turn the REGEX pattern matching on or off - * - * @var bool - */ - protected $regex = true; - - /** - * Array of valid users. Each element is a regular expression. You should - * user \ to escape special chars, like '.' etc. - * - */ - protected $valid_attribute_values = []; - - /** - * Initialize this filter. - * Validate configuration parameters. - * - * @param array $config Configuration information about this filter. - * @param mixed $reserved For future use. - */ - public function __construct(array $config, $reserved) - { - parent::__construct($config, $reserved); - - // Check for the deny option, get it and remove it - // Must be bool specifically, if not, it might be for a attrib filter below - if (isset($config['deny']) && is_bool($config['deny'])) { - $this->deny = $config['deny']; - unset($config['deny']); - } - - // Check for the regex option, get it and remove it - // Must be bool specifically, if not, it might be for a attrib filter below - if (isset($config['regex']) && is_bool($config['regex'])) { - $this->regex = $config['regex']; - unset($config['regex']); - } - - foreach ($config as $attribute => $values) { - if (is_string($values)) - $values = array($values); - if (!is_array($values)) - throw new Exception('Filter Authorize: Attribute values is neither string nor array: ' . var_export($attribute, true)); - foreach ($values as $value){ - if(!is_string($value)) { - throw new Exception('Filter Authorize: Each value should be a string for attribute: ' . var_export($attribute, true) . ' value: ' . var_export($value, true) . ' Config is: ' . var_export($config, true)); - } - } - $this->valid_attribute_values[$attribute] = $values; - } - } - - - /** - * Apply filter to validate attributes. - * - * @param array &$request The current request - */ - public function process(array &$request) - { - $authorize = $this->deny; - assert(array_key_exists('Attributes', $request)); - - $attributes =& $request['Attributes']; - - foreach ($this->valid_attribute_values as $name => $patterns) { - if(array_key_exists($name, $attributes)) { - foreach ($patterns as $pattern){ - $values = $attributes[$name]; - if (!is_array($values)) - $values = array($values); - foreach ($values as $value){ - if ($this->regex) { - $matched = preg_match($pattern, $value); - } else { - $matched = ($value == $pattern); - } - if ($matched) { - $authorize = ($this->deny ? false : true); - break 3; - } - } - } - } - } - if (!$authorize){ - $this->unauthorized($request); - } - } - - /** - * When the process logic determines that the user is not - * authorized for this service, then forward the user to - * an 403 unauthorized page. - * - * Separated this code into its own method so that child - * classes can override it and change the action. Forward - * thinking in case a "chained" ACL is needed, more complex - * permission logic. - * - * @param array $request - */ - protected function unauthorized(array &$request) - { - // Save state and redirect to 403 page - $id = SimpleSAML_Auth_State::saveState($request, - 'authorize:Authorize'); - $url = SimpleSAML\Module::getModuleURL( - 'authorize/authorize_403.php'); - \SimpleSAML\Utils\HTTP::redirectTrustedURL($url, array('StateId' => $id)); - } +class sspmod_authorize_Auth_Process_Authorize extends SimpleSAML_Auth_ProcessingFilter { + + /** + * Flag to deny/unauthorize the user a attribute filter IS found + * + * @var bool + */ + protected $deny = FALSE; + + /** + * Flag to turn the REGEX pattern matching on or off + * + * @var bool + */ + protected $regex = TRUE; + + /** + * Array of valid users. Each element is a regular expression. You should + * user \ to escape special chars, like '.' etc. + * + */ + protected $valid_attribute_values = array(); + + + /** + * Initialize this filter. + * Validate configuration parameters. + * + * @param array $config Configuration information about this filter. + * @param mixed $reserved For future use. + */ + public function __construct($config, $reserved) { + parent::__construct($config, $reserved); + + assert(is_array($config)); + + // Check for the deny option, get it and remove it + // Must be bool specifically, if not, it might be for a attrib filter below + if (isset($config['deny']) && is_bool($config['deny'])) { + $this->deny = $config['deny']; + unset($config['deny']); + } + + // Check for the regex option, get it and remove it + // Must be bool specifically, if not, it might be for a attrib filter below + if (isset($config['regex']) && is_bool($config['regex'])) { + $this->regex = $config['regex']; + unset($config['regex']); + } + + foreach ($config as $attribute => $values) { + if (is_string($values)) + $values = array($values); + if (!is_array($values)) + throw new Exception('Filter Authorize: Attribute values is neither string nor array: ' . var_export($attribute, TRUE)); + foreach ($values as $value){ + if(!is_string($value)) { + throw new Exception('Filter Authorize: Each value should be a string for attribute: ' . var_export($attribute, TRUE) . ' value: ' . var_export($value, TRUE) . ' Config is: ' . var_export($config, TRUE)); + } + } + $this->valid_attribute_values[$attribute] = $values; + } + } + + + /** + * Apply filter to validate attributes. + * + * @param array &$request The current request + */ + public function process(&$request) { + $authorize = $this->deny; + assert(is_array($request)); + assert(array_key_exists('Attributes', $request)); + + $attributes =& $request['Attributes']; + + foreach ($this->valid_attribute_values as $name => $patterns) { + if(array_key_exists($name, $attributes)) { + foreach ($patterns as $pattern){ + $values = $attributes[$name]; + if (!is_array($values)) + $values = array($values); + foreach ($values as $value){ + if ($this->regex) { + $matched = preg_match($pattern, $value); + } else { + $matched = ($value == $pattern); + } + if ($matched) { + $authorize = ($this->deny ? FALSE : TRUE); + break 3; + } + } + } + } + } + if (!$authorize){ + $this->unauthorized($request); + } + } + + + /** + * When the process logic determines that the user is not + * authorized for this service, then forward the user to + * an 403 unauthorized page. + * + * Separated this code into its own method so that child + * classes can override it and change the action. Forward + * thinking in case a "chained" ACL is needed, more complex + * permission logic. + * + * @param array $request + */ + protected function unauthorized(&$request) { + // Save state and redirect to 403 page + $id = SimpleSAML_Auth_State::saveState($request, + 'authorize:Authorize'); + $url = SimpleSAML\Module::getModuleURL( + 'authorize/authorize_403.php'); + \SimpleSAML\Utils\HTTP::redirectTrustedURL($url, array('StateId' => $id)); + } } diff --git a/modules/authtwitter/lib/Auth/Source/Twitter.php b/modules/authtwitter/lib/Auth/Source/Twitter.php index 6ffba993e10a3a7ef1cdc3737af332dea5539846..2b5d68d9328aa4dacbe5ec64e0ee191b54539da9 100644 --- a/modules/authtwitter/lib/Auth/Source/Twitter.php +++ b/modules/authtwitter/lib/Auth/Source/Twitter.php @@ -5,24 +5,25 @@ require_once(dirname(dirname(dirname(dirname(dirname(__FILE__))))) . '/oauth/lib /** * Authenticate using Twitter. * + * @author Andreas Åkre Solberg, UNINETT AS. * @package SimpleSAMLphp */ class sspmod_authtwitter_Auth_Source_Twitter extends SimpleSAML_Auth_Source { - /** - * The string used to identify our states. - */ - const STAGE_INIT = 'twitter:init'; + /** + * The string used to identify our states. + */ + const STAGE_INIT = 'twitter:init'; - /** - * The key of the AuthId field in the state. - */ - const AUTHID = 'twitter:AuthId'; + /** + * The key of the AuthId field in the state. + */ + const AUTHID = 'twitter:AuthId'; /** * @var string */ - private $key; + private $key; /** * @var string @@ -32,110 +33,117 @@ class sspmod_authtwitter_Auth_Source_Twitter extends SimpleSAML_Auth_Source /** * @var bool */ - private $force_login; + private $force_login; /** * @var bool */ private $include_email; - /** - * Constructor for this authentication source. - * - * @param array $info Information about this authentication source. - * @param array $config Configuration. - */ - public function __construct(array $info, array $config) + /** + * Constructor for this authentication source. + * + * @param array $info Information about this authentication source. + * @param array $config Configuration. + */ + public function __construct($info, $config) { - // Call the parent constructor first, as required by the interface - parent::__construct($info, $config); + assert(is_array($info)); + assert(is_array($config)); - $configObject = SimpleSAML_Configuration::loadFromArray($config, 'authsources[' . var_export($this->authId, true) . ']'); + // Call the parent constructor first, as required by the interface + parent::__construct($info, $config); - $this->key = $configObject->getString('key'); - $this->secret = $configObject->getString('secret'); - $this->force_login = $configObject->getBoolean('force_login', false); - $this->include_email = $configObject->getBoolean('include_email', false); - } + $configObject = SimpleSAML_Configuration::loadFromArray($config, 'authsources[' . var_export($this->authId, true) . ']'); - /** - * Log-in using Twitter platform - * - * @param array &$state Information about the current authentication. - */ - public function authenticate(array &$state) + $this->key = $configObject->getString('key'); + $this->secret = $configObject->getString('secret'); + $this->force_login = $configObject->getBoolean('force_login', false); + $this->include_email = $configObject->getBoolean('include_email', false); + } + + + /** + * Log-in using Twitter platform + * + * @param array &$state Information about the current authentication. + */ + public function authenticate(&$state) { - // We are going to need the authId in order to retrieve this authentication source later - $state[self::AUTHID] = $this->authId; - - $stateID = SimpleSAML_Auth_State::saveState($state, self::STAGE_INIT); - - $consumer = new sspmod_oauth_Consumer($this->key, $this->secret); - // Get the request token - $linkback = SimpleSAML\Module::getModuleURL('authtwitter/linkback.php', array('AuthState' => $stateID)); - $requestToken = $consumer->getRequestToken('https://api.twitter.com/oauth/request_token', array('oauth_callback' => $linkback)); - SimpleSAML\Logger::debug("Got a request token from the OAuth service provider [" . - $requestToken->key . "] with the secret [" . $requestToken->secret . "]"); - - $state['authtwitter:authdata:requestToken'] = $requestToken; - SimpleSAML_Auth_State::saveState($state, self::STAGE_INIT); - - // Authorize the request token - $url = 'https://api.twitter.com/oauth/authenticate'; - if ($this->force_login) { - $url = \SimpleSAML\Utils\HTTP::addURLParameters($url, array('force_login' => 'true')); - } - $consumer->getAuthorizeRequest($url, $requestToken); - } - - public function finalStep(array &$state) + assert(is_array($state)); + + // We are going to need the authId in order to retrieve this authentication source later + $state[self::AUTHID] = $this->authId; + + $stateID = SimpleSAML_Auth_State::saveState($state, self::STAGE_INIT); + + $consumer = new sspmod_oauth_Consumer($this->key, $this->secret); + // Get the request token + $linkback = SimpleSAML\Module::getModuleURL('authtwitter/linkback.php', array('AuthState' => $stateID)); + $requestToken = $consumer->getRequestToken('https://api.twitter.com/oauth/request_token', array('oauth_callback' => $linkback)); + SimpleSAML\Logger::debug("Got a request token from the OAuth service provider [" . + $requestToken->key . "] with the secret [" . $requestToken->secret . "]"); + + $state['authtwitter:authdata:requestToken'] = $requestToken; + SimpleSAML_Auth_State::saveState($state, self::STAGE_INIT); + + // Authorize the request token + $url = 'https://api.twitter.com/oauth/authenticate'; + if ($this->force_login) { + $url = \SimpleSAML\Utils\HTTP::addURLParameters($url, array('force_login' => 'true')); + } + $consumer->getAuthorizeRequest($url, $requestToken); + } + + + public function finalStep(&$state) { - $requestToken = $state['authtwitter:authdata:requestToken']; - $parameters = array(); - - if (!isset($_REQUEST['oauth_token'])) { - throw new SimpleSAML_Error_BadRequest("Missing oauth_token parameter."); - } - if ($requestToken->key !== (string)$_REQUEST['oauth_token']) { - throw new SimpleSAML_Error_BadRequest("Invalid oauth_token parameter."); - } - - if (!isset($_REQUEST['oauth_verifier'])) { - throw new SimpleSAML_Error_BadRequest("Missing oauth_verifier parameter."); - } - $parameters['oauth_verifier'] = (string)$_REQUEST['oauth_verifier']; - - $consumer = new sspmod_oauth_Consumer($this->key, $this->secret); - - SimpleSAML\Logger::debug("oauth: Using this request token [" . - $requestToken->key . "] with the secret [" . $requestToken->secret . "]"); - - // Replace the request token with an access token - $accessToken = $consumer->getAccessToken('https://api.twitter.com/oauth/access_token', $requestToken, $parameters); - SimpleSAML\Logger::debug("Got an access token from the OAuth service provider [" . - $accessToken->key . "] with the secret [" . $accessToken->secret . "]"); - - $verify_credentials_url = 'https://api.twitter.com/1.1/account/verify_credentials.json'; - if ($this->include_email) { - $verify_credentials_url = $verify_credentials_url . '?include_email=true'; - } - $userdata = $consumer->getUserInfo($verify_credentials_url, $accessToken); - - if (!isset($userdata['id_str']) || !isset($userdata['screen_name'])) { - throw new SimpleSAML_Error_AuthSource($this->authId, 'Authentication error: id_str and screen_name not set.'); - } - - $attributes = array(); - foreach ($userdata as $key => $value) { - if (is_string($value)) { - $attributes['twitter.' . $key] = array((string)$value); + $requestToken = $state['authtwitter:authdata:requestToken']; + $parameters = array(); + + if (!isset($_REQUEST['oauth_token'])) { + throw new SimpleSAML_Error_BadRequest("Missing oauth_token parameter."); + } + if ($requestToken->key !== (string)$_REQUEST['oauth_token']) { + throw new SimpleSAML_Error_BadRequest("Invalid oauth_token parameter."); + } + + if (!isset($_REQUEST['oauth_verifier'])) { + throw new SimpleSAML_Error_BadRequest("Missing oauth_verifier parameter."); + } + $parameters['oauth_verifier'] = (string)$_REQUEST['oauth_verifier']; + + $consumer = new sspmod_oauth_Consumer($this->key, $this->secret); + + SimpleSAML\Logger::debug("oauth: Using this request token [" . + $requestToken->key . "] with the secret [" . $requestToken->secret . "]"); + + // Replace the request token with an access token + $accessToken = $consumer->getAccessToken('https://api.twitter.com/oauth/access_token', $requestToken, $parameters); + SimpleSAML\Logger::debug("Got an access token from the OAuth service provider [" . + $accessToken->key . "] with the secret [" . $accessToken->secret . "]"); + + $verify_credentials_url = 'https://api.twitter.com/1.1/account/verify_credentials.json'; + if ($this->include_email) { + $verify_credentials_url = $verify_credentials_url . '?include_email=true'; + } + $userdata = $consumer->getUserInfo($verify_credentials_url, $accessToken); + + if (!isset($userdata['id_str']) || !isset($userdata['screen_name'])) { + throw new SimpleSAML_Error_AuthSource($this->authId, 'Authentication error: id_str and screen_name not set.'); + } + + $attributes = array(); + foreach ($userdata as $key => $value) { + if (is_string($value)) { + $attributes['twitter.' . $key] = array((string)$value); } - } - - $attributes['twitter_at_screen_name'] = array('@' . $userdata['screen_name']); - $attributes['twitter_screen_n_realm'] = array($userdata['screen_name'] . '@twitter.com'); - $attributes['twitter_targetedID'] = array('http://twitter.com!' . $userdata['id_str']); - - $state['Attributes'] = $attributes; - } + } + + $attributes['twitter_at_screen_name'] = array('@' . $userdata['screen_name']); + $attributes['twitter_screen_n_realm'] = array($userdata['screen_name'] . '@twitter.com'); + $attributes['twitter_targetedID'] = array('http://twitter.com!' . $userdata['id_str']); + + $state['Attributes'] = $attributes; + } } diff --git a/modules/authwindowslive/lib/Auth/Source/LiveID.php b/modules/authwindowslive/lib/Auth/Source/LiveID.php index d3ad06cdb148e4b9d625f5a69a2923480218433b..39fbfd1595f1762391885cd0b8adf0a80db6d4a4 100644 --- a/modules/authwindowslive/lib/Auth/Source/LiveID.php +++ b/modules/authwindowslive/lib/Auth/Source/LiveID.php @@ -1,11 +1,15 @@ <?php + /** * Authenticate using LiveID. * + * @author Brook Schofield, TERENA. + * @author Guy Halse, TENET. * @package SimpleSAMLphp */ class sspmod_authwindowslive_Auth_Source_LiveID extends SimpleSAML_Auth_Source { + /** * The string used to identify our states. */ @@ -28,8 +32,11 @@ class sspmod_authwindowslive_Auth_Source_LiveID extends SimpleSAML_Auth_Source * * @throws Exception In case of misconfiguration. */ - public function __construct(array $info, array $config) + public function __construct($info, $config) { + assert(is_array($info)); + assert(is_array($config)); + // Call the parent constructor first, as required by the interface parent::__construct($info, $config); @@ -46,12 +53,13 @@ class sspmod_authwindowslive_Auth_Source_LiveID extends SimpleSAML_Auth_Source $this->secret = $config['secret']; } + /** * Log-in using LiveID platform * * @param array &$state Information about the current authentication. */ - public function authenticate(array &$state) + public function authenticate(&$state) { assert(is_array($state)); @@ -77,12 +85,13 @@ class sspmod_authwindowslive_Auth_Source_LiveID extends SimpleSAML_Auth_Source \SimpleSAML\Utils\HTTP::redirectTrustedURL($authorizeURL); } + /** * @param $state * * @throws Exception */ - public function finalStep(array &$state) + public function finalStep(&$state) { SimpleSAML\Logger::debug( "authwindowslive oauth: Using this verification code [".$state['authwindowslive:verification_code']."]" @@ -145,6 +154,7 @@ class sspmod_authwindowslive_Auth_Source_LiveID extends SimpleSAML_Auth_Source } } + SimpleSAML\Logger::debug('LiveID Returned Attributes: '. implode(", ", array_keys($attributes))); $state['Attributes'] = $attributes; diff --git a/modules/cas/lib/Auth/Source/CAS.php b/modules/cas/lib/Auth/Source/CAS.php index 36f15c87cc534d259e3ddcc20354a9b8a9ca83dc..db045d3e63a7827ef3ff7967397fc701cf792585 100644 --- a/modules/cas/lib/Auth/Source/CAS.php +++ b/modules/cas/lib/Auth/Source/CAS.php @@ -5,6 +5,7 @@ * * Based on www/auth/login-cas.php by Mads Freek, RUC. * + * @author Danny Bollaert, UGent. * @package SimpleSAMLphp */ diff --git a/modules/cdc/lib/Auth/Process/CDC.php b/modules/cdc/lib/Auth/Process/CDC.php index 421d8f40030cd09e7be1078350b4df7b804eb491..9641da2ab90586b1d237ce7fb4aa0ab10d54d46f 100644 --- a/modules/cdc/lib/Auth/Process/CDC.php +++ b/modules/cdc/lib/Auth/Process/CDC.php @@ -29,9 +29,10 @@ class sspmod_cdc_Auth_Process_CDC extends SimpleSAML_Auth_ProcessingFilter * @param array $config Configuration information about this filter. * @param mixed $reserved For future use. */ - public function __construct(array $config, $reserved) + public function __construct($config, $reserved) { parent::__construct($config, $reserved); + assert(is_array($config)); if (!isset($config['domain'])) { throw new SimpleSAML_Error_Exception('Missing domain option in cdc:CDC filter.'); @@ -47,8 +48,10 @@ class sspmod_cdc_Auth_Process_CDC extends SimpleSAML_Auth_ProcessingFilter * * @param array &$state The request state. */ - public function process(array &$state) + public function process(&$state) { + assert(is_array($state)); + if (!isset($state['Source']['entityid'])) { SimpleSAML\Logger::warning('saml:CDC: Could not find IdP entityID.'); return; diff --git a/modules/consent/lib/Auth/Process/Consent.php b/modules/consent/lib/Auth/Process/Consent.php index ee7ce6f93d2d642639fa20e1bf6807ce50b2e232..0647ac84f194f457b48e5d83139f23cd30067ddf 100644 --- a/modules/consent/lib/Auth/Process/Consent.php +++ b/modules/consent/lib/Auth/Process/Consent.php @@ -1,4 +1,6 @@ <?php + + /** * Consent Authentication Processing filter * @@ -69,8 +71,9 @@ class sspmod_consent_Auth_Process_Consent extends SimpleSAML_Auth_ProcessingFilt * * @throws SimpleSAML_Error_Exception if the configuration is not valid. */ - public function __construct(array $config, $reserved) + public function __construct($config, $reserved) { + assert(is_array($config)); parent::__construct($config, $reserved); if (array_key_exists('includeValues', $config)) { @@ -212,8 +215,9 @@ class sspmod_consent_Auth_Process_Consent extends SimpleSAML_Auth_ProcessingFilt * * @throws SimpleSAML_Error_NoPassive if the request was passive and consent is needed. */ - public function process(array &$state) + public function process(&$state) { + assert(is_array($state)); assert(array_key_exists('UserID', $state)); assert(array_key_exists('Destination', $state)); assert(array_key_exists('entityid', $state['Destination'])); diff --git a/modules/core/lib/Auth/Process/AttributeAdd.php b/modules/core/lib/Auth/Process/AttributeAdd.php index 84e3fd09ee2a452d8cbf09b22113176b34329230..63aa03fb2becf34654b18b7f95b7a307c912c7b9 100644 --- a/modules/core/lib/Auth/Process/AttributeAdd.php +++ b/modules/core/lib/Auth/Process/AttributeAdd.php @@ -1,79 +1,85 @@ <?php + /** * Filter to add attributes. * * This filter allows you to add attributes to the attribute set being processed. * + * @author Olav Morken, UNINETT AS. * @package SimpleSAMLphp */ -class sspmod_core_Auth_Process_AttributeAdd extends SimpleSAML_Auth_ProcessingFilter -{ - /** - * Flag which indicates wheter this filter should append new values or replace old values. - */ - private $replace = false; +class sspmod_core_Auth_Process_AttributeAdd extends SimpleSAML_Auth_ProcessingFilter { + + /** + * Flag which indicates wheter this filter should append new values or replace old values. + */ + private $replace = FALSE; + + + /** + * Attributes which should be added/appended. + * + * Assiciative array of arrays. + */ + private $attributes = array(); + + + /** + * Initialize this filter. + * + * @param array $config Configuration information about this filter. + * @param mixed $reserved For future use. + */ + public function __construct($config, $reserved) { + parent::__construct($config, $reserved); - /** - * Attributes which should be added/appended. - * - * Assiciative array of arrays. - */ - private $attributes = []; + assert(is_array($config)); - /** - * Initialize this filter. - * - * @param array $config Configuration information about this filter. - * @param mixed $reserved For future use. - */ - public function __construct(array $config, $reserved) - { - parent::__construct($config, $reserved); + foreach($config as $name => $values) { + if(is_int($name)) { + if($values === '%replace') { + $this->replace = TRUE; + } else { + throw new Exception('Unknown flag: ' . var_export($values, TRUE)); + } + continue; + } - foreach($config as $name => $values) { - if(is_int($name)) { - if($values === '%replace') { - $this->replace = true; - } else { - throw new Exception('Unknown flag: ' . var_export($values, true)); - } - continue; - } + if(!is_array($values)) { + $values = array($values); + } + foreach($values as $value) { + if(!is_string($value)) { + throw new Exception('Invalid value for attribute ' . $name . ': ' . + var_export($values, TRUE)); + } + } - if(!is_array($values)) { - $values = array($values); - } - foreach($values as $value) { - if(!is_string($value)) { - throw new Exception('Invalid value for attribute ' . $name . ': ' . - var_export($values, true)); - } - } + $this->attributes[$name] = $values; + } + } - $this->attributes[$name] = $values; - } - } + /** + * Apply filter to add or replace attributes. + * + * Add or replace existing attributes with the configured values. + * + * @param array &$request The current request + */ + public function process(&$request) { + assert(is_array($request)); + assert(array_key_exists('Attributes', $request)); - /** - * Apply filter to add or replace attributes. - * - * Add or replace existing attributes with the configured values. - * - * @param array &$request The current request - */ - public function process(array &$request) - { - assert(array_key_exists('Attributes', $request)); + $attributes =& $request['Attributes']; - $attributes =& $request['Attributes']; + foreach($this->attributes as $name => $values) { + if($this->replace === TRUE || !array_key_exists($name, $attributes)) { + $attributes[$name] = $values; + } else { + $attributes[$name] = array_merge($attributes[$name], $values); + } + } + } - foreach($this->attributes as $name => $values) { - if($this->replace === true || !array_key_exists($name, $attributes)) { - $attributes[$name] = $values; - } else { - $attributes[$name] = array_merge($attributes[$name], $values); - } - } - } } diff --git a/modules/core/lib/Auth/Process/AttributeAlter.php b/modules/core/lib/Auth/Process/AttributeAlter.php index ddc7772134ea5120ebd41f27ffdac8f722ab48cf..c53625790b57c44990ec666b6bf400cff330fbba 100644 --- a/modules/core/lib/Auth/Process/AttributeAlter.php +++ b/modules/core/lib/Auth/Process/AttributeAlter.php @@ -4,6 +4,7 @@ * * This filter can modify or replace attributes given a regular expression. * + * @author Jacob Christiansen, WAYF * @package SimpleSAMLphp */ class sspmod_core_Auth_Process_AttributeAlter extends SimpleSAML_Auth_ProcessingFilter @@ -45,10 +46,12 @@ class sspmod_core_Auth_Process_AttributeAlter extends SimpleSAML_Auth_Processing * @param mixed $reserved For future use. * @throws SimpleSAML_Error_Exception In case of invalid configuration. */ - public function __construct(array $config, $reserved) + public function __construct($config, $reserved) { parent::__construct($config, $reserved); + assert(is_array($config)); + // parse filter configuration foreach ($config as $name => $value) { if (is_int($name)) { @@ -85,8 +88,8 @@ class sspmod_core_Auth_Process_AttributeAlter extends SimpleSAML_Auth_Processing * @param array &$request The current request. * @throws SimpleSAML_Error_Exception In case of invalid configuration. */ - public function process(array &$request) - { + public function process(&$request) { + assert(is_array($request)); assert(array_key_exists('Attributes', $request)); // get attributes from request diff --git a/modules/core/lib/Auth/Process/AttributeCopy.php b/modules/core/lib/Auth/Process/AttributeCopy.php index 1b62952161e64a7e40c6e969027ec2aeebbc342e..e2412a45c8d0ff36e41bf9cfc2e51a89d12ec48c 100644 --- a/modules/core/lib/Auth/Process/AttributeCopy.php +++ b/modules/core/lib/Auth/Process/AttributeCopy.php @@ -1,7 +1,9 @@ <?php + /** * Attribute filter for renaming attributes. * + * @author Gyula Szabo MTA SZTAKI * @package SimpleSAMLphp * * You just follow the 'source' => 'destination' schema. In this example user's * cn will be the user's displayName. @@ -13,57 +15,62 @@ * ), * */ -class sspmod_core_Auth_Process_AttributeCopy extends SimpleSAML_Auth_ProcessingFilter -{ - /** - * Assosiative array with the mappings of attribute names. - */ - private $map = []; +class sspmod_core_Auth_Process_AttributeCopy extends SimpleSAML_Auth_ProcessingFilter { + + /** + * Assosiative array with the mappings of attribute names. + */ + private $map = array(); + + + /** + * Initialize this filter, parse configuration + * + * @param array $config Configuration information about this filter. + * @param mixed $reserved For future use. + */ + public function __construct($config, $reserved) { + parent::__construct($config, $reserved); + + assert(is_array($config)); + + foreach($config as $source => $destination) { - /** - * Initialize this filter, parse configuration - * - * @param array $config Configuration information about this filter. - * @param mixed $reserved For future use. - */ - public function __construct(array $config, $reserved) { - parent::__construct($config, $reserved); + if(!is_string($source)) { + throw new Exception('Invalid source attribute name: ' . var_export($source, TRUE)); + } - foreach($config as $source => $destination) { - if(!is_string($source)) { - throw new Exception('Invalid source attribute name: ' . var_export($source, true)); - } + if(!is_string($destination) && !is_array($destination)) { + throw new Exception('Invalid destination attribute name: ' . var_export($destination, TRUE)); + } - if(!is_string($destination) && !is_array($destination)) { - throw new Exception('Invalid destination attribute name: ' . var_export($destination, true)); - } + $this->map[$source] = $destination; + } + } - $this->map[$source] = $destination; - } - } + /** + * Apply filter to rename attributes. + * + * @param array &$request The current request + */ + public function process(&$request) { + assert(is_array($request)); + assert(array_key_exists('Attributes', $request)); - /** - * Apply filter to rename attributes. - * - * @param array &$request The current request - */ - public function process(array &$request) - { - assert(array_key_exists('Attributes', $request)); + $attributes =& $request['Attributes']; - $attributes =& $request['Attributes']; + foreach($attributes as $name => $values) { + if (array_key_exists($name,$this->map)){ + if (!is_array($this->map[$name])) { + $attributes[$this->map[$name]] = $values; + } else { + foreach ($this->map[$name] as $to_map) { + $attributes[$to_map] = $values; + } + } + } + } - foreach($attributes as $name => $values) { - if (array_key_exists($name,$this->map)){ - if (!is_array($this->map[$name])) { - $attributes[$this->map[$name]] = $values; - } else { - foreach ($this->map[$name] as $to_map) { - $attributes[$to_map] = $values; - } - } - } - } - } + } } diff --git a/modules/core/lib/Auth/Process/AttributeLimit.php b/modules/core/lib/Auth/Process/AttributeLimit.php index 8b981f5e69e205040259e3a68c591c8183806a58..0ae3a92770b4b8926731e0a12ccd7b9b79d81334 100644 --- a/modules/core/lib/Auth/Process/AttributeLimit.php +++ b/modules/core/lib/Auth/Process/AttributeLimit.php @@ -1,110 +1,116 @@ <?php + /** * A filter for limiting which attributes are passed on. * + * @author Olav Morken, UNINETT AS. * @package SimpleSAMLphp */ -class sspmod_core_Auth_Process_AttributeLimit extends SimpleSAML_Auth_ProcessingFilter -{ - /** - * List of attributes which this filter will allow through. - */ - private $allowedAttributes = []; +class sspmod_core_Auth_Process_AttributeLimit extends SimpleSAML_Auth_ProcessingFilter { - /** - * Whether the 'attributes' option in the metadata takes precedence. - * - * @var bool - */ - private $isDefault = false; + /** + * List of attributes which this filter will allow through. + */ + private $allowedAttributes = array(); - /** - * Initialize this filter. - * - * @param array $config Configuration information about this filter. - * @param mixed $reserved For future use + + /** + * Whether the 'attributes' option in the metadata takes precedence. + * + * @var bool + */ + private $isDefault = false; + + + /** + * Initialize this filter. + * + * @param array $config Configuration information about this filter. + * @param mixed $reserved For future use * @throws SimpleSAML_Error_Exception If invalid configuration is found. - */ - public function __construct(array $config, $reserved) - { - parent::__construct($config, $reserved); - - foreach ($config as $index => $value) { - if ($index === 'default') { - $this->isDefault = (bool)$value; - } elseif (is_int($index)) { - if (!is_string($value)) { - throw new SimpleSAML_Error_Exception('AttributeLimit: Invalid attribute name: ' . - var_export($value, true)); - } - $this->allowedAttributes[] = $value; + */ + public function __construct($config, $reserved) { + parent::__construct($config, $reserved); + + assert(is_array($config)); + + foreach ($config as $index => $value) { + if ($index === 'default') { + $this->isDefault = (bool)$value; + } elseif (is_int($index)) { + if (!is_string($value)) { + throw new SimpleSAML_Error_Exception('AttributeLimit: Invalid attribute name: ' . + var_export($value, TRUE)); + } + $this->allowedAttributes[] = $value; } elseif (is_string($index)) { if (!is_array($value)) { - throw new SimpleSAML_Error_Exception('AttributeLimit: Values for ' . var_export($index, true) . + throw new SimpleSAML_Error_Exception('AttributeLimit: Values for ' . var_export($index, TRUE) . ' must be specified in an array.'); } $this->allowedAttributes[$index] = $value; - } else { - throw new SimpleSAML_Error_Exception('AttributeLimit: Invalid option: ' . var_export($index, true)); - } - } - } + } else { + throw new SimpleSAML_Error_Exception('AttributeLimit: Invalid option: ' . var_export($index, TRUE)); + } + } + } - /** - * Get list of allowed from the SP/IdP config. - * - * @param array &$request The current request. - * @return array|null Array with attribute names, or null if no limit is placed. - */ - private static function getSPIdPAllowed(array &$request) - { - if (array_key_exists('attributes', $request['Destination'])) { - // SP Config - return $request['Destination']['attributes']; - } - if (array_key_exists('attributes', $request['Source'])) { - // IdP Config - return $request['Source']['attributes']; - } - return null; - } + /** + * Get list of allowed from the SP/IdP config. + * + * @param array &$request The current request. + * @return array|NULL Array with attribute names, or NULL if no limit is placed. + */ + private static function getSPIdPAllowed(array &$request) { - /** - * Apply filter to remove attributes. - * - * Removes all attributes which aren't one of the allowed attributes. - * - * @param array &$request The current request + if (array_key_exists('attributes', $request['Destination'])) { + // SP Config + return $request['Destination']['attributes']; + } + if (array_key_exists('attributes', $request['Source'])) { + // IdP Config + return $request['Source']['attributes']; + } + return NULL; + } + + + /** + * Apply filter to remove attributes. + * + * Removes all attributes which aren't one of the allowed attributes. + * + * @param array &$request The current request * @throws SimpleSAML_Error_Exception If invalid configuration is found. - */ - public function process(array &$request) - { - assert(array_key_exists('Attributes', $request)); + */ + public function process(&$request) { + assert(is_array($request)); + assert(array_key_exists('Attributes', $request)); - if ($this->isDefault) { - $allowedAttributes = self::getSPIdPAllowed($request); - if ($allowedAttributes === null) { - $allowedAttributes = $this->allowedAttributes; - } - } elseif (!empty($this->allowedAttributes)) { - $allowedAttributes = $this->allowedAttributes; - } else { - $allowedAttributes = self::getSPIdPAllowed($request); - if ($allowedAttributes === null) { - return; /* No limit on attributes. */ - } - } + if ($this->isDefault) { + $allowedAttributes = self::getSPIdPAllowed($request); + if ($allowedAttributes === NULL) { + $allowedAttributes = $this->allowedAttributes; + } + } elseif (!empty($this->allowedAttributes)) { + $allowedAttributes = $this->allowedAttributes; + } else { + $allowedAttributes = self::getSPIdPAllowed($request); + if ($allowedAttributes === NULL) { + return; /* No limit on attributes. */ + } + } - $attributes =& $request['Attributes']; + $attributes =& $request['Attributes']; - foreach ($attributes as $name => $values) { - if (!in_array($name, $allowedAttributes, true)) { + foreach ($attributes as $name => $values) { + if (!in_array($name, $allowedAttributes, TRUE)) { // the attribute name is not in the array of allowed attributes if (array_key_exists($name, $allowedAttributes)) { // but it is an index of the array if (!is_array($allowedAttributes[$name])) { - throw new SimpleSAML_Error_Exception('AttributeLimit: Values for ' . var_export($name, true) . + throw new SimpleSAML_Error_Exception('AttributeLimit: Values for ' . var_export($name, TRUE) . ' must be specified in an array.'); } $attributes[$name] = $this->filterAttributeValues($attributes[$name], $allowedAttributes[$name]); @@ -113,9 +119,10 @@ class sspmod_core_Auth_Process_AttributeLimit extends SimpleSAML_Auth_Processing } } unset($attributes[$name]); - } - } - } + } + } + + } /** * Perform the filtering of attributes diff --git a/modules/core/lib/Auth/Process/AttributeMap.php b/modules/core/lib/Auth/Process/AttributeMap.php index a258768a22e4c0d635614375ae356341faeb62bc..5de07cb24b229f8503adfe6c8150db31423bdbed 100644 --- a/modules/core/lib/Auth/Process/AttributeMap.php +++ b/modules/core/lib/Auth/Process/AttributeMap.php @@ -1,21 +1,26 @@ <?php + + /** * Attribute filter for renaming attributes. * + * @author Olav Morken, UNINETT AS. * @package SimpleSAMLphp */ class sspmod_core_Auth_Process_AttributeMap extends SimpleSAML_Auth_ProcessingFilter { + /** * Associative array with the mappings of attribute names. */ - private $map = []; + private $map = array(); /** * Should attributes be duplicated or renamed. */ private $duplicate = false; + /** * Initialize this filter, parse configuration * @@ -24,10 +29,11 @@ class sspmod_core_Auth_Process_AttributeMap extends SimpleSAML_Auth_ProcessingFi * * @throws Exception If the configuration of the filter is wrong. */ - public function __construct(array $config, $reserved) + public function __construct($config, $reserved) { parent::__construct($config, $reserved); + assert(is_array($config)); $mapFiles = array(); foreach ($config as $origName => $newName) { @@ -58,6 +64,7 @@ class sspmod_core_Auth_Process_AttributeMap extends SimpleSAML_Auth_ProcessingFi } } + /** * Loads and merges in a file with a attribute map. * @@ -97,13 +104,15 @@ class sspmod_core_Auth_Process_AttributeMap extends SimpleSAML_Auth_ProcessingFi } } + /** * Apply filter to rename attributes. * * @param array &$request The current request. */ - public function process(array &$request) + public function process(&$request) { + assert(is_array($request)); assert(array_key_exists('Attributes', $request)); $attributes =& $request['Attributes']; diff --git a/modules/core/lib/Auth/Process/AttributeRealm.php b/modules/core/lib/Auth/Process/AttributeRealm.php index b2f6f299a669ee3780229dce924775820c512c06..86c8be1b2f10e25b04873213d573f681e504a0d5 100644 --- a/modules/core/lib/Auth/Process/AttributeRealm.php +++ b/modules/core/lib/Auth/Process/AttributeRealm.php @@ -1,13 +1,15 @@ <?php + /** * Filter that will take the user ID on the format 'andreas@uninett.no' * and create a new attribute 'realm' that includes the value after the '@' sign. * + * @author Andreas Åkre Solberg, UNINETT AS. * @package SimpleSAMLphp * @deprecated Use ScopeFromAttribute instead. */ -class sspmod_core_Auth_Process_AttributeRealm extends SimpleSAML_Auth_ProcessingFilter -{ +class sspmod_core_Auth_Process_AttributeRealm extends SimpleSAML_Auth_ProcessingFilter { + private $attributename = 'realm'; /** @@ -16,12 +18,13 @@ class sspmod_core_Auth_Process_AttributeRealm extends SimpleSAML_Auth_Processing * @param array $config Configuration information about this filter. * @param mixed $reserved For future use. */ - public function __construct(array $config, $reserved) { + public function __construct($config, $reserved) { parent::__construct($config, $reserved); + assert(is_array($config)); + + if (array_key_exists('attributename', $config)) + $this->attributename = $config['attributename']; - if (array_key_exists('attributename', $config)) { - $this->attributename = $config['attributename']; - } } /** @@ -31,8 +34,8 @@ class sspmod_core_Auth_Process_AttributeRealm extends SimpleSAML_Auth_Processing * * @param array &$request The current request */ - public function process(array &$request) - { + public function process(&$request) { + assert(is_array($request)); assert(array_key_exists('Attributes', $request)); $attributes =& $request['Attributes']; diff --git a/modules/core/lib/Auth/Process/AttributeValueMap.php b/modules/core/lib/Auth/Process/AttributeValueMap.php index 121f67ee0ff5f4f0cb95dd4c335268ac45f308f9..5c69048f69d97ba59fc97c57190f1f7c44582745 100644 --- a/modules/core/lib/Auth/Process/AttributeValueMap.php +++ b/modules/core/lib/Auth/Process/AttributeValueMap.php @@ -5,24 +5,26 @@ namespace SimpleSAML\Module\core\Auth\Process; /** * Filter to create target attribute based on value(s) in source attribute * + * @author Martin van Es, m7 * @package SimpleSAMLphp */ class AttributeValueMap extends \SimpleSAML_Auth_ProcessingFilter { + /** - * The name of the attribute we should assign values to (ie: the target attribute). - */ + * The name of the attribute we should assign values to (ie: the target attribute). + */ private $targetattribute; /** - * The name of the attribute we should create values from. - */ + * The name of the attribute we should create values from. + */ private $sourceattribute; /** - * The required $sourceattribute values and target affiliations. - */ - private $values = []; + * The required $sourceattribute values and target affiliations. + */ + private $values = array(); /** * Whether $sourceattribute should be kept or not. @@ -30,8 +32,8 @@ class AttributeValueMap extends \SimpleSAML_Auth_ProcessingFilter private $keep = false; /** - * Whether $target attribute values should be replaced by new values or not. - */ + * Whether $target attribute values should be replaced by new values or not. + */ private $replace = false; /** @@ -41,10 +43,12 @@ class AttributeValueMap extends \SimpleSAML_Auth_ProcessingFilter * @param mixed $reserved For future use. * @throws \SimpleSAML_Error_Exception If the configuration is not valid. */ - public function __construct(array $config, $reserved) + public function __construct($config, $reserved) { parent::__construct($config, $reserved); + assert(is_array($config)); + // parse configuration foreach ($config as $name => $value) { if (is_int($name)) { @@ -90,15 +94,17 @@ class AttributeValueMap extends \SimpleSAML_Auth_ProcessingFilter } } + /** * Apply filter. * * @param array &$request The current request */ - public function process(array &$request) + public function process(&$request) { \SimpleSAML\Logger::debug('Processing the AttributeValueMap filter.'); + assert(is_array($request)); assert(array_key_exists('Attributes', $request)); $attributes =& $request['Attributes']; diff --git a/modules/core/lib/Auth/Process/Cardinality.php b/modules/core/lib/Auth/Process/Cardinality.php index 2cbb4de49159771bbd4ab4a37f92ff979c20f35e..88b44f336be99fb4f4ec7ff5a987ea652c1f7f49 100644 --- a/modules/core/lib/Auth/Process/Cardinality.php +++ b/modules/core/lib/Auth/Process/Cardinality.php @@ -1,7 +1,9 @@ <?php + /** * Filter to ensure correct cardinality of attributes * + * @author Guy Halse, http://orcid.org/0000-0002-9388-8592 * @package SimpleSAMLphp */ class sspmod_core_Auth_Process_Cardinality extends SimpleSAML_Auth_ProcessingFilter @@ -19,9 +21,10 @@ class sspmod_core_Auth_Process_Cardinality extends SimpleSAML_Auth_ProcessingFil * @param mixed $reserved For future use. * @throws SimpleSAML_Error_Exception */ - public function __construct(array $config, $reserved) + public function __construct($config, $reserved) { parent::__construct($config, $reserved); + assert(is_array($config)); foreach ($config as $attribute => $rules) { if ($attribute === '%ignoreEntities') { @@ -85,8 +88,9 @@ class sspmod_core_Auth_Process_Cardinality extends SimpleSAML_Auth_ProcessingFil * * @param array &$request The current request */ - public function process(array &$request) + public function process(&$request) { + assert(is_array($request)); assert(array_key_exists("Attributes", $request)); $entityid = false; diff --git a/modules/core/lib/Auth/Process/CardinalitySingle.php b/modules/core/lib/Auth/Process/CardinalitySingle.php index b1ed90ec48e08736a23a22e068217d23a68f8fc8..a8dbb3c56042dec1d9bf9f7d2503bc91d396237e 100644 --- a/modules/core/lib/Auth/Process/CardinalitySingle.php +++ b/modules/core/lib/Auth/Process/CardinalitySingle.php @@ -1,10 +1,12 @@ <?php + /** * Filter to ensure correct cardinality of single-valued attributes * * This filter implements a special case of the core:Cardinality filter, and * allows for optional corrections to be made when cardinality errors are encountered. * + * @author Guy Halse, http://orcid.org/0000-0002-9388-8592 * @package SimpleSAMLphp */ class sspmod_core_Auth_Process_CardinalitySingle extends SimpleSAML_Auth_ProcessingFilter @@ -27,11 +29,13 @@ class sspmod_core_Auth_Process_CardinalitySingle extends SimpleSAML_Auth_Process /** * Initialize this filter, parse configuration. * + * @param array $config Configuration information about this filter. * @param mixed $reserved For future use. */ - public function __construct(array $config, $reserved) + public function __construct($config, $reserved) { parent::__construct($config, $reserved); + assert(is_array($config)); if (array_key_exists('singleValued', $config)) { $this->singleValued = $config['singleValued']; @@ -59,8 +63,9 @@ class sspmod_core_Auth_Process_CardinalitySingle extends SimpleSAML_Auth_Process * * @param array &$request The current request */ - public function process(array &$request) + public function process(&$request) { + assert(is_array($request)); assert(array_key_exists("Attributes", $request)); if (array_key_exists('Source', $request) && diff --git a/modules/core/lib/Auth/Process/ExtendIdPSession.php b/modules/core/lib/Auth/Process/ExtendIdPSession.php index 81da8a7b409ed523de74f034d2ae3a1cfd1477a4..faca137a8a80ec1e84ae609d7cb9da09fa38ca6e 100644 --- a/modules/core/lib/Auth/Process/ExtendIdPSession.php +++ b/modules/core/lib/Auth/Process/ExtendIdPSession.php @@ -1,48 +1,47 @@ <?php + /** * Extend IdP session and cookies. - */ -class sspmod_core_Auth_Process_ExtendIdPSession extends SimpleSAML_Auth_ProcessingFilter -{ - /** - * Apply filter to extend IdP session and cookies. - * - * @param array &$request The current request - */ - public function process(array &$request) { - if (empty($request['Expire']) || empty($request['Authority'])) { - return; - } - - $now = time(); - $delta = $request['Expire'] - $now; - - $globalConfig = SimpleSAML_Configuration::getInstance(); - $sessionDuration = $globalConfig->getInteger('session.duration', 8*60*60); - - // Extend only if half of session duration already passed - if ($delta >= ($sessionDuration * 0.5)) { - return; - } - - // Update authority expire time - $session = SimpleSAML_Session::getSessionFromRequest(); - $session->setAuthorityExpire($request['Authority']); - - /* Update session cookies duration */ - - /* If remember me is active */ - $rememberMeExpire = $session->getRememberMeExpire(); - if (!empty($request['RememberMe']) && $rememberMeExpire !== null && $globalConfig->getBoolean('session.rememberme.enable', false)) { - $session->setRememberMeExpire(); - return; - } - - /* Or if session lifetime is more than zero */ - $sessionHandler = \SimpleSAML\SessionHandler::getSessionHandler(); - $cookieParams = $sessionHandler->getCookieParams(); - if ($cookieParams['lifetime'] > 0) { - $session->updateSessionCookies(); - } - } +*/ +class sspmod_core_Auth_Process_ExtendIdPSession extends SimpleSAML_Auth_ProcessingFilter { + + public function process(&$state) { + assert(is_array($state)); + + if (empty($state['Expire']) || empty($state['Authority'])) { + return; + } + + $now = time(); + $delta = $state['Expire'] - $now; + + $globalConfig = SimpleSAML_Configuration::getInstance(); + $sessionDuration = $globalConfig->getInteger('session.duration', 8*60*60); + + // Extend only if half of session duration already passed + if ($delta >= ($sessionDuration * 0.5)) { + return; + } + + // Update authority expire time + $session = SimpleSAML_Session::getSessionFromRequest(); + $session->setAuthorityExpire($state['Authority']); + + /* Update session cookies duration */ + + /* If remember me is active */ + $rememberMeExpire = $session->getRememberMeExpire(); + if (!empty($state['RememberMe']) && $rememberMeExpire !== NULL && $globalConfig->getBoolean('session.rememberme.enable', FALSE)) { + $session->setRememberMeExpire(); + return; + } + + /* Or if session lifetime is more than zero */ + $sessionHandler = \SimpleSAML\SessionHandler::getSessionHandler(); + $cookieParams = $sessionHandler->getCookieParams(); + if ($cookieParams['lifetime'] > 0) { + $session->updateSessionCookies(); + } + } + } diff --git a/modules/core/lib/Auth/Process/GenerateGroups.php b/modules/core/lib/Auth/Process/GenerateGroups.php index c5f9356355d137f2213eb54847451ab2792850d9..17b896e5f28e17f2221f4a9791833cd383d21e3c 100644 --- a/modules/core/lib/Auth/Process/GenerateGroups.php +++ b/modules/core/lib/Auth/Process/GenerateGroups.php @@ -1,133 +1,142 @@ <?php + /** * Filter to generate a groups attribute based on many of the attributes of the user. * + * @author Olav Morken, UNINETT AS. * @package SimpleSAMLphp */ -class sspmod_core_Auth_Process_GenerateGroups extends SimpleSAML_Auth_ProcessingFilter -{ - /** - * The attributes we should generate groups from. - */ - private $generateGroupsFrom; - - /** - * Initialize this filter. - * - * @param array $config Configuration information about this filter. - * @param mixed $reserved For future use. - */ - public function __construct(array $config, $reserved) - { - parent::__construct($config, $reserved); - - if (count($config) === 0) { - // Use default groups - $this->generateGroupsFrom = array( - 'eduPersonAffiliation', - 'eduPersonOrgUnitDN', - 'eduPersonEntitlement', - ); - - } else { - // Validate configuration - foreach ($config as $attributeName) { - if (!is_string($attributeName)) { - throw new Exception('Invalid attribute name for core:GenerateGroups filter: ' . - var_export($attributeName, TRUE)); - } - } - - $this->generateGroupsFrom = $config; - } - } - - /** - * Apply filter to add groups attribute. - * - * @param array &$request The current request - */ - public function process(array &$request) - { - assert(array_key_exists('Attributes', $request)); - - $groups = array(); - $attributes =& $request['Attributes']; - - $realm = self::getRealm($attributes); - if ($realm !== NULL) { - $groups[] = 'realm-' . $realm; - } - - foreach ($this->generateGroupsFrom as $name) { - if (!array_key_exists($name, $attributes)) { - SimpleSAML\Logger::debug('GenerateGroups - attribute \'' . $name . '\' not found.'); - /* Attribute not present. */ - continue; - } - - foreach ($attributes[$name] as $value) { - $value = self::escapeIllegalChars($value); - $groups[] = $name . '-' . $value; - if ($realm !== NULL) { - $groups[] = $name . '-' . $realm . '-' . $value; - } - } - } - - if (count($groups) > 0) { - $attributes['groups'] = $groups; - } - } - - - /** - * Determine which realm the user belongs to. - * - * This function will attempt to determine the realm a user belongs to based on the - * eduPersonPrincipalName attribute if it is present. If it isn't, or if it doesn't contain - * a realm, NULL will be returned. - * - * @param array $attributes The attributes of the user. - * @return string|NULL The realm of the user, or NULL if we are unable to determine the realm. - */ - private static function getRealm(array $attributes) - { - if (!array_key_exists('eduPersonPrincipalName', $attributes)) { - return NULL; - } - $eppn = $attributes['eduPersonPrincipalName']; - - if (count($eppn) < 1) { - return NULL; - } - $eppn = $eppn[0]; - - $realm = explode('@', $eppn, 2); - if (count($realm) < 2) { - return NULL; - } - $realm = $realm[1]; - - return self::escapeIllegalChars($realm); - } - - /** - * Escape special characters in a string. - * - * This function is similar to urlencode, but encodes many more characters. - * This function takes any characters not in [a-zA-Z0-9_@=.] and encodes them with as - * %<hex version>. For example, it will encode '+' as '%2b' and '%' as '%25'. - * - * @param string $string The string which should be escaped. - * @return string The escaped string. - */ - private static function escapeIllegalChars($string) - { - assert(is_string($string)); - - return preg_replace_callback('/([^a-zA-Z0-9_@=.])/', - function ($m) { return sprintf("%%%02x", ord($m[1])); }, - $string); - } +class sspmod_core_Auth_Process_GenerateGroups extends SimpleSAML_Auth_ProcessingFilter { + + + /** + * The attributes we should generate groups from. + */ + private $generateGroupsFrom; + + + /** + * Initialize this filter. + * + * @param array $config Configuration information about this filter. + * @param mixed $reserved For future use. + */ + public function __construct($config, $reserved) { + parent::__construct($config, $reserved); + + assert(is_array($config)); + + if (count($config) === 0) { + // Use default groups + $this->generateGroupsFrom = array( + 'eduPersonAffiliation', + 'eduPersonOrgUnitDN', + 'eduPersonEntitlement', + ); + + } else { + // Validate configuration + foreach ($config as $attributeName) { + if (!is_string($attributeName)) { + throw new Exception('Invalid attribute name for core:GenerateGroups filter: ' . + var_export($attributeName, TRUE)); + } + } + + $this->generateGroupsFrom = $config; + } + } + + + /** + * Apply filter to add groups attribute. + * + * @param array &$request The current request + */ + public function process(&$request) { + assert(is_array($request)); + assert(array_key_exists('Attributes', $request)); + + $groups = array(); + $attributes =& $request['Attributes']; + + $realm = self::getRealm($attributes); + if ($realm !== NULL) { + $groups[] = 'realm-' . $realm; + } + + + foreach ($this->generateGroupsFrom as $name) { + if (!array_key_exists($name, $attributes)) { + SimpleSAML\Logger::debug('GenerateGroups - attribute \'' . $name . '\' not found.'); + /* Attribute not present. */ + continue; + } + + foreach ($attributes[$name] as $value) { + $value = self::escapeIllegalChars($value); + $groups[] = $name . '-' . $value; + if ($realm !== NULL) { + $groups[] = $name . '-' . $realm . '-' . $value; + } + } + } + + if (count($groups) > 0) { + $attributes['groups'] = $groups; + } + } + + + /** + * Determine which realm the user belongs to. + * + * This function will attempt to determine the realm a user belongs to based on the + * eduPersonPrincipalName attribute if it is present. If it isn't, or if it doesn't contain + * a realm, NULL will be returned. + * + * @param array $attributes The attributes of the user. + * @return string|NULL The realm of the user, or NULL if we are unable to determine the realm. + */ + private static function getRealm($attributes) { + assert(is_array($attributes)); + + if (!array_key_exists('eduPersonPrincipalName', $attributes)) { + return NULL; + } + $eppn = $attributes['eduPersonPrincipalName']; + + if (count($eppn) < 1) { + return NULL; + } + $eppn = $eppn[0]; + + $realm = explode('@', $eppn, 2); + if (count($realm) < 2) { + return NULL; + } + $realm = $realm[1]; + + return self::escapeIllegalChars($realm); + } + + + /** + * Escape special characters in a string. + * + * This function is similar to urlencode, but encodes many more characters. + * This function takes any characters not in [a-zA-Z0-9_@=.] and encodes them with as + * %<hex version>. For example, it will encode '+' as '%2b' and '%' as '%25'. + * + * @param string $string The string which should be escaped. + * @return string The escaped string. + */ + private static function escapeIllegalChars($string) { + assert(is_string($string)); + + return preg_replace_callback('/([^a-zA-Z0-9_@=.])/', + function ($m) { return sprintf("%%%02x", ord($m[1])); }, + $string); + } + } diff --git a/modules/core/lib/Auth/Process/LanguageAdaptor.php b/modules/core/lib/Auth/Process/LanguageAdaptor.php index a69d8a3545555a00fe1c6a393cbb6df250d9b02f..4a1b381405255b2f441089e95f5595db24243326 100644 --- a/modules/core/lib/Auth/Process/LanguageAdaptor.php +++ b/modules/core/lib/Auth/Process/LanguageAdaptor.php @@ -1,62 +1,66 @@ <?php + /** * Filter to set and get language settings from attributes. * + * @author Andreas Åkre Solberg, UNINETT AS. * @package SimpleSAMLphp */ -class sspmod_core_Auth_Process_LanguageAdaptor extends SimpleSAML_Auth_ProcessingFilter -{ - private $langattr = 'preferredLanguage'; - - /** - * Initialize this filter. - * - * @param array $config Configuration information about this filter. - * @param mixed $reserved For future use. - */ - public function __construct(array $config, $reserved) - { - parent::__construct($config, $reserved); - - if (array_key_exists('attributename', $config)) { - $this->langattr = $config['attributename']; - } - } - - /** - * Apply filter to add or replace attributes. - * - * Add or replace existing attributes with the configured values. - * - * @param array &$request The current request - */ - public function process(array &$request) - { - assert(array_key_exists('Attributes', $request)); - - $attributes =& $request['Attributes']; - - $attrlang = null; - if (array_key_exists($this->langattr, $attributes)) { - $attrlang = $attributes[$this->langattr][0]; - } +class sspmod_core_Auth_Process_LanguageAdaptor extends SimpleSAML_Auth_ProcessingFilter { - $lang = SimpleSAML\Locale\Language::getLanguageCookie(); + private $langattr = 'preferredLanguage'; - if (isset($attrlang)) { - SimpleSAML\Logger::debug('LanguageAdaptor: Language in attribute was set [' . $attrlang . ']'); - } - if (isset($lang)) { - SimpleSAML\Logger::debug('LanguageAdaptor: Language in session was set [' . $lang . ']'); + + /** + * Initialize this filter. + * + * @param array $config Configuration information about this filter. + * @param mixed $reserved For future use. + */ + public function __construct($config, $reserved) { + parent::__construct($config, $reserved); + assert(is_array($config)); + + if (array_key_exists('attributename', $config)) { + $this->langattr = $config['attributename']; + } } - if (isset($attrlang) && !isset($lang)) { - // Language set in attribute but not in cookie - update cookie - SimpleSAML\Locale\Language::setLanguageCookie($attrlang); - } elseif (!isset($attrlang) && isset($lang)) { - // Language set in cookie, but not in attribute. Update attribute - $request['Attributes'][$this->langattr] = array($lang); - } - } + /** + * Apply filter to add or replace attributes. + * + * Add or replace existing attributes with the configured values. + * + * @param array &$request The current request + */ + public function process(&$request) { + assert(is_array($request)); + assert(array_key_exists('Attributes', $request)); + + $attributes =& $request['Attributes']; + + $attrlang = NULL; + if (array_key_exists($this->langattr, $attributes)) + $attrlang = $attributes[$this->langattr][0]; + + $lang = SimpleSAML\Locale\Language::getLanguageCookie(); + + + if (isset($attrlang)) + SimpleSAML\Logger::debug('LanguageAdaptor: Language in attribute was set [' . $attrlang . ']'); + if (isset($lang)) + SimpleSAML\Logger::debug('LanguageAdaptor: Language in session was set [' . $lang . ']'); + + + if (isset($attrlang) && !isset($lang)) { + // Language set in attribute but not in cookie - update cookie + SimpleSAML\Locale\Language::setLanguageCookie($attrlang); + } elseif (!isset($attrlang) && isset($lang)) { + // Language set in cookie, but not in attribute. Update attribute + $request['Attributes'][$this->langattr] = array($lang); + } + + } + } diff --git a/modules/core/lib/Auth/Process/PHP.php b/modules/core/lib/Auth/Process/PHP.php index be7dd30210a94a8780b155a3f8927a1c4a8bb6dd..5b7f11711bc8507b2dbc68e55d37eebafbe7ed17 100644 --- a/modules/core/lib/Auth/Process/PHP.php +++ b/modules/core/lib/Auth/Process/PHP.php @@ -1,4 +1,6 @@ <?php + + /** * Attribute filter for running arbitrary PHP code. * @@ -6,6 +8,7 @@ */ class sspmod_core_Auth_Process_PHP extends SimpleSAML_Auth_ProcessingFilter { + /** * The PHP code that should be run. * @@ -13,6 +16,7 @@ class sspmod_core_Auth_Process_PHP extends SimpleSAML_Auth_ProcessingFilter */ private $code; + /** * Initialize this filter, parse configuration * @@ -21,23 +25,27 @@ class sspmod_core_Auth_Process_PHP extends SimpleSAML_Auth_ProcessingFilter * * @throws SimpleSAML_Error_Exception if the 'code' option is not defined. */ - public function __construct(array $config, $reserved) + public function __construct($config, $reserved) { parent::__construct($config, $reserved); + assert(is_array($config)); + if (!isset($config['code'])) { throw new SimpleSAML_Error_Exception("core:PHP: missing mandatory configuration option 'code'."); } $this->code = (string) $config['code']; } + /** * Apply the PHP code to the attributes. * * @param array &$request The current request */ - public function process(array &$request) + public function process(&$request) { + assert(is_array($request)); assert(array_key_exists('Attributes', $request)); $function = function(&$attributes) { eval($this->code); }; diff --git a/modules/core/lib/Auth/Process/ScopeAttribute.php b/modules/core/lib/Auth/Process/ScopeAttribute.php index 182f9b8ac214967a73b7f7d30bb1d6c276c37774..a44ff14de75b7a519af8887da99d309321affb3d 100644 --- a/modules/core/lib/Auth/Process/ScopeAttribute.php +++ b/modules/core/lib/Auth/Process/ScopeAttribute.php @@ -1,4 +1,5 @@ <?php + /** * Add a scoped variant of an attribute. * @@ -6,95 +7,101 @@ */ class sspmod_core_Auth_Process_ScopeAttribute extends SimpleSAML_Auth_ProcessingFilter { - /** - * The attribute we extract the scope from. - * - * @var string - */ - private $scopeAttribute; - - /** - * The attribute we want to add scope to. - * - * @var string - */ - private $sourceAttribute; - - /** - * The attribute we want to add the scoped attributes to. - * - * @var string - */ - private $targetAttribute; - - /** - * Only modify targetAttribute if it doesn't already exist. - * - * @var bool - */ - private $onlyIfEmpty = false; - - /** - * Initialize this filter, parse configuration - * - * @param array $config Configuration information about this filter. - * @param mixed $reserved For future use. - */ - public function __construct(array $config, $reserved) + /** + * The attribute we extract the scope from. + * + * @var string + */ + private $scopeAttribute; + + + /** + * The attribute we want to add scope to. + * + * @var string + */ + private $sourceAttribute; + + + /** + * The attribute we want to add the scoped attributes to. + * + * @var string + */ + private $targetAttribute; + + /** + * Only modify targetAttribute if it doesn't already exist. + * + * @var bool + */ + private $onlyIfEmpty = false; + + + /** + * Initialize this filter, parse configuration + * + * @param array $config Configuration information about this filter. + * @param mixed $reserved For future use. + */ + public function __construct($config, $reserved) { - parent::__construct($config, $reserved); - - $config = SimpleSAML_Configuration::loadFromArray($config, 'ScopeAttribute'); - - $this->scopeAttribute = $config->getString('scopeAttribute'); - $this->sourceAttribute = $config->getString('sourceAttribute'); - $this->targetAttribute = $config->getString('targetAttribute'); - $this->onlyIfEmpty = $config->getBoolean('onlyIfEmpty', false); - } - - /** - * Apply this filter to the request. - * - * @param array &$request The current request - */ - public function process(array &$request) + parent::__construct($config, $reserved); + assert(is_array($config)); + + $config = SimpleSAML_Configuration::loadFromArray($config, 'ScopeAttribute'); + + $this->scopeAttribute = $config->getString('scopeAttribute'); + $this->sourceAttribute = $config->getString('sourceAttribute'); + $this->targetAttribute = $config->getString('targetAttribute'); + $this->onlyIfEmpty = $config->getBoolean('onlyIfEmpty', false); + } + + + /** + * Apply this filter to the request. + * + * @param array &$request The current request + */ + public function process(&$request) { - assert(array_key_exists('Attributes', $request)); + assert(is_array($request)); + assert(array_key_exists('Attributes', $request)); - $attributes =& $request['Attributes']; + $attributes =& $request['Attributes']; - if (!isset($attributes[$this->scopeAttribute])) { - return; - } + if (!isset($attributes[$this->scopeAttribute])) { + return; + } - if (!isset($attributes[$this->sourceAttribute])) { - return; - } + if (!isset($attributes[$this->sourceAttribute])) { + return; + } - if (!isset($attributes[$this->targetAttribute])) { - $attributes[$this->targetAttribute] = array(); - } + if (!isset($attributes[$this->targetAttribute])) { + $attributes[$this->targetAttribute] = array(); + } - if ($this->onlyIfEmpty && count($attributes[$this->targetAttribute]) > 0) { - return; - } + if ($this->onlyIfEmpty && count($attributes[$this->targetAttribute]) > 0) { + return; + } - foreach ($attributes[$this->scopeAttribute] as $scope) { - if (strpos($scope, '@') !== false) { - $scope = explode('@', $scope, 2); - $scope = $scope[1]; - } + foreach ($attributes[$this->scopeAttribute] as $scope) { + if (strpos($scope, '@') !== false) { + $scope = explode('@', $scope, 2); + $scope = $scope[1]; + } - foreach ($attributes[$this->sourceAttribute] as $value) { - $value = $value . '@' . $scope; + foreach ($attributes[$this->sourceAttribute] as $value) { + $value = $value . '@' . $scope; - if (in_array($value, $attributes[$this->targetAttribute], true)) { - // Already present - continue; - } + if (in_array($value, $attributes[$this->targetAttribute], true)) { + // Already present + continue; + } - $attributes[$this->targetAttribute][] = $value; - } - } - } + $attributes[$this->targetAttribute][] = $value; + } + } + } } diff --git a/modules/core/lib/Auth/Process/ScopeFromAttribute.php b/modules/core/lib/Auth/Process/ScopeFromAttribute.php index 06d8ddc2e7e2cf23b2f697b780cc82856cfbc2e7..818a24f7657bfcfb77e5bba86ce54790f0056db8 100644 --- a/modules/core/lib/Auth/Process/ScopeFromAttribute.php +++ b/modules/core/lib/Auth/Process/ScopeFromAttribute.php @@ -1,4 +1,5 @@ <?php + /** * Retrieve a scope from a source attribute and add it as a virtual target * attribute. @@ -15,74 +16,74 @@ * to add a virtual 'scope' attribute from the eduPersonPrincipalName * attribute. */ -class sspmod_core_Auth_Process_ScopeFromAttribute extends SimpleSAML_Auth_ProcessingFilter -{ - /** - * The attribute where the scope is taken from - * - * @var string - */ - private $sourceAttribute; +class sspmod_core_Auth_Process_ScopeFromAttribute extends SimpleSAML_Auth_ProcessingFilter { + /** + * The attribute where the scope is taken from + * + * @var string + */ + private $sourceAttribute; + /** + * The name of the attribute which includes the scope + * + * @var string + */ + private $targetAttribute; - /** - * The name of the attribute which includes the scope - * - * @var string - */ - private $targetAttribute; + /** + * Initialize this filter, parse configuration + * + * @param array $config Configuration information about this filter. + * @param mixed $reserved For future use. + */ + public function __construct($config, $reserved) { + parent::__construct($config, $reserved); + assert(is_array($config)); - /** - * Initialize this filter, parse configuration - * - * @param array $config Configuration information about this filter. - * @param mixed $reserved For future use. - */ - public function __construct(array $config, $reserved) - { - parent::__construct($config, $reserved); + $config = SimpleSAML_Configuration::loadFromArray($config, 'ScopeFromAttribute'); + $this->targetAttribute = $config->getString('targetAttribute'); + $this->sourceAttribute = $config->getString('sourceAttribute'); + } // end constructor - $config = SimpleSAML_Configuration::loadFromArray($config, 'ScopeFromAttribute'); - $this->targetAttribute = $config->getString('targetAttribute'); - $this->sourceAttribute = $config->getString('sourceAttribute'); - } - /** - * Apply this filter. - * - * @param array &$request The current request - */ - public function process(array &$request) { - assert(array_key_exists('Attributes', $request)); + /** + * Apply this filter. + * + * @param array &$request The current request + */ + public function process(&$request) { + assert(is_array($request)); + assert(array_key_exists('Attributes', $request)); - $attributes =& $request['Attributes']; + $attributes =& $request['Attributes']; - if (!isset($attributes[$this->sourceAttribute])) { - return; - } + if (!isset($attributes[$this->sourceAttribute])) { + return; + } - // will not overwrite existing attribute - if (isset($attributes[$this->targetAttribute])) { - return; - } + // will not overwrite existing attribute + if (isset($attributes[$this->targetAttribute])) { + return; + } - $sourceAttrVal = $attributes[$this->sourceAttribute][0]; + $sourceAttrVal = $attributes[$this->sourceAttribute][0]; - /* the last position of an @ is usually the beginning of the scope - * string */ - $scopeIndex = strrpos($sourceAttrVal, '@'); + /* the last position of an @ is usually the beginning of the scope + * string */ + $scopeIndex = strrpos($sourceAttrVal, '@'); - if ($scopeIndex !== false) { - $attributes[$this->targetAttribute] = array(); - $scope = substr($sourceAttrVal, $scopeIndex+1); - $attributes[$this->targetAttribute][] = $scope; - SimpleSAML\Logger::debug('ScopeFromAttribute: Inserted new attribute ' . - $this->targetAttribute . ', with scope ' . - $scope); - } else { - SimpleSAML\Logger::warning('ScopeFromAttribute: The configured source attribute ' . - $this->sourceAttribute . - ' does not have a scope. Did not add attribute ' . - $this->targetAttribute . '.'); - } - } + if ($scopeIndex !== FALSE) { + $attributes[$this->targetAttribute] = array(); + $scope = substr($sourceAttrVal, $scopeIndex+1); + $attributes[$this->targetAttribute][] = $scope; + SimpleSAML\Logger::debug('ScopeFromAttribute: Inserted new attribute ' . + $this->targetAttribute . ', with scope ' . + $scope); + } else { + SimpleSAML\Logger::warning('ScopeFromAttribute: The configured source attribute ' . + $this->sourceAttribute . + ' does not have a scope. Did not add attribute ' . + $this->targetAttribute . '.'); + } + } /* end process */ } diff --git a/modules/core/lib/Auth/Process/StatisticsWithAttribute.php b/modules/core/lib/Auth/Process/StatisticsWithAttribute.php index 941bf07b3062532d4ef348fab28a55d5176033a4..800558cbd51b32f28bc307304c81d5326cecc23c 100644 --- a/modules/core/lib/Auth/Process/StatisticsWithAttribute.php +++ b/modules/core/lib/Auth/Process/StatisticsWithAttribute.php @@ -1,7 +1,9 @@ <?php + /** * Log a line in the STAT log with one attribute. * + * @author Andreas Åkre Solberg, UNINETT AS. * @package SimpleSAMLphp */ class sspmod_core_Auth_Process_StatisticsWithAttribute extends SimpleSAML_Auth_ProcessingFilter @@ -10,7 +12,7 @@ class sspmod_core_Auth_Process_StatisticsWithAttribute extends SimpleSAML_Auth_P * The attribute to log * @var string|null */ - private $attribute = null; + private $attribute = null; /** * @var string @@ -29,10 +31,12 @@ class sspmod_core_Auth_Process_StatisticsWithAttribute extends SimpleSAML_Auth_P * @param array $config Configuration information about this filter. * @param mixed $reserved For future use. */ - public function __construct(array $config, $reserved) + public function __construct($config, $reserved) { parent::__construct($config, $reserved); + assert(is_array($config)); + if (array_key_exists('attributename', $config)) { $this->attribute = $config['attributename']; if (!is_string($this->attribute)) { @@ -52,13 +56,15 @@ class sspmod_core_Auth_Process_StatisticsWithAttribute extends SimpleSAML_Auth_P } } + /** * Log line. * * @param array &$state The current state. */ - public function process(array &$state) + public function process(&$state) { + assert(is_array($state)); assert(array_key_exists('Attributes', $state)); $logAttribute = 'NA'; @@ -85,7 +91,7 @@ class sspmod_core_Auth_Process_StatisticsWithAttribute extends SimpleSAML_Auth_P } SimpleSAML\Logger::stats($isPassive.$this->typeTag.' '.$dest.' '.$source.' '.$logAttribute); - } + } /** * @param string &$direction Either 'Source' or 'Destination'. @@ -93,7 +99,7 @@ class sspmod_core_Auth_Process_StatisticsWithAttribute extends SimpleSAML_Auth_P * * @return string */ - private function setIdentifier($direction, array $state) + private function setIdentifier($direction, $state) { if (array_key_exists($direction, $state)) { if (isset($state[$direction]['core:statistics-id'])) { diff --git a/modules/core/lib/Auth/Process/TargetedID.php b/modules/core/lib/Auth/Process/TargetedID.php index 1b2cb8972f378a27f195111a496fb6d5f4903a22..3b70f02aa4ad20a7468862fa6c3ff89be8ec236a 100644 --- a/modules/core/lib/Auth/Process/TargetedID.php +++ b/modules/core/lib/Auth/Process/TargetedID.php @@ -1,4 +1,5 @@ <?php + /** * Filter to generate the eduPersonTargetedID attribute. * @@ -24,138 +25,148 @@ * ), * </code> * + * @author Olav Morken, UNINETT AS. * @package SimpleSAMLphp */ -class sspmod_core_Auth_Process_TargetedID extends SimpleSAML_Auth_ProcessingFilter -{ - /** - * The attribute we should generate the targeted id from, or null if we should use the - * UserID. - */ - private $attribute = null; - - /** - * Whether the attribute should be generated as a NameID value, or as a simple string. - * - * @var boolean - */ - private $generateNameId = false; - - /** - * Initialize this filter. - * - * @param array $config Configuration information about this filter. - * @param mixed $reserved For future use. - */ - public function __construct(array $config, $reserved) - { - parent::__construct($config, $reserved); - - if (array_key_exists('attributename', $config)) { - $this->attribute = $config['attributename']; - if (!is_string($this->attribute)) { - throw new Exception('Invalid attribute name given to core:TargetedID filter.'); - } - } - - if (array_key_exists('nameId', $config)) { - $this->generateNameId = $config['nameId']; - if (!is_bool($this->generateNameId)) { - throw new Exception('Invalid value of \'nameId\'-option to core:TargetedID filter.'); - } - } - } - - /** - * Apply filter to add the targeted ID. - * - * @param array &$state The current state. - */ - public function process(array &$state) - { - assert(array_key_exists('Attributes', $state)); - - if ($this->attribute === null) { - if (!array_key_exists('UserID', $state)) { - throw new Exception('core:TargetedID: Missing UserID for this user. Please' . - ' check the \'userid.attribute\' option in the metadata against the' . - ' attributes provided by the authentication source.'); - } - - $userID = $state['UserID']; - } else { - if (!array_key_exists($this->attribute, $state['Attributes'])) { - throw new Exception('core:TargetedID: Missing attribute \'' . $this->attribute . - '\', which is needed to generate the targeted ID.'); - } - - $userID = $state['Attributes'][$this->attribute][0]; - } - - $secretSalt = SimpleSAML\Utils\Config::getSecretSalt(); - - if (array_key_exists('Source', $state)) { - $srcID = self::getEntityId($state['Source']); - } else { - $srcID = ''; - } - - if (array_key_exists('Destination', $state)) { - $dstID = self::getEntityId($state['Destination']); - } else { - $dstID = ''; - } - - $uidData = 'uidhashbase' . $secretSalt; - $uidData .= strlen($srcID) . ':' . $srcID; - $uidData .= strlen($dstID) . ':' . $dstID; - $uidData .= strlen($userID) . ':' . $userID; - $uidData .= $secretSalt; - - $uid = hash('sha1', $uidData); - - if ($this->generateNameId) { - // Convert the targeted ID to a SAML 2.0 name identifier element - $nameId = new \SAML2\XML\saml\NameID(); - $nameId->value = $uid; - $nameId->Format = \SAML2\Constants::NAMEID_PERSISTENT; - - if (isset($state['Source']['entityid'])) { - $nameId->NameQualifier = $state['Source']['entityid']; - } - if (isset($state['Destination']['entityid'])) { - $nameId->SPNameQualifier = $state['Destination']['entityid']; - } - } else { - $nameId = $uid; - } - - $state['Attributes']['eduPersonTargetedID'] = array($nameId); - } - - /** - * Generate ID from entity metadata. - * - * This function takes in the metadata of an entity, and attempts to generate - * an unique identifier based on that. - * - * @param array $metadata The metadata of the entity. - * @return string The unique identifier for the entity. - */ - private static function getEntityId(array $metadata) - { - $id = ''; - - if (array_key_exists('metadata-set', $metadata)) { - $set = $metadata['metadata-set']; - $id .= 'set' . strlen($set) . ':' . $set; - } - - if (array_key_exists('entityid', $metadata)) { - $entityid = $metadata['entityid']; - $id .= 'set' . strlen($entityid) . ':' . $entityid; - } - - return $id; - } +class sspmod_core_Auth_Process_TargetedID extends SimpleSAML_Auth_ProcessingFilter { + + + /** + * The attribute we should generate the targeted id from, or NULL if we should use the + * UserID. + */ + private $attribute = NULL; + + + /** + * Whether the attribute should be generated as a NameID value, or as a simple string. + * + * @var boolean + */ + private $generateNameId = FALSE; + + + /** + * Initialize this filter. + * + * @param array $config Configuration information about this filter. + * @param mixed $reserved For future use. + */ + public function __construct($config, $reserved) { + parent::__construct($config, $reserved); + + assert(is_array($config)); + + if (array_key_exists('attributename', $config)) { + $this->attribute = $config['attributename']; + if (!is_string($this->attribute)) { + throw new Exception('Invalid attribute name given to core:TargetedID filter.'); + } + } + + if (array_key_exists('nameId', $config)) { + $this->generateNameId = $config['nameId']; + if (!is_bool($this->generateNameId)) { + throw new Exception('Invalid value of \'nameId\'-option to core:TargetedID filter.'); + } + } + } + + + /** + * Apply filter to add the targeted ID. + * + * @param array &$state The current state. + */ + public function process(&$state) { + assert(is_array($state)); + assert(array_key_exists('Attributes', $state)); + + if ($this->attribute === NULL) { + if (!array_key_exists('UserID', $state)) { + throw new Exception('core:TargetedID: Missing UserID for this user. Please' . + ' check the \'userid.attribute\' option in the metadata against the' . + ' attributes provided by the authentication source.'); + } + + $userID = $state['UserID']; + } else { + if (!array_key_exists($this->attribute, $state['Attributes'])) { + throw new Exception('core:TargetedID: Missing attribute \'' . $this->attribute . + '\', which is needed to generate the targeted ID.'); + } + + $userID = $state['Attributes'][$this->attribute][0]; + } + + + $secretSalt = SimpleSAML\Utils\Config::getSecretSalt(); + + if (array_key_exists('Source', $state)) { + $srcID = self::getEntityId($state['Source']); + } else { + $srcID = ''; + } + + if (array_key_exists('Destination', $state)) { + $dstID = self::getEntityId($state['Destination']); + } else { + $dstID = ''; + } + + $uidData = 'uidhashbase' . $secretSalt; + $uidData .= strlen($srcID) . ':' . $srcID; + $uidData .= strlen($dstID) . ':' . $dstID; + $uidData .= strlen($userID) . ':' . $userID; + $uidData .= $secretSalt; + + $uid = hash('sha1', $uidData); + + if ($this->generateNameId) { + // Convert the targeted ID to a SAML 2.0 name identifier element + $nameId = new \SAML2\XML\saml\NameID(); + $nameId->value = $uid; + $nameId->Format = \SAML2\Constants::NAMEID_PERSISTENT; + + if (isset($state['Source']['entityid'])) { + $nameId->NameQualifier = $state['Source']['entityid']; + } + if (isset($state['Destination']['entityid'])) { + $nameId->SPNameQualifier = $state['Destination']['entityid']; + } + } else { + $nameId = $uid; + } + + $state['Attributes']['eduPersonTargetedID'] = array($nameId); + } + + + /** + * Generate ID from entity metadata. + * + * This function takes in the metadata of an entity, and attempts to generate + * an unique identifier based on that. + * + * @param array $metadata The metadata of the entity. + * @return string The unique identifier for the entity. + */ + private static function getEntityId($metadata) { + assert(is_array($metadata)); + + $id = ''; + + if (array_key_exists('metadata-set', $metadata)) { + $set = $metadata['metadata-set']; + $id .= 'set' . strlen($set) . ':' . $set; + } + + if (array_key_exists('entityid', $metadata)) { + $entityid = $metadata['entityid']; + $id .= 'set' . strlen($entityid) . ':' . $entityid; + } + + return $id; + } + } diff --git a/modules/core/lib/Auth/Process/WarnShortSSOInterval.php b/modules/core/lib/Auth/Process/WarnShortSSOInterval.php index 59911eb6c0020ecbf32ac0463873cc452e5fd32e..d8ae6fa0a6e9bda49d7d493aaa00997216296b72 100644 --- a/modules/core/lib/Auth/Process/WarnShortSSOInterval.php +++ b/modules/core/lib/Auth/Process/WarnShortSSOInterval.php @@ -1,49 +1,52 @@ <?php + /** * Give a warning to the user if we receive multiple requests in a short time. * * @package SimpleSAMLphp */ -class sspmod_core_Auth_Process_WarnShortSSOInterval extends SimpleSAML_Auth_ProcessingFilter -{ - /** - * Process a authentication response. - * - * This function checks how long it is since the last time the user was authenticated. - * If it is to short a while since, we will show a warning to the user. - * - * @param array $state The state of the response. - */ - public function process(array &$state) - { - if (!array_key_exists('PreviousSSOTimestamp', $state)) { - /* - * No timestamp from the previous SSO to this SP. This is the first - * time during this session. - */ - return; - } - - $timeDelta = time() - $state['PreviousSSOTimestamp']; - if ($timeDelta >= 10) { - // At least 10 seconds since last attempt - return; - } - - if (array_key_exists('Destination', $state) - && array_key_exists('entityid', $state['Destination'])) { - $entityId = $state['Destination']['entityid']; - } else { - $entityId = 'UNKNOWN'; - } - - SimpleSAML\Logger::warning('WarnShortSSOInterval: Only ' . $timeDelta . - ' seconds since last SSO for this user from the SP ' . - var_export($entityId, true)); - - // Save state and redirect - $id = SimpleSAML_Auth_State::saveState($state, 'core:short_sso_interval'); - $url = SimpleSAML\Module::getModuleURL('core/short_sso_interval.php'); - \SimpleSAML\Utils\HTTP::redirectTrustedURL($url, array('StateId' => $id)); - } +class sspmod_core_Auth_Process_WarnShortSSOInterval extends SimpleSAML_Auth_ProcessingFilter { + + /** + * Process a authentication response. + * + * This function checks how long it is since the last time the user was authenticated. + * If it is to short a while since, we will show a warning to the user. + * + * @param array $state The state of the response. + */ + public function process(&$state) { + assert(is_array($state)); + + if (!array_key_exists('PreviousSSOTimestamp', $state)) { + /* + * No timestamp from the previous SSO to this SP. This is the first + * time during this session. + */ + return; + } + + $timeDelta = time() - $state['PreviousSSOTimestamp']; + if ($timeDelta >= 10) { + // At least 10 seconds since last attempt + return; + } + + if (array_key_exists('Destination', $state) + && array_key_exists('entityid', $state['Destination'])) { + $entityId = $state['Destination']['entityid']; + } else { + $entityId = 'UNKNOWN'; + } + + SimpleSAML\Logger::warning('WarnShortSSOInterval: Only ' . $timeDelta . + ' seconds since last SSO for this user from the SP ' . + var_export($entityId, TRUE)); + + // Save state and redirect + $id = SimpleSAML_Auth_State::saveState($state, 'core:short_sso_interval'); + $url = SimpleSAML\Module::getModuleURL('core/short_sso_interval.php'); + \SimpleSAML\Utils\HTTP::redirectTrustedURL($url, array('StateId' => $id)); + } + } diff --git a/modules/core/lib/Auth/Source/AdminPassword.php b/modules/core/lib/Auth/Source/AdminPassword.php index 240ba526fb4c41ea7237cb12358e7b7dcf2ff018..3ba1a821086d5e290b0149445c323562973429df 100644 --- a/modules/core/lib/Auth/Source/AdminPassword.php +++ b/modules/core/lib/Auth/Source/AdminPassword.php @@ -1,57 +1,64 @@ <?php + /** * Authentication source which verifies the password against * the 'auth.adminpassword' configuration option. * * @package SimpleSAMLphp */ -class sspmod_core_Auth_Source_AdminPassword extends sspmod_core_Auth_UserPassBase -{ - /** - * Constructor for this authentication source. - * - * @param array $info Information about this authentication source. - * @param array $config Configuration. - */ - public function __construct(array $info, array $config) { - // Call the parent constructor first, as required by the interface - parent::__construct($info, $config); - - $this->setForcedUsername("admin"); - } - - /** - * Attempt to log in using the given username and password. - * - * On a successful login, this function should return the users attributes. On failure, - * it should throw an exception. If the error was caused by the user entering the wrong - * username or password, a SimpleSAML_Error_Error('WRONGUSERPASS') should be thrown. - * - * Note that both the username and the password are UTF-8 encoded. - * - * @param string $username The username the user wrote. - * @param string $password The password the user wrote. - * @return array Associative array with the users attributes. - */ - protected function login($username, $password) { - assert(is_string($username)); - assert(is_string($password)); - - $config = SimpleSAML_Configuration::getInstance(); - $adminPassword = $config->getString('auth.adminpassword', '123'); - if ($adminPassword === '123') { - // We require that the user changes the password - throw new SimpleSAML_Error_Error('NOTSET'); - } - - if ($username !== "admin") { - throw new SimpleSAML_Error_Error('WRONGUSERPASS'); - } - - if (!SimpleSAML\Utils\Crypto::pwValid($adminPassword, $password)) { - throw new SimpleSAML_Error_Error('WRONGUSERPASS'); - } - - return array('user' => array('admin')); - } +class sspmod_core_Auth_Source_AdminPassword extends sspmod_core_Auth_UserPassBase { + + + /** + * Constructor for this authentication source. + * + * @param array $info Information about this authentication source. + * @param array $config Configuration. + */ + public function __construct($info, $config) { + assert(is_array($info)); + assert(is_array($config)); + + // Call the parent constructor first, as required by the interface + parent::__construct($info, $config); + + $this->setForcedUsername("admin"); + } + + + /** + * Attempt to log in using the given username and password. + * + * On a successful login, this function should return the users attributes. On failure, + * it should throw an exception. If the error was caused by the user entering the wrong + * username or password, a SimpleSAML_Error_Error('WRONGUSERPASS') should be thrown. + * + * Note that both the username and the password are UTF-8 encoded. + * + * @param string $username The username the user wrote. + * @param string $password The password the user wrote. + * @return array Associative array with the users attributes. + */ + protected function login($username, $password) { + assert(is_string($username)); + assert(is_string($password)); + + $config = SimpleSAML_Configuration::getInstance(); + $adminPassword = $config->getString('auth.adminpassword', '123'); + if ($adminPassword === '123') { + // We require that the user changes the password + throw new SimpleSAML_Error_Error('NOTSET'); + } + + if ($username !== "admin") { + throw new SimpleSAML_Error_Error('WRONGUSERPASS'); + } + + if (!SimpleSAML\Utils\Crypto::pwValid($adminPassword, $password)) { + throw new SimpleSAML_Error_Error('WRONGUSERPASS'); + } + + return array('user' => array('admin')); + } + } diff --git a/modules/exampleauth/lib/Auth/Process/RedirectTest.php b/modules/exampleauth/lib/Auth/Process/RedirectTest.php index 4da04c5b770e3973455e1dff5c1e2cf9a0f58b47..7e3e93ee03fae8c09354a4af286c8b4ac52ccc7a 100644 --- a/modules/exampleauth/lib/Auth/Process/RedirectTest.php +++ b/modules/exampleauth/lib/Auth/Process/RedirectTest.php @@ -1,23 +1,28 @@ <?php + /** * A simple processing filter for testing that redirection works as it should. + * */ -class sspmod_exampleauth_Auth_Process_RedirectTest extends SimpleSAML_Auth_ProcessingFilter -{ - /** - * Initialize processing of the redirect test. - * - * @param array &$state The state we should update. - */ - public function process(array &$state) { - assert(array_key_exists('Attributes', $state)); +class sspmod_exampleauth_Auth_Process_RedirectTest extends SimpleSAML_Auth_ProcessingFilter { + + + /** + * Initialize processing of the redirect test. + * + * @param array &$state The state we should update. + */ + public function process(&$state) { + assert(is_array($state)); + assert(array_key_exists('Attributes', $state)); + + // To check whether the state is saved correctly + $state['Attributes']['RedirectTest1'] = array('OK'); - // To check whether the state is saved correctly - $state['Attributes']['RedirectTest1'] = array('OK'); + // Save state and redirect + $id = SimpleSAML_Auth_State::saveState($state, 'exampleauth:redirectfilter-test'); + $url = SimpleSAML\Module::getModuleURL('exampleauth/redirecttest.php'); + \SimpleSAML\Utils\HTTP::redirectTrustedURL($url, array('StateId' => $id)); + } - // Save state and redirect - $id = SimpleSAML_Auth_State::saveState($state, 'exampleauth:redirectfilter-test'); - $url = SimpleSAML\Module::getModuleURL('exampleauth/redirecttest.php'); - \SimpleSAML\Utils\HTTP::redirectTrustedURL($url, array('StateId' => $id)); - } } diff --git a/modules/exampleauth/lib/Auth/Source/External.php b/modules/exampleauth/lib/Auth/Source/External.php index 12046c6679fa80232668ca3a8d7a8540be44ea63..6b37a541a54a569627074c034959d0d2e2f41fd9 100644 --- a/modules/exampleauth/lib/Auth/Source/External.php +++ b/modules/exampleauth/lib/Auth/Source/External.php @@ -20,243 +20,253 @@ * * @package SimpleSAMLphp */ -class sspmod_exampleauth_Auth_Source_External extends SimpleSAML_Auth_Source -{ - /** - * Constructor for this authentication source. - * - * @param array $info Information about this authentication source. - * @param array $config Configuration. - */ - public function __construct(array $info, array $config) - { - // Call the parent constructor first, as required by the interface - parent::__construct($info, $config); - - // Do any other configuration we need here - } - - /** - * Retrieve attributes for the user. - * - * @return array|null The user's attributes, or null if the user isn't authenticated. - */ - private function getUser() - { - /* - * In this example we assume that the attributes are - * stored in the users PHP session, but this could be replaced - * with anything. - */ - - if (!session_id()) { - /* session_start not called before. Do it here. */ - session_start(); - } - - if (!isset($_SESSION['uid'])) { - /* The user isn't authenticated. */ - return null; - } - - /* - * Find the attributes for the user. - * Note that all attributes in SimpleSAMLphp are multivalued, so we need - * to store them as arrays. - */ - - $attributes = array( - 'uid' => array($_SESSION['uid']), - 'displayName' => array($_SESSION['name']), - 'mail' => array($_SESSION['mail']), - ); - - /* Here we generate a multivalued attribute based on the account type. */ - $attributes['eduPersonAffiliation'] = array( - $_SESSION['type'], /* In this example, either 'student' or 'employee'. */ - 'member', - ); - - return $attributes; - } - - /** - * Log in using an external authentication helper. - * - * @param array &$state Information about the current authentication. - */ - public function authenticate(array &$state) - { - $attributes = $this->getUser(); - if ($attributes !== null) { - /* - * The user is already authenticated. - * - * Add the users attributes to the $state-array, and return control - * to the authentication process. - */ - $state['Attributes'] = $attributes; - return; - } - - /* - * The user isn't authenticated. We therefore need to - * send the user to the login page. - */ - - /* - * First we add the identifier of this authentication source - * to the state array, so that we know where to resume. - */ - $state['exampleauth:AuthID'] = $this->authId; - - /* - * We need to save the $state-array, so that we can resume the - * login process after authentication. - * - * Note the second parameter to the saveState-function. This is a - * unique identifier for where the state was saved, and must be used - * again when we retrieve the state. - * - * The reason for it is to prevent - * attacks where the user takes a $state-array saved in one location - * and restores it in another location, and thus bypasses steps in - * the authentication process. - */ - $stateId = SimpleSAML_Auth_State::saveState($state, 'exampleauth:External'); - - /* - * Now we generate a URL the user should return to after authentication. - * We assume that whatever authentication page we send the user to has an - * option to return the user to a specific page afterwards. - */ - $returnTo = SimpleSAML\Module::getModuleURL('exampleauth/resume.php', array( - 'State' => $stateId, - )); - - /* - * Get the URL of the authentication page. - * - * Here we use the getModuleURL function again, since the authentication page - * is also part of this module, but in a real example, this would likely be - * the absolute URL of the login page for the site. - */ - $authPage = SimpleSAML\Module::getModuleURL('exampleauth/authpage.php'); - - /* - * The redirect to the authentication page. - * - * Note the 'ReturnTo' parameter. This must most likely be replaced with - * the real name of the parameter for the login page. - */ - \SimpleSAML\Utils\HTTP::redirectTrustedURL($authPage, array( - 'ReturnTo' => $returnTo, - )); - - /* - * The redirect function never returns, so we never get this far. - */ - assert(false); - } - - /** - * Resume authentication process. - * - * This function resumes the authentication process after the user has - * entered his or her credentials. - * - * @param array &$state The authentication state. - */ - public static function resume() - { - /* - * First we need to restore the $state-array. We should have the identifier for - * it in the 'State' request parameter. - */ - if (!isset($_REQUEST['State'])) { - throw new SimpleSAML_Error_BadRequest('Missing "State" parameter.'); - } - - /* - * Once again, note the second parameter to the loadState function. This must - * match the string we used in the saveState-call above. - */ - $state = SimpleSAML_Auth_State::loadState($_REQUEST['State'], 'exampleauth:External'); - - /* - * Now we have the $state-array, and can use it to locate the authentication - * source. - */ - $source = SimpleSAML_Auth_Source::getById($state['exampleauth:AuthID']); - if ($source === null) { - /* - * The only way this should fail is if we remove or rename the authentication source - * while the user is at the login page. - */ - throw new SimpleSAML_Error_Exception('Could not find authentication source with id ' . $state[self::AUTHID]); - } - - /* - * Make sure that we haven't switched the source type while the - * user was at the authentication page. This can only happen if we - * change config/authsources.php while an user is logging in. - */ - if (! ($source instanceof self)) { - throw new SimpleSAML_Error_Exception('Authentication source type changed.'); - } - - - /* - * OK, now we know that our current state is sane. Time to actually log the user in. - * - * First we check that the user is acutally logged in, and didn't simply skip the login page. - */ - $attributes = $source->getUser(); - if ($attributes === null) { - /* - * The user isn't authenticated. - * - * Here we simply throw an exception, but we could also redirect the user back to the - * login page. - */ - throw new SimpleSAML_Error_Exception('User not authenticated after login page.'); - } - - /* - * So, we have a valid user. Time to resume the authentication process where we - * paused it in the authenticate()-function above. - */ - - $state['Attributes'] = $attributes; - SimpleSAML_Auth_Source::completeAuth($state); - - /* - * The completeAuth-function never returns, so we never get this far. - */ - assert(false); - } - - /** - * This function is called when the user start a logout operation, for example - * by logging out of a SP that supports single logout. - * - * @param array &$state The logout state array. - */ - public function logout(array &$state) - { - if (!session_id()) { - /* session_start not called before. Do it here. */ - session_start(); - } - - /* - * In this example we simply remove the 'uid' from the session. - */ - unset($_SESSION['uid']); - - /* - * If we need to do a redirect to a different page, we could do this - * here, but in this example we don't need to do this. - */ - } +class sspmod_exampleauth_Auth_Source_External extends SimpleSAML_Auth_Source { + + /** + * Constructor for this authentication source. + * + * @param array $info Information about this authentication source. + * @param array $config Configuration. + */ + public function __construct($info, $config) { + assert(is_array($info)); + assert(is_array($config)); + + // Call the parent constructor first, as required by the interface + parent::__construct($info, $config); + + // Do any other configuration we need here + } + + + /** + * Retrieve attributes for the user. + * + * @return array|NULL The user's attributes, or NULL if the user isn't authenticated. + */ + private function getUser() { + + /* + * In this example we assume that the attributes are + * stored in the users PHP session, but this could be replaced + * with anything. + */ + + if (!session_id()) { + /* session_start not called before. Do it here. */ + session_start(); + } + + if (!isset($_SESSION['uid'])) { + /* The user isn't authenticated. */ + return NULL; + } + + /* + * Find the attributes for the user. + * Note that all attributes in SimpleSAMLphp are multivalued, so we need + * to store them as arrays. + */ + + $attributes = array( + 'uid' => array($_SESSION['uid']), + 'displayName' => array($_SESSION['name']), + 'mail' => array($_SESSION['mail']), + ); + + /* Here we generate a multivalued attribute based on the account type. */ + $attributes['eduPersonAffiliation'] = array( + $_SESSION['type'], /* In this example, either 'student' or 'employee'. */ + 'member', + ); + + return $attributes; + } + + + /** + * Log in using an external authentication helper. + * + * @param array &$state Information about the current authentication. + */ + public function authenticate(&$state) { + assert(is_array($state)); + + $attributes = $this->getUser(); + if ($attributes !== NULL) { + /* + * The user is already authenticated. + * + * Add the users attributes to the $state-array, and return control + * to the authentication process. + */ + $state['Attributes'] = $attributes; + return; + } + + /* + * The user isn't authenticated. We therefore need to + * send the user to the login page. + */ + + /* + * First we add the identifier of this authentication source + * to the state array, so that we know where to resume. + */ + $state['exampleauth:AuthID'] = $this->authId; + + + /* + * We need to save the $state-array, so that we can resume the + * login process after authentication. + * + * Note the second parameter to the saveState-function. This is a + * unique identifier for where the state was saved, and must be used + * again when we retrieve the state. + * + * The reason for it is to prevent + * attacks where the user takes a $state-array saved in one location + * and restores it in another location, and thus bypasses steps in + * the authentication process. + */ + $stateId = SimpleSAML_Auth_State::saveState($state, 'exampleauth:External'); + + /* + * Now we generate a URL the user should return to after authentication. + * We assume that whatever authentication page we send the user to has an + * option to return the user to a specific page afterwards. + */ + $returnTo = SimpleSAML\Module::getModuleURL('exampleauth/resume.php', array( + 'State' => $stateId, + )); + + /* + * Get the URL of the authentication page. + * + * Here we use the getModuleURL function again, since the authentication page + * is also part of this module, but in a real example, this would likely be + * the absolute URL of the login page for the site. + */ + $authPage = SimpleSAML\Module::getModuleURL('exampleauth/authpage.php'); + + /* + * The redirect to the authentication page. + * + * Note the 'ReturnTo' parameter. This must most likely be replaced with + * the real name of the parameter for the login page. + */ + \SimpleSAML\Utils\HTTP::redirectTrustedURL($authPage, array( + 'ReturnTo' => $returnTo, + )); + + /* + * The redirect function never returns, so we never get this far. + */ + assert(false); + } + + + /** + * Resume authentication process. + * + * This function resumes the authentication process after the user has + * entered his or her credentials. + * + * @param array &$state The authentication state. + */ + public static function resume() { + + /* + * First we need to restore the $state-array. We should have the identifier for + * it in the 'State' request parameter. + */ + if (!isset($_REQUEST['State'])) { + throw new SimpleSAML_Error_BadRequest('Missing "State" parameter.'); + } + + /* + * Once again, note the second parameter to the loadState function. This must + * match the string we used in the saveState-call above. + */ + $state = SimpleSAML_Auth_State::loadState($_REQUEST['State'], 'exampleauth:External'); + + /* + * Now we have the $state-array, and can use it to locate the authentication + * source. + */ + $source = SimpleSAML_Auth_Source::getById($state['exampleauth:AuthID']); + if ($source === NULL) { + /* + * The only way this should fail is if we remove or rename the authentication source + * while the user is at the login page. + */ + throw new SimpleSAML_Error_Exception('Could not find authentication source with id ' . $state[self::AUTHID]); + } + + /* + * Make sure that we haven't switched the source type while the + * user was at the authentication page. This can only happen if we + * change config/authsources.php while an user is logging in. + */ + if (! ($source instanceof self)) { + throw new SimpleSAML_Error_Exception('Authentication source type changed.'); + } + + + /* + * OK, now we know that our current state is sane. Time to actually log the user in. + * + * First we check that the user is acutally logged in, and didn't simply skip the login page. + */ + $attributes = $source->getUser(); + if ($attributes === NULL) { + /* + * The user isn't authenticated. + * + * Here we simply throw an exception, but we could also redirect the user back to the + * login page. + */ + throw new SimpleSAML_Error_Exception('User not authenticated after login page.'); + } + + /* + * So, we have a valid user. Time to resume the authentication process where we + * paused it in the authenticate()-function above. + */ + + $state['Attributes'] = $attributes; + SimpleSAML_Auth_Source::completeAuth($state); + + /* + * The completeAuth-function never returns, so we never get this far. + */ + assert(false); + } + + + /** + * This function is called when the user start a logout operation, for example + * by logging out of a SP that supports single logout. + * + * @param array &$state The logout state array. + */ + public function logout(&$state) { + assert(is_array($state)); + + if (!session_id()) { + /* session_start not called before. Do it here. */ + session_start(); + } + + /* + * In this example we simply remove the 'uid' from the session. + */ + unset($_SESSION['uid']); + + /* + * If we need to do a redirect to a different page, we could do this + * here, but in this example we don't need to do this. + */ + } + } diff --git a/modules/exampleauth/lib/Auth/Source/Static.php b/modules/exampleauth/lib/Auth/Source/Static.php index e395978a0cbcb40761c9de82f0ec98373b8ba03a..8c5eba05715bceea091c129b8ec79e56f8d722dd 100644 --- a/modules/exampleauth/lib/Auth/Source/Static.php +++ b/modules/exampleauth/lib/Auth/Source/Static.php @@ -6,43 +6,52 @@ * This class is an example authentication source which will always return a user with * a static set of attributes. * + * @author Olav Morken, UNINETT AS. * @package SimpleSAMLphp */ -class sspmod_exampleauth_Auth_Source_Static extends SimpleSAML_Auth_Source -{ - /** - * The attributes we return. - */ - private $attributes; - - /** - * Constructor for this authentication source. - * - * @param array $info Information about this authentication source. - * @param array $config Configuration. - */ - public function __construct(array $info, array $config) - { - // Call the parent constructor first, as required by the interface - parent::__construct($info, $config); - - // Parse attributes - try { - $this->attributes = SimpleSAML\Utils\Attributes::normalizeAttributesArray($config); - } catch(Exception $e) { - throw new Exception('Invalid attributes for authentication source ' . - $this->authId . ': ' . $e->getMessage()); - } - - } - - /** - * Log in using static attributes. - * - * @param array &$state Information about the current authentication. - */ - public function authenticate(array &$state) - { - $state['Attributes'] = $this->attributes; - } +class sspmod_exampleauth_Auth_Source_Static extends SimpleSAML_Auth_Source { + + + /** + * The attributes we return. + */ + private $attributes; + + + /** + * Constructor for this authentication source. + * + * @param array $info Information about this authentication source. + * @param array $config Configuration. + */ + public function __construct($info, $config) { + assert(is_array($info)); + assert(is_array($config)); + + // Call the parent constructor first, as required by the interface + parent::__construct($info, $config); + + + // Parse attributes + try { + $this->attributes = SimpleSAML\Utils\Attributes::normalizeAttributesArray($config); + } catch(Exception $e) { + throw new Exception('Invalid attributes for authentication source ' . + $this->authId . ': ' . $e->getMessage()); + } + + } + + + /** + * Log in using static attributes. + * + * @param array &$state Information about the current authentication. + */ + public function authenticate(&$state) { + assert(is_array($state)); + + $state['Attributes'] = $this->attributes; + } + } diff --git a/modules/exampleauth/lib/Auth/Source/UserPass.php b/modules/exampleauth/lib/Auth/Source/UserPass.php index cc1353d31e5063e2ba77353df1a1fa88e3aa3d58..8582d1c7c989a28af3f233d18cb72c806f39d0b8 100644 --- a/modules/exampleauth/lib/Auth/Source/UserPass.php +++ b/modules/exampleauth/lib/Auth/Source/UserPass.php @@ -6,79 +6,85 @@ * This class is an example authentication source which stores all username/passwords in an array, * and authenticates users against this array. * + * @author Olav Morken, UNINETT AS. * @package SimpleSAMLphp */ -class sspmod_exampleauth_Auth_Source_UserPass extends sspmod_core_Auth_UserPassBase -{ - /** - * Our users, stored in an associative array. The key of the array is "<username>:<password>", - * while the value of each element is a new array with the attributes for each user. - */ - private $users; - - /** - * Constructor for this authentication source. - * - * @param array $info Information about this authentication source. - * @param array $config Configuration. - */ - public function __construct(array $info, array $config) - { - // Call the parent constructor first, as required by the interface - parent::__construct($info, $config); - - $this->users = array(); - - // Validate and parse our configuration - foreach ($config as $userpass => $attributes) { - if (!is_string($userpass)) { - throw new Exception('Invalid <username>:<password> for authentication source ' . - $this->authId . ': ' . $userpass); - } - - $userpass = explode(':', $userpass, 2); - if (count($userpass) !== 2) { - throw new Exception('Invalid <username>:<password> for authentication source ' . - $this->authId . ': ' . $userpass[0]); - } - $username = $userpass[0]; - $password = $userpass[1]; - - try { - $attributes = SimpleSAML\Utils\Attributes::normalizeAttributesArray($attributes); - } catch(Exception $e) { - throw new Exception('Invalid attributes for user ' . $username . - ' in authentication source ' . $this->authId . ': ' . - $e->getMessage()); - } - - $this->users[$username . ':' . $password] = $attributes; - } - } - - /** - * Attempt to log in using the given username and password. - * - * On a successful login, this function should return the users attributes. On failure, - * it should throw an exception. If the error was caused by the user entering the wrong - * username or password, a SimpleSAML_Error_Error('WRONGUSERPASS') should be thrown. - * - * Note that both the username and the password are UTF-8 encoded. - * - * @param string $username The username the user wrote. - * @param string $password The password the user wrote. - * @return array Associative array with the users attributes. - */ - protected function login($username, $password) - { - assert(is_string($username)); - assert(is_string($password)); - - $userpass = $username . ':' . $password; - if (!array_key_exists($userpass, $this->users)) { - throw new SimpleSAML_Error_Error('WRONGUSERPASS'); - } - - return $this->users[$userpass]; - } +class sspmod_exampleauth_Auth_Source_UserPass extends sspmod_core_Auth_UserPassBase { + + + /** + * Our users, stored in an associative array. The key of the array is "<username>:<password>", + * while the value of each element is a new array with the attributes for each user. + */ + private $users; + + + /** + * Constructor for this authentication source. + * + * @param array $info Information about this authentication source. + * @param array $config Configuration. + */ + public function __construct($info, $config) { + assert(is_array($info)); + assert(is_array($config)); + + // Call the parent constructor first, as required by the interface + parent::__construct($info, $config); + + $this->users = array(); + + // Validate and parse our configuration + foreach ($config as $userpass => $attributes) { + if (!is_string($userpass)) { + throw new Exception('Invalid <username>:<password> for authentication source ' . + $this->authId . ': ' . $userpass); + } + + $userpass = explode(':', $userpass, 2); + if (count($userpass) !== 2) { + throw new Exception('Invalid <username>:<password> for authentication source ' . + $this->authId . ': ' . $userpass[0]); + } + $username = $userpass[0]; + $password = $userpass[1]; + + try { + $attributes = SimpleSAML\Utils\Attributes::normalizeAttributesArray($attributes); + } catch(Exception $e) { + throw new Exception('Invalid attributes for user ' . $username . + ' in authentication source ' . $this->authId . ': ' . + $e->getMessage()); + } + + $this->users[$username . ':' . $password] = $attributes; + } + } + + + /** + * Attempt to log in using the given username and password. + * + * On a successful login, this function should return the users attributes. On failure, + * it should throw an exception. If the error was caused by the user entering the wrong + * username or password, a SimpleSAML_Error_Error('WRONGUSERPASS') should be thrown. + * + * Note that both the username and the password are UTF-8 encoded. + * + * @param string $username The username the user wrote. + * @param string $password The password the user wrote. + * @return array Associative array with the users attributes. + */ + protected function login($username, $password) { + assert(is_string($username)); + assert(is_string($password)); + + $userpass = $username . ':' . $password; + if (!array_key_exists($userpass, $this->users)) { + throw new SimpleSAML_Error_Error('WRONGUSERPASS'); + } + + return $this->users[$userpass]; + } + } diff --git a/modules/exampleauth/www/authpage.php b/modules/exampleauth/www/authpage.php index 13f95a56c6d31c4f319963c90a299ac45b509849..73fcb131ecd9df5ce0bd4b82a41ad5502e0e95a1 100644 --- a/modules/exampleauth/www/authpage.php +++ b/modules/exampleauth/www/authpage.php @@ -10,7 +10,7 @@ */ if (!isset($_REQUEST['ReturnTo'])) { - die('Missing ReturnTo parameter.'); + die('Missing ReturnTo parameter.'); } $returnTo = \SimpleSAML\Utils\HTTP::checkURLAllowed($_REQUEST['ReturnTo']); @@ -27,7 +27,7 @@ $returnTo = \SimpleSAML\Utils\HTTP::checkURLAllowed($_REQUEST['ReturnTo']); */ if (!preg_match('@State=(.*)@', $returnTo, $matches)) { - die('Invalid ReturnTo URL for this example.'); + die('Invalid ReturnTo URL for this example.'); } SimpleSAML_Auth_State::loadState(urldecode($matches[1]), 'exampleauth:External'); @@ -42,20 +42,20 @@ SimpleSAML_Auth_State::loadState(urldecode($matches[1]), 'exampleauth:External') * Our list of users. */ $users = array( - 'student' => array( - 'password' => 'student', - 'uid' => 'student', - 'name' => 'Student Name', - 'mail' => 'somestudent@example.org', - 'type' => 'student', - ), - 'admin' => array( - 'password' => 'admin', - 'uid' => 'admin', - 'name' => 'Admin Name', - 'mail' => 'someadmin@example.org', - 'type' => 'employee', - ), + 'student' => array( + 'password' => 'student', + 'uid' => 'student', + 'name' => 'Student Name', + 'mail' => 'somestudent@example.org', + 'type' => 'student', + ), + 'admin' => array( + 'password' => 'admin', + 'uid' => 'admin', + 'name' => 'Admin Name', + 'mail' => 'someadmin@example.org', + 'type' => 'employee', + ), ); @@ -64,29 +64,29 @@ $users = array( * Since this is a dummy example, we accept any data. */ -$badUserPass = false; +$badUserPass = FALSE; if ($_SERVER['REQUEST_METHOD'] === 'POST') { - $username = (string)$_REQUEST['username']; - $password = (string)$_REQUEST['password']; + $username = (string)$_REQUEST['username']; + $password = (string)$_REQUEST['password']; - if (!isset($users[$username]) || $users[$username]['password'] !== $password) { - $badUserPass = true; - } else { + if (!isset($users[$username]) || $users[$username]['password'] !== $password) { + $badUserPass = TRUE; + } else { - $user = $users[$username]; + $user = $users[$username]; - if (!session_id()) { - // session_start not called before. Do it here. - session_start(); - } + if (!session_id()) { + // session_start not called before. Do it here. + session_start(); + } - $_SESSION['uid'] = $user['uid']; - $_SESSION['name'] = $user['name']; - $_SESSION['mail'] = $user['mail']; - $_SESSION['type'] = $user['type']; + $_SESSION['uid'] = $user['uid']; + $_SESSION['name'] = $user['name']; + $_SESSION['mail'] = $user['mail']; + $_SESSION['type'] = $user['type']; - \SimpleSAML\Utils\HTTP::redirectTrustedURL($returnTo); - } + \SimpleSAML\Utils\HTTP::redirectTrustedURL($returnTo); + } } diff --git a/modules/exampleauth/www/redirecttest.php b/modules/exampleauth/www/redirecttest.php index 883f94ab4db9397b93003b2d5e4b8a4a793cba45..96ff9a50f7bd3d229d9a32ca5f0fd48b9ed14ed0 100644 --- a/modules/exampleauth/www/redirecttest.php +++ b/modules/exampleauth/www/redirecttest.php @@ -1,12 +1,14 @@ <?php + /** * Request handler for redirect filter test. * + * @author Olav Morken, UNINETT AS. * @package SimpleSAMLphp */ if (!array_key_exists('StateId', $_REQUEST)) { - throw new SimpleSAML_Error_BadRequest('Missing required StateId query parameter.'); + throw new SimpleSAML_Error_BadRequest('Missing required StateId query parameter.'); } $state = SimpleSAML_Auth_State::loadState($_REQUEST['StateId'], 'exampleauth:redirectfilter-test'); diff --git a/modules/exampleauth/www/resume.php b/modules/exampleauth/www/resume.php index ec04a028b47f0d84990be2ccf76796fed06ff52b..08d66dd3f490d198e5467665d21204d8c6afd64b 100644 --- a/modules/exampleauth/www/resume.php +++ b/modules/exampleauth/www/resume.php @@ -1,4 +1,5 @@ <?php + /** * This page serves as the point where the user's authentication * process is resumed after the login page. diff --git a/modules/expirycheck/lib/Auth/Process/ExpiryDate.php b/modules/expirycheck/lib/Auth/Process/ExpiryDate.php index a1384eb3383ddf23ff83e7494361d6e8c441f8cc..c315169fa97f29ec7079be03d925f06723de3332 100644 --- a/modules/expirycheck/lib/Auth/Process/ExpiryDate.php +++ b/modules/expirycheck/lib/Auth/Process/ExpiryDate.php @@ -1,4 +1,5 @@ <?php + /** * Filter which show "about to expire" warning or deny access if netid is expired. * @@ -15,130 +16,140 @@ * ), * </code> * + * @author Alex Mihičinac, ARNES. <alexm@arnes.si> * @package SimpleSAMLphp */ -class sspmod_expirycheck_Auth_Process_ExpiryDate extends SimpleSAML_Auth_ProcessingFilter -{ - private $warndaysbefore = 0; - private $netid_attr = null; - private $expirydate_attr = null; - private $date_format = 'd.m.Y'; - - /** - * Initialize this filter. - * - * @param array $config Configuration information about this filter. - * @param mixed $reserved For future use. - */ - public function __construct(array $config, $reserved) - { - parent::__construct($config, $reserved); - - if (array_key_exists('warndaysbefore', $config)) { - $this->warndaysbefore = $config['warndaysbefore']; - if (!is_string($this->warndaysbefore)) { - throw new Exception('Invalid value for number of days given to expirycheck::ExpiryDate filter.'); - } - } - - if (array_key_exists('netid_attr', $config)) { - $this->netid_attr = $config['netid_attr']; - if (!is_string($this->netid_attr)) { - throw new Exception('Invalid attribute name given as eduPersonPrincipalName to expirycheck::ExpiryDate filter.'); - } - } - - if (array_key_exists('expirydate_attr', $config)) { - $this->expirydate_attr = $config['expirydate_attr']; - if (!is_string($this->expirydate_attr)) { - throw new Exception('Invalid attribute name given as schacExpiryDate to expirycheck::ExpiryDate filter.'); - } - } - - if (array_key_exists('date_format', $config)) { - $this->date_format = $config['date_format']; - if (!is_string($this->date_format)) { - throw new Exception('Invalid date format given to expirycheck::ExpiryDate filter.'); - } - } - } - - /** - * Show expirational warning if remaining days is equal or under defined $warndaysbefore - * @param array $state Current authenticaton state. - * @param integer $expireOnDate - * @param integer $warndaysbefore - * @return bool - */ - private function shWarning(array &$state, $expireOnDate, $warndaysbefore) { - $now = time(); - $end = $expireOnDate; - - if ($expireOnDate >= $now) { - $days = (int)(($end - $now) / (24*60*60)); - if ($days <= $warndaysbefore) { - $state['daysleft'] = $days; - return true; - } - } - return false; - } - - /** - * Check if given date is older than today - * @param integer $expireOnDate - * @return bool - * - */ - private function checkDate($expireOnDate) - { - $now = time(); - $end = $expireOnDate; - - return ($now <= $end); - } - - /** - * Apply filter - * - * @param array &$state The current state. - */ - public function process(array &$state) - { - /* - * UTC format: 20090527080352Z - */ - $netId = $state['Attributes'][$this->netid_attr][0]; - $expireOnDate = strtotime($state['Attributes'][$this->expirydate_attr][0]); - - if (self::shWarning($state, $expireOnDate, $this->warndaysbefore)) { - assert(is_array($state)); - if (isset($state['isPassive']) && $state['isPassive'] === true) { - // We have a passive request. Skip the warning. - return; - } - - SimpleSAML\Logger::warning('expirycheck: NetID ' . $netId . - ' is about to expire!'); - - // Save state and redirect - $state['expireOnDate'] = date($this->date_format, $expireOnDate); - $state['netId'] = $netId; - $id = SimpleSAML_Auth_State::saveState($state, 'expirywarning:about2expire'); - $url = SimpleSAML\Module::getModuleURL('expirycheck/about2expire.php'); - \SimpleSAML\Utils\HTTP::redirectTrustedURL($url, array('StateId' => $id)); - } - - if (!self::checkDate($expireOnDate)) { - SimpleSAML\Logger::error('expirycheck: NetID ' . $netId . - ' has expired [' . date($this->date_format, $expireOnDate) . ']. Access denied!'); - - /* Save state and redirect. */ - $state['expireOnDate'] = date($this->date_format, $expireOnDate); - $state['netId'] = $netId; - $id = SimpleSAML_Auth_State::saveState($state, 'expirywarning:expired'); - $url = SimpleSAML\Module::getModuleURL('expirycheck/expired.php'); - \SimpleSAML\Utils\HTTP::redirectTrustedURL($url, array('StateId' => $id)); - } - } + +class sspmod_expirycheck_Auth_Process_ExpiryDate extends SimpleSAML_Auth_ProcessingFilter { + + private $warndaysbefore = 0; + private $netid_attr = NULL; + private $expirydate_attr = NULL; + private $date_format = 'd.m.Y'; + + + /** + * Initialize this filter. + * + * @param array $config Configuration information about this filter. + * @param mixed $reserved For future use. + */ + public function __construct($config, $reserved) { + parent::__construct($config, $reserved); + + assert(is_array($config)); + + if (array_key_exists('warndaysbefore', $config)) { + $this->warndaysbefore = $config['warndaysbefore']; + if (!is_string($this->warndaysbefore)) { + throw new Exception('Invalid value for number of days given to expirycheck::ExpiryDate filter.'); + } + } + + if (array_key_exists('netid_attr', $config)) { + $this->netid_attr = $config['netid_attr']; + if (!is_string($this->netid_attr)) { + throw new Exception('Invalid attribute name given as eduPersonPrincipalName to expirycheck::ExpiryDate filter.'); + } + } + + if (array_key_exists('expirydate_attr', $config)) { + $this->expirydate_attr = $config['expirydate_attr']; + if (!is_string($this->expirydate_attr)) { + throw new Exception('Invalid attribute name given as schacExpiryDate to expirycheck::ExpiryDate filter.'); + } + } + + if (array_key_exists('date_format', $config)) { + $this->date_format = $config['date_format']; + if (!is_string($this->date_format)) { + throw new Exception('Invalid date format given to expirycheck::ExpiryDate filter.'); + } + } + } + + /** + * Show expirational warning if remaining days is equal or under defined $warndaysbefore + * @param integer $expireOnDate + * @param integer $warndaysbefore + * @return bool + * + */ + public function shWarning(&$state, $expireOnDate, $warndaysbefore) { + $now = time(); + $end = $expireOnDate; + + if ($expireOnDate >= $now) { + $days = (int)(($end - $now) / (24*60*60)); + if ($days <= $warndaysbefore) { + $state['daysleft'] = $days; + return true; + } + } + return false; + } + + /** + * Check if given date is older than today + * @param integer $expireOnDate + * @return bool + * + */ + public function checkDate($expireOnDate) { + $now = time(); + $end = $expireOnDate; + + if ($now <= $end) { + return true; + } else { + return false; + } + + } + + /** + * Apply filter + * + * @param array &$state The current state. + */ + public function process(&$state) { + /* + * UTC format: 20090527080352Z + */ + $netId = $state['Attributes'][$this->netid_attr][0]; + $expireOnDate = strtotime($state['Attributes'][$this->expirydate_attr][0]); + + if (self::shWarning($state, $expireOnDate, $this->warndaysbefore)) { + assert(is_array($state)); + if (isset($state['isPassive']) && $state['isPassive'] === TRUE) { + // We have a passive request. Skip the warning. + return; + } + + SimpleSAML\Logger::warning('expirycheck: NetID ' . $netId . + ' is about to expire!'); + + // Save state and redirect + $state['expireOnDate'] = date($this->date_format, $expireOnDate); + $state['netId'] = $netId; + $id = SimpleSAML_Auth_State::saveState($state, 'expirywarning:about2expire'); + $url = SimpleSAML\Module::getModuleURL('expirycheck/about2expire.php'); + \SimpleSAML\Utils\HTTP::redirectTrustedURL($url, array('StateId' => $id)); + } + + if (!self::checkDate($expireOnDate)) { + SimpleSAML\Logger::error('expirycheck: NetID ' . $netId . + ' has expired [' . date($this->date_format, $expireOnDate) . ']. Access denied!'); + + /* Save state and redirect. */ + $state['expireOnDate'] = date($this->date_format, $expireOnDate); + $state['netId'] = $netId; + $id = SimpleSAML_Auth_State::saveState($state, 'expirywarning:expired'); + $url = SimpleSAML\Module::getModuleURL('expirycheck/expired.php'); + \SimpleSAML\Utils\HTTP::redirectTrustedURL($url, array('StateId' => $id)); + + } + } + + } diff --git a/modules/ldap/lib/Auth/Process/AttributeAddFromLDAP.php b/modules/ldap/lib/Auth/Process/AttributeAddFromLDAP.php index 35d25f71d38ba24dd5ae5d96c8128b5d072bb098..e788d268906f944afddb984aa30d039c405d754a 100644 --- a/modules/ldap/lib/Auth/Process/AttributeAddFromLDAP.php +++ b/modules/ldap/lib/Auth/Process/AttributeAddFromLDAP.php @@ -1,11 +1,40 @@ <?php + /** * Filter to add attributes to the identity by executing a query against an LDAP directory * + * Original Author: Steve Moitozo II <steve_moitozo@jaars.org> + * Created: 20100513 + * Updated: 20100920 Steve Moitozo II + * - incorporated feedback from Olav Morken to prep code for inclusion in SimpleSAMLphp distro + * - moved call to ldap_set_options() inside test for $ds + * - added the output of ldap_error() to the exceptions + * - reduced some of the nested ifs + * - added support for multiple values + * - added support for anonymous binds + * - added escaping of search filter and attribute + * Updated: 20111118 Ryan Panning + * - Updated the class to use BaseFilter which reuses LDAP connection features + * - Added conversion of original filter option names for backwards-compatibility + * - Updated the constructor to use the new config method + * - Updated the process method to use the new config variable names + * Updated: 20131119 Yørn de Jong / Jaime Perez + * - Added support for retrieving multiple values at once from LDAP + * - Don't crash but fail silently on LDAP errors; the plugin is to complement attributes + * Updated: 20161223 Remy Blom <remy.blom@hku.nl> + * - Adjusted the silent fail so it does show a warning in log when $this->getLdap() fails + * + * @author Yørn de Jong + * @author Jaime Perez + * @author Steve Moitozo + * @author JAARS, Inc. + * @author Ryan Panning + * @author Remy Blom <remy.blom@hku.nl> * @package SimpleSAMLphp */ class sspmod_ldap_Auth_Process_AttributeAddFromLDAP extends sspmod_ldap_Auth_Process_BaseFilter { + /** * LDAP attributes to add to the request attributes * @@ -13,6 +42,7 @@ class sspmod_ldap_Auth_Process_AttributeAddFromLDAP extends sspmod_ldap_Auth_Pro */ protected $search_attributes; + /** * LDAP search filter to use in the LDAP query * @@ -20,6 +50,7 @@ class sspmod_ldap_Auth_Process_AttributeAddFromLDAP extends sspmod_ldap_Auth_Pro */ protected $search_filter; + /** * What to do with attributes when the target already exists. Either replace, merge or add. * @@ -33,7 +64,7 @@ class sspmod_ldap_Auth_Process_AttributeAddFromLDAP extends sspmod_ldap_Auth_Pro * @param array $config Configuration information about this filter. * @param mixed $reserved For future use. */ - public function __construct(array $config, $reserved) + public function __construct($config, $reserved) { /* * For backwards compatibility, check for old config names @@ -104,8 +135,9 @@ class sspmod_ldap_Auth_Process_AttributeAddFromLDAP extends sspmod_ldap_Auth_Pro * * @param array &$request The current request */ - public function process(array &$request) + public function process(&$request) { + assert(is_array($request)); assert(array_key_exists('Attributes', $request)); $attributes =& $request['Attributes']; diff --git a/modules/ldap/lib/Auth/Process/AttributeAddUsersGroups.php b/modules/ldap/lib/Auth/Process/AttributeAddUsersGroups.php index 7fd1d7820363a6e6f4c0d475c85d84e1064fd899..8fa7c2ccf2a9b9661434ba9917942f11513ecde7 100644 --- a/modules/ldap/lib/Auth/Process/AttributeAddUsersGroups.php +++ b/modules/ldap/lib/Auth/Process/AttributeAddUsersGroups.php @@ -1,9 +1,11 @@ <?php + /** * Does a reverse membership lookup on the logged in user, * looking for groups it is a member of and adds them to * a defined attribute, in DN format. * + * @author Ryan Panning <panman@traileyes.com> * @package SimpleSAMLphp */ class sspmod_ldap_Auth_Process_AttributeAddUsersGroups extends sspmod_ldap_Auth_Process_BaseFilter @@ -15,10 +17,11 @@ class sspmod_ldap_Auth_Process_AttributeAddUsersGroups extends sspmod_ldap_Auth_ * are then added to the request attributes. * * @throws SimpleSAML_Error_Exception - * @param array $request + * @param $request */ - public function process(array &$request) + public function process(&$request) { + assert(is_array($request)); assert(array_key_exists('Attributes', $request)); // Log the process @@ -58,6 +61,7 @@ class sspmod_ldap_Auth_Process_AttributeAddUsersGroups extends sspmod_ldap_Auth_ ); } + /** * This section of code was broken out because the child * filter AuthorizeByGroup can use this method as well. @@ -69,7 +73,7 @@ class sspmod_ldap_Auth_Process_AttributeAddUsersGroups extends sspmod_ldap_Auth_ * @param array $attributes * @return array */ - protected function getGroups(array $attributes) + protected function getGroups($attributes) { // Log the request SimpleSAML\Logger::debug( @@ -120,6 +124,7 @@ class sspmod_ldap_Auth_Process_AttributeAddUsersGroups extends sspmod_ldap_Auth_ return $groups; } + /** * OpenLDAP optimized search * using the required attribute values from the user to @@ -129,7 +134,7 @@ class sspmod_ldap_Auth_Process_AttributeAddUsersGroups extends sspmod_ldap_Auth_ * @param array $attributes * @return array */ - protected function getGroupsOpenLdap(array $attributes) + protected function getGroupsOpenLdap($attributes) { // Log the OpenLDAP specific search SimpleSAML\Logger::debug( @@ -161,6 +166,7 @@ class sspmod_ldap_Auth_Process_AttributeAddUsersGroups extends sspmod_ldap_Auth_ return $groups; } + /** * Active Directory optimized search * using the required attribute values from the user to @@ -170,7 +176,7 @@ class sspmod_ldap_Auth_Process_AttributeAddUsersGroups extends sspmod_ldap_Auth_ * @param array $attributes * @return array */ - protected function getGroupsActiveDirectory(array $attributes) + protected function getGroupsActiveDirectory($attributes) { // Log the AD specific search SimpleSAML\Logger::debug( @@ -208,8 +214,10 @@ class sspmod_ldap_Auth_Process_AttributeAddUsersGroups extends sspmod_ldap_Auth_ * @param array $memberof * @return array */ - protected function search(array $memberof) + protected function search($memberof) { + assert(is_array($memberof)); + // Used to determine what DN's have already been searched static $searched = array(); @@ -276,6 +284,7 @@ class sspmod_ldap_Auth_Process_AttributeAddUsersGroups extends sspmod_ldap_Auth_ return array_unique($groups); } + /** * Searches LDAP using a ActiveDirectory specific filter, * looking for group membership for the users DN. Returns diff --git a/modules/ldap/lib/Auth/Process/BaseFilter.php b/modules/ldap/lib/Auth/Process/BaseFilter.php index 1f4270184c66a1bf8d8724a4dba7f1be7e57c3eb..d7116a2d835ec3b6c101b2f4d882123631809093 100644 --- a/modules/ldap/lib/Auth/Process/BaseFilter.php +++ b/modules/ldap/lib/Auth/Process/BaseFilter.php @@ -1,13 +1,20 @@ <?php + /** * This base LDAP filter class can be extended to enable real * filter classes direct access to the authsource ldap config * and connects to the ldap server. * + * Updated: 20161223 Remy Blom + * - Wrapped the building of authsource config with issets + * + * @author Ryan Panning <panman@traileyes.com> + * @author Remy Blom <remy.blom@hku.nl> * @package SimpleSAMLphp */ abstract class sspmod_ldap_Auth_Process_BaseFilter extends SimpleSAML_Auth_ProcessingFilter { + /** * List of attribute "alias's" linked to the real attribute * name. Used for abstraction / configuration of the LDAP @@ -17,6 +24,7 @@ abstract class sspmod_ldap_Auth_Process_BaseFilter extends SimpleSAML_Auth_Proce */ protected $attribute_map; + /** * The base DN of the LDAP connection. Used when searching * the LDAP server. @@ -25,6 +33,7 @@ abstract class sspmod_ldap_Auth_Process_BaseFilter extends SimpleSAML_Auth_Proce */ protected $base_dn; + /** * The construct method will change the filter config into * a SimpleSAML_Configuration object and store it here for @@ -34,6 +43,7 @@ abstract class sspmod_ldap_Auth_Process_BaseFilter extends SimpleSAML_Auth_Proce */ protected $config; + /** * Instance, object of the ldap connection. Stored here to * be access later during processing. @@ -42,6 +52,7 @@ abstract class sspmod_ldap_Auth_Process_BaseFilter extends SimpleSAML_Auth_Proce */ private $ldap; + /** * Many times a LDAP product specific query can be used to * speed up or reduce the filter process. This helps the @@ -52,6 +63,7 @@ abstract class sspmod_ldap_Auth_Process_BaseFilter extends SimpleSAML_Auth_Proce */ protected $product; + /** * The class "title" used in logging and exception messages. * This should be prepended to the beginning of the message. @@ -60,6 +72,7 @@ abstract class sspmod_ldap_Auth_Process_BaseFilter extends SimpleSAML_Auth_Proce */ protected $title = 'ldap:BaseFilter : '; + /** * List of LDAP object types, used to determine the type of * object that a DN references. @@ -68,6 +81,7 @@ abstract class sspmod_ldap_Auth_Process_BaseFilter extends SimpleSAML_Auth_Proce */ protected $type_map; + /** * Checks the authsource, if defined, for configuration values * to the LDAP server. Then sets up the LDAP connection for the @@ -77,7 +91,7 @@ abstract class sspmod_ldap_Auth_Process_BaseFilter extends SimpleSAML_Auth_Proce * @param array $config * @param $reserved */ - public function __construct(array &$config, $reserved) + public function __construct(&$config, $reserved) { parent::__construct($config, $reserved); diff --git a/modules/ldap/lib/Auth/Source/LDAP.php b/modules/ldap/lib/Auth/Source/LDAP.php index 08d51cdd1ee26406aaa10f4a8303e11f0b00408f..2e2144b8f54351dc56585460db44c528cb8beef6 100644 --- a/modules/ldap/lib/Auth/Source/LDAP.php +++ b/modules/ldap/lib/Auth/Source/LDAP.php @@ -12,19 +12,24 @@ */ class sspmod_ldap_Auth_Source_LDAP extends sspmod_core_Auth_UserPassBase { + /** * A LDAP configuration object. */ private $ldapConfig; + /** * Constructor for this authentication source. * * @param array $info Information about this authentication source. * @param array $config Configuration. */ - public function __construct(array $info, array $config) + public function __construct($info, $config) { + assert(is_array($info)); + assert(is_array($config)); + // Call the parent constructor first, as required by the interface parent::__construct($info, $config); @@ -32,6 +37,7 @@ class sspmod_ldap_Auth_Source_LDAP extends sspmod_core_Auth_UserPassBase 'Authentication source ' . var_export($this->authId, true)); } + /** * Attempt to log in using the given username and password. * @@ -47,4 +53,5 @@ class sspmod_ldap_Auth_Source_LDAP extends sspmod_core_Auth_UserPassBase return $this->ldapConfig->login($username, $password, $sasl_args); } + } diff --git a/modules/ldap/lib/Auth/Source/LDAPMulti.php b/modules/ldap/lib/Auth/Source/LDAPMulti.php index 6cf4f3570072d77a7114ab42ce8431d5a4c3d6a9..c11a43e469f0b9145d02051361a7e29618a6e7fd 100644 --- a/modules/ldap/lib/Auth/Source/LDAPMulti.php +++ b/modules/ldap/lib/Auth/Source/LDAPMulti.php @@ -12,6 +12,7 @@ */ class sspmod_ldap_Auth_Source_LDAPMulti extends sspmod_core_Auth_UserPassOrgBase { + /** * An array with descriptions for organizations. */ @@ -27,20 +28,25 @@ class sspmod_ldap_Auth_Source_LDAPMulti extends sspmod_core_Auth_UserPassOrgBase */ private $includeOrgInUsername; + /** * Constructor for this authentication source. * * @param array $info Information about this authentication source. * @param array $config Configuration. */ - public function __construct(array $info, array $config) + public function __construct($info, $config) { + assert(is_array($info)); + assert(is_array($config)); + // Call the parent constructor first, as required by the interface parent::__construct($info, $config); $cfgHelper = SimpleSAML_Configuration::loadFromArray($config, 'Authentication source ' . var_export($this->authId, true)); + $this->orgs = array(); $this->ldapOrgs = array(); foreach ($config as $name => $value) { @@ -75,6 +81,7 @@ class sspmod_ldap_Auth_Source_LDAPMulti extends sspmod_core_Auth_UserPassOrgBase } } + /** * Attempt to log in using the given username and password. * @@ -104,6 +111,7 @@ class sspmod_ldap_Auth_Source_LDAPMulti extends sspmod_core_Auth_UserPassOrgBase return $this->ldapOrgs[$org]->login($username, $password, $sasl_args); } + /** * Retrieve list of organizations. * diff --git a/modules/multiauth/lib/Auth/Source/MultiAuth.php b/modules/multiauth/lib/Auth/Source/MultiAuth.php index f22918ab6fad94cd1d23ffa0162b18a715d07f61..f63bcce9d4c26e1d7b61548e320e777a89551a10 100644 --- a/modules/multiauth/lib/Auth/Source/MultiAuth.php +++ b/modules/multiauth/lib/Auth/Source/MultiAuth.php @@ -1,223 +1,234 @@ <?php + /** * Authentication source which let the user chooses among a list of * other authentication sources * + * @author Lorenzo Gil, Yaco Sistemas S.L. * @package SimpleSAMLphp */ -class sspmod_multiauth_Auth_Source_MultiAuth extends SimpleSAML_Auth_Source -{ - /** - * The key of the AuthId field in the state. - */ - const AUTHID = 'sspmod_multiauth_Auth_Source_MultiAuth.AuthId'; - - /** - * The string used to identify our states. - */ - const STAGEID = 'sspmod_multiauth_Auth_Source_MultiAuth.StageId'; - - /** - * The key where the sources is saved in the state. - */ - const SOURCESID = 'sspmod_multiauth_Auth_Source_MultiAuth.SourceId'; - - /** - * The key where the selected source is saved in the session. - */ - const SESSION_SOURCE = 'multiauth:selectedSource'; - - /** - * Array of sources we let the user chooses among. - */ - private $sources; - - /** - * Constructor for this authentication source. - * - * @param array $info Information about this authentication source. - * @param array $config Configuration. - */ - public function __construct(array $info, array $config) { - // Call the parent constructor first, as required by the interface - parent::__construct($info, $config); - - if (!array_key_exists('sources', $config)) { - throw new Exception('The required "sources" config option was not found'); - } - - $globalConfiguration = SimpleSAML_Configuration::getInstance(); - $defaultLanguage = $globalConfiguration->getString('language.default', 'en'); - $authsources = SimpleSAML_Configuration::getConfig('authsources.php'); - $this->sources = array(); - foreach($config['sources'] as $source => $info) { - - if (is_int($source)) { // Backwards compatibility - $source = $info; - $info = array(); - } - - if (array_key_exists('text', $info)) { - $text = $info['text']; - } else { - $text = array($defaultLanguage => $source); - } - - if (array_key_exists('css-class', $info)) { - $css_class = $info['css-class']; - } else { - // Use the authtype as the css class - $authconfig = $authsources->getArray($source, NULL); - if (!array_key_exists(0, $authconfig) || !is_string($authconfig[0])) { - $css_class = ""; - } else { - $css_class = str_replace(":", "-", $authconfig[0]); - } - } - - $this->sources[] = array( - 'source' => $source, - 'text' => $text, - 'css_class' => $css_class, - ); - } - } - - /** - * Prompt the user with a list of authentication sources. - * - * This method saves the information about the configured sources, - * and redirects to a page where the user must select one of these - * authentication sources. - * - * This method never return. The authentication process is finished - * in the delegateAuthentication method. - * - * @param array &$state Information about the current authentication. - */ - public function authenticate(array &$state) { - $state[self::AUTHID] = $this->authId; - $state[self::SOURCESID] = $this->sources; - - /* Save the $state array, so that we can restore if after a redirect */ - $id = SimpleSAML_Auth_State::saveState($state, self::STAGEID); - - /* Redirect to the select source page. We include the identifier of the - saved state array as a parameter to the login form */ - $url = SimpleSAML\Module::getModuleURL('multiauth/selectsource.php'); - $params = array('AuthState' => $id); - - // Allowes the user to specify the auth souce to be used - if(isset($_GET['source'])) { - $params['source'] = $_GET['source']; - } - - \SimpleSAML\Utils\HTTP::redirectTrustedURL($url, $params); - - /* The previous function never returns, so this code is never - executed */ - assert(false); - } - - /** - * Delegate authentication. - * - * This method is called once the user has choosen one authentication - * source. It saves the selected authentication source in the session - * to be able to logout properly. Then it calls the authenticate method - * on such selected authentication source. - * - * @param string $authId Selected authentication source - * @param array $state Information about the current authentication. - */ - public static function delegateAuthentication($authId, array $state) { - assert(is_string($authId)); - - $as = SimpleSAML_Auth_Source::getById($authId); - $valid_sources = array_map( - function($src) { - return $src['source']; - }, - $state[self::SOURCESID] - ); - if ($as === NULL || !in_array($authId, $valid_sources, true)) { - throw new Exception('Invalid authentication source: ' . $authId); - } - - /* Save the selected authentication source for the logout process. */ - $session = SimpleSAML_Session::getSessionFromRequest(); - $session->setData(self::SESSION_SOURCE, $state[self::AUTHID], $authId, SimpleSAML_Session::DATA_TIMEOUT_SESSION_END); - - try { - $as->authenticate($state); - } catch (SimpleSAML_Error_Exception $e) { - SimpleSAML_Auth_State::throwException($state, $e); - } catch (Exception $e) { - $e = new SimpleSAML_Error_UnserializableException($e); - SimpleSAML_Auth_State::throwException($state, $e); - } - SimpleSAML_Auth_Source::completeAuth($state); - } - - /** - * Log out from this authentication source. - * - * This method retrieves the authentication source used for this - * session and then call the logout method on it. - * - * @param array &$state Information about the current logout operation. - */ - public function logout(array &$state) { - /* Get the source that was used to authenticate */ - $session = SimpleSAML_Session::getSessionFromRequest(); - $authId = $session->getData(self::SESSION_SOURCE, $this->authId); - - $source = SimpleSAML_Auth_Source::getById($authId); - if ($source === NULL) { - throw new Exception('Invalid authentication source during logout: ' . $source); - } - /* Then, do the logout on it */ - $source->logout($state); - } - - /** - * Set the previous authentication source. - * - * This method remembers the authentication source that the user selected - * by storing its name in a cookie. - * - * @param string $source Name of the authentication source the user selected. - */ - public function setPreviousSource($source) { - assert(is_string($source)); - - $cookieName = 'multiauth_source_' . $this->authId; - - $config = SimpleSAML_Configuration::getInstance(); - $params = array( - /* We save the cookies for 90 days. */ - 'lifetime' => (60*60*24*90), - /* The base path for cookies. - This should be the installation directory for SimpleSAMLphp. */ - 'path' => $config->getBasePath(), - 'httponly' => FALSE, + +class sspmod_multiauth_Auth_Source_MultiAuth extends SimpleSAML_Auth_Source { + + /** + * The key of the AuthId field in the state. + */ + const AUTHID = 'sspmod_multiauth_Auth_Source_MultiAuth.AuthId'; + + /** + * The string used to identify our states. + */ + const STAGEID = 'sspmod_multiauth_Auth_Source_MultiAuth.StageId'; + + /** + * The key where the sources is saved in the state. + */ + const SOURCESID = 'sspmod_multiauth_Auth_Source_MultiAuth.SourceId'; + + /** + * The key where the selected source is saved in the session. + */ + const SESSION_SOURCE = 'multiauth:selectedSource'; + + /** + * Array of sources we let the user chooses among. + */ + private $sources; + + /** + * Constructor for this authentication source. + * + * @param array $info Information about this authentication source. + * @param array $config Configuration. + */ + public function __construct($info, $config) { + assert(is_array($info)); + assert(is_array($config)); + + // Call the parent constructor first, as required by the interface + parent::__construct($info, $config); + + if (!array_key_exists('sources', $config)) { + throw new Exception('The required "sources" config option was not found'); + } + + $globalConfiguration = SimpleSAML_Configuration::getInstance(); + $defaultLanguage = $globalConfiguration->getString('language.default', 'en'); + $authsources = SimpleSAML_Configuration::getConfig('authsources.php'); + $this->sources = array(); + foreach($config['sources'] as $source => $info) { + + if (is_int($source)) { // Backwards compatibility + $source = $info; + $info = array(); + } + + if (array_key_exists('text', $info)) { + $text = $info['text']; + } else { + $text = array($defaultLanguage => $source); + } + + if (array_key_exists('css-class', $info)) { + $css_class = $info['css-class']; + } else { + // Use the authtype as the css class + $authconfig = $authsources->getArray($source, NULL); + if (!array_key_exists(0, $authconfig) || !is_string($authconfig[0])) { + $css_class = ""; + } else { + $css_class = str_replace(":", "-", $authconfig[0]); + } + } + + $this->sources[] = array( + 'source' => $source, + 'text' => $text, + 'css_class' => $css_class, + ); + } + } + + /** + * Prompt the user with a list of authentication sources. + * + * This method saves the information about the configured sources, + * and redirects to a page where the user must select one of these + * authentication sources. + * + * This method never return. The authentication process is finished + * in the delegateAuthentication method. + * + * @param array &$state Information about the current authentication. + */ + public function authenticate(&$state) { + assert(is_array($state)); + + $state[self::AUTHID] = $this->authId; + $state[self::SOURCESID] = $this->sources; + + /* Save the $state array, so that we can restore if after a redirect */ + $id = SimpleSAML_Auth_State::saveState($state, self::STAGEID); + + /* Redirect to the select source page. We include the identifier of the + saved state array as a parameter to the login form */ + $url = SimpleSAML\Module::getModuleURL('multiauth/selectsource.php'); + $params = array('AuthState' => $id); + + // Allowes the user to specify the auth souce to be used + if(isset($_GET['source'])) { + $params['source'] = $_GET['source']; + } + + \SimpleSAML\Utils\HTTP::redirectTrustedURL($url, $params); + + /* The previous function never returns, so this code is never + executed */ + assert(false); + } + + /** + * Delegate authentication. + * + * This method is called once the user has choosen one authentication + * source. It saves the selected authentication source in the session + * to be able to logout properly. Then it calls the authenticate method + * on such selected authentication source. + * + * @param string $authId Selected authentication source + * @param array $state Information about the current authentication. + */ + public static function delegateAuthentication($authId, $state) { + assert(is_string($authId)); + assert(is_array($state)); + + $as = SimpleSAML_Auth_Source::getById($authId); + $valid_sources = array_map( + function($src) { + return $src['source']; + }, + $state[self::SOURCESID] ); + if ($as === NULL || !in_array($authId, $valid_sources, true)) { + throw new Exception('Invalid authentication source: ' . $authId); + } + + /* Save the selected authentication source for the logout process. */ + $session = SimpleSAML_Session::getSessionFromRequest(); + $session->setData(self::SESSION_SOURCE, $state[self::AUTHID], $authId, SimpleSAML_Session::DATA_TIMEOUT_SESSION_END); + + try { + $as->authenticate($state); + } catch (SimpleSAML_Error_Exception $e) { + SimpleSAML_Auth_State::throwException($state, $e); + } catch (Exception $e) { + $e = new SimpleSAML_Error_UnserializableException($e); + SimpleSAML_Auth_State::throwException($state, $e); + } + SimpleSAML_Auth_Source::completeAuth($state); + } + + /** + * Log out from this authentication source. + * + * This method retrieves the authentication source used for this + * session and then call the logout method on it. + * + * @param array &$state Information about the current logout operation. + */ + public function logout(&$state) { + assert(is_array($state)); + + /* Get the source that was used to authenticate */ + $session = SimpleSAML_Session::getSessionFromRequest(); + $authId = $session->getData(self::SESSION_SOURCE, $this->authId); + + $source = SimpleSAML_Auth_Source::getById($authId); + if ($source === NULL) { + throw new Exception('Invalid authentication source during logout: ' . $source); + } + /* Then, do the logout on it */ + $source->logout($state); + } + + /** + * Set the previous authentication source. + * + * This method remembers the authentication source that the user selected + * by storing its name in a cookie. + * + * @param string $source Name of the authentication source the user selected. + */ + public function setPreviousSource($source) { + assert(is_string($source)); + + $cookieName = 'multiauth_source_' . $this->authId; + + $config = SimpleSAML_Configuration::getInstance(); + $params = array( + /* We save the cookies for 90 days. */ + 'lifetime' => (60*60*24*90), + /* The base path for cookies. + This should be the installation directory for SimpleSAMLphp. */ + 'path' => $config->getBasePath(), + 'httponly' => FALSE, + ); \SimpleSAML\Utils\HTTP::setCookie($cookieName, $source, $params, FALSE); - } - - /** - * Get the previous authentication source. - * - * This method retrieves the authentication source that the user selected - * last time or NULL if this is the first time or remembering is disabled. - */ - public function getPreviousSource() { - $cookieName = 'multiauth_source_' . $this->authId; - if(array_key_exists($cookieName, $_COOKIE)) { - return $_COOKIE[$cookieName]; - } else { - return NULL; - } - } + } + + /** + * Get the previous authentication source. + * + * This method retrieves the authentication source that the user selected + * last time or NULL if this is the first time or remembering is disabled. + */ + public function getPreviousSource() { + $cookieName = 'multiauth_source_' . $this->authId; + if(array_key_exists($cookieName, $_COOKIE)) { + return $_COOKIE[$cookieName]; + } else { + return NULL; + } + } } diff --git a/modules/negotiate/lib/Auth/Source/Negotiate.php b/modules/negotiate/lib/Auth/Source/Negotiate.php index 573e1c4cdfab1c52ac01a551613b3756b79fbf9b..c1d56500d63e94d16a741d793fbb059a3c64be1e 100644 --- a/modules/negotiate/lib/Auth/Source/Negotiate.php +++ b/modules/negotiate/lib/Auth/Source/Negotiate.php @@ -1,4 +1,6 @@ <?php + + /** * The Negotiate module. Allows for password-less, secure login by Kerberos and Negotiate. * @@ -7,6 +9,7 @@ */ class sspmod_negotiate_Auth_Source_Negotiate extends SimpleSAML_Auth_Source { + // Constants used in the module const STAGEID = 'sspmod_negotiate_Auth_Source_Negotiate.StageId'; @@ -26,6 +29,7 @@ class sspmod_negotiate_Auth_Source_Negotiate extends SimpleSAML_Auth_Source protected $admin_pw = null; protected $attributes = null; + /** * Constructor for this authentication source. * @@ -34,8 +38,11 @@ class sspmod_negotiate_Auth_Source_Negotiate extends SimpleSAML_Auth_Source * * @throws Exception If the KRB5 extension is not installed or active. */ - public function __construct(array $info, array $config) + public function __construct($info, $config) { + assert(is_array($info)); + assert(is_array($config)); + if (!extension_loaded('krb5')) { throw new Exception('KRB5 Extension not installed'); } @@ -61,6 +68,7 @@ class sspmod_negotiate_Auth_Source_Negotiate extends SimpleSAML_Auth_Source $this->attributes = $config->getArray('attributes', null); } + /** * The inner workings of the module. * @@ -72,8 +80,10 @@ class sspmod_negotiate_Auth_Source_Negotiate extends SimpleSAML_Auth_Source * * @param array &$state Information about the current authentication. */ - public function authenticate(array &$state) + public function authenticate(&$state) { + assert(is_array($state)); + // set the default backend to config $state['LogoutState'] = array( 'negotiate:backend' => $this->backend, @@ -175,7 +185,8 @@ class sspmod_negotiate_Auth_Source_Negotiate extends SimpleSAML_Auth_Source assert(false); } - public function spDisabledInMetadata(array $spMetadata) + + public function spDisabledInMetadata($spMetadata) { if (array_key_exists('negotiate:disable', $spMetadata)) { if ($spMetadata['negotiate:disable'] == true) { @@ -224,7 +235,7 @@ class sspmod_negotiate_Auth_Source_Negotiate extends SimpleSAML_Auth_Source * * @param array $params additional parameters to the URL in the URL in the body. */ - protected function sendNegotiate(array $params) + protected function sendNegotiate($params) { $url = htmlspecialchars(SimpleSAML\Module::getModuleURL('negotiate/backend.php', $params)); $json_url = json_encode($url); @@ -254,7 +265,7 @@ EOF; * @throws SimpleSAML_Error_Exception * @throws Exception */ - public static function fallBack(array &$state) + public static function fallBack(&$state) { $authId = $state['LogoutState']['negotiate:backend']; @@ -276,6 +287,7 @@ EOF; self::loginCompleted($state); } + /** * Strips away the realm of the Kerberos identifier, looks up what attributes to fetch from SP metadata and * searches the directory. @@ -303,6 +315,7 @@ EOF; } } + /** * Elevates the LDAP connection to allow restricted lookups if * so configured. Does nothing if not. @@ -324,6 +337,7 @@ EOF; } } + /** * Log out from this authentication source. * @@ -332,8 +346,9 @@ EOF; * * @param array &$state Information about the current logout operation. */ - public function logout(array &$state) + public function logout(&$state) { + assert(is_array($state)); // get the source that was used to authenticate $authId = $state['negotiate:backend']; SimpleSAML\Logger::debug('Negotiate - logout has the following authId: "'.$authId.'"'); diff --git a/modules/preprodwarning/lib/Auth/Process/Warning.php b/modules/preprodwarning/lib/Auth/Process/Warning.php index 271cadd70667af47e6c08f9dad12af681231e6bb..9ece3fa4bd5532eff56e96a36dfb66c6c5ede471 100644 --- a/modules/preprodwarning/lib/Auth/Process/Warning.php +++ b/modules/preprodwarning/lib/Auth/Process/Warning.php @@ -1,28 +1,36 @@ <?php + /** * Give a warning that the user is accessing a test system, not a production system. * * @package SimpleSAMLphp */ -class sspmod_preprodwarning_Auth_Process_Warning extends SimpleSAML_Auth_ProcessingFilter -{ - /** - * Process a authentication response. - * - * This function saves the state, and redirects the user to the page where the user - * can authorize the release of the attributes. - * - * @param array $state The state of the response. - */ - public function process(array &$state) { - if (isset($state['isPassive']) && $state['isPassive'] === true) { - // We have a passive request. Skip the warning - return; - } - - // Save state and redirect. - $id = SimpleSAML_Auth_State::saveState($state, 'warning:request'); - $url = SimpleSAML\Module::getModuleURL('preprodwarning/showwarning.php'); - \SimpleSAML\Utils\HTTP::redirectTrustedURL($url, array('StateId' => $id)); - } +class sspmod_preprodwarning_Auth_Process_Warning extends SimpleSAML_Auth_ProcessingFilter { + + + + /** + * Process a authentication response. + * + * This function saves the state, and redirects the user to the page where the user + * can authorize the release of the attributes. + * + * @param array $state The state of the response. + */ + public function process(&$state) { + assert(is_array($state)); + + if (isset($state['isPassive']) && $state['isPassive'] === TRUE) { + // We have a passive request. Skip the warning + return; + } + + // Save state and redirect. + $id = SimpleSAML_Auth_State::saveState($state, 'warning:request'); + $url = SimpleSAML\Module::getModuleURL('preprodwarning/showwarning.php'); + \SimpleSAML\Utils\HTTP::redirectTrustedURL($url, array('StateId' => $id)); + } + + + } diff --git a/modules/radius/lib/Auth/Source/Radius.php b/modules/radius/lib/Auth/Source/Radius.php index b730f897dbb291f96a8af31ad99301d721862794..649df807b768dcdc4f0abd3e9e8fe6d007bd1cab 100644 --- a/modules/radius/lib/Auth/Source/Radius.php +++ b/modules/radius/lib/Auth/Source/Radius.php @@ -71,8 +71,11 @@ class sspmod_radius_Auth_Source_Radius extends sspmod_core_Auth_UserPassBase * @param array $info Information about this authentication source. * @param array $config Configuration. */ - public function __construct(array $info, array $config) + public function __construct($info, $config) { + assert(is_array($info)); + assert(is_array($config)); + // Call the parent constructor first, as required by the interface parent::__construct($info, $config); diff --git a/modules/saml/lib/Auth/Process/AttributeNameID.php b/modules/saml/lib/Auth/Process/AttributeNameID.php index 6b6e6b58c8d862be99618c4b07fbb52feb7d305b..1bb86a74e9669cc0af8a7ef9297bb5b746cd4a86 100644 --- a/modules/saml/lib/Auth/Process/AttributeNameID.php +++ b/modules/saml/lib/Auth/Process/AttributeNameID.php @@ -1,4 +1,6 @@ <?php + + /** * Authentication processing filter to create a NameID from an attribute. * @@ -6,6 +8,7 @@ */ class sspmod_saml_Auth_Process_AttributeNameID extends sspmod_saml_BaseNameIDGenerator { + /** * The attribute we should use as the NameID. * @@ -13,6 +16,7 @@ class sspmod_saml_Auth_Process_AttributeNameID extends sspmod_saml_BaseNameIDGen */ private $attribute; + /** * Initialize this filter, parse configuration. * @@ -21,9 +25,10 @@ class sspmod_saml_Auth_Process_AttributeNameID extends sspmod_saml_BaseNameIDGen * * @throws SimpleSAML_Error_Exception If the required options 'Format' or 'attribute' are missing. */ - public function __construct(array $config, $reserved) + public function __construct($config, $reserved) { parent::__construct($config, $reserved); + assert(is_array($config)); if (!isset($config['Format'])) { throw new SimpleSAML_Error_Exception("AttributeNameID: Missing required option 'Format'."); @@ -36,6 +41,7 @@ class sspmod_saml_Auth_Process_AttributeNameID extends sspmod_saml_BaseNameIDGen $this->attribute = (string) $config['attribute']; } + /** * Get the NameID value. * @@ -44,6 +50,7 @@ class sspmod_saml_Auth_Process_AttributeNameID extends sspmod_saml_BaseNameIDGen */ protected function getValue(array &$state) { + if (!isset($state['Attributes'][$this->attribute]) || count($state['Attributes'][$this->attribute]) === 0) { SimpleSAML\Logger::warning( 'Missing attribute '.var_export($this->attribute, true). @@ -71,4 +78,5 @@ class sspmod_saml_Auth_Process_AttributeNameID extends sspmod_saml_BaseNameIDGen return $value; } + } diff --git a/modules/saml/lib/Auth/Process/AuthnContextClassRef.php b/modules/saml/lib/Auth/Process/AuthnContextClassRef.php index 5e7436016d4df937962bc681e6cf7ea670be29f3..d1ebbf0efe3dc582a02bf92cd5d9e37b27504dbd 100644 --- a/modules/saml/lib/Auth/Process/AuthnContextClassRef.php +++ b/modules/saml/lib/Auth/Process/AuthnContextClassRef.php @@ -1,4 +1,6 @@ <?php + + /** * Filter for setting the AuthnContextClassRef in the response. * @@ -14,6 +16,7 @@ class sspmod_saml_Auth_Process_AuthnContextClassRef extends SimpleSAML_Auth_Proc */ private $authnContextClassRef; + /** * Initialize this filter. * @@ -22,9 +25,10 @@ class sspmod_saml_Auth_Process_AuthnContextClassRef extends SimpleSAML_Auth_Proc * * @throws SimpleSAML_Error_Exception if the mandatory 'AuthnContextClassRef' option is missing. */ - public function __construct(array $config, $reserved) + public function __construct($config, $reserved) { parent::__construct($config, $reserved); + assert(is_array($config)); if (!isset($config['AuthnContextClassRef'])) { throw new SimpleSAML_Error_Exception('Missing AuthnContextClassRef option in processing filter.'); @@ -33,13 +37,16 @@ class sspmod_saml_Auth_Process_AuthnContextClassRef extends SimpleSAML_Auth_Proc $this->authnContextClassRef = (string) $config['AuthnContextClassRef']; } + /** * Set the AuthnContextClassRef in the SAML 2 response. * * @param array &$state The state array for this request. */ - public function process(array &$state) + public function process(&$state) { + assert(is_array($state)); + $state['saml:AuthnContextClassRef'] = $this->authnContextClassRef; } } diff --git a/modules/saml/lib/Auth/Process/ExpectedAuthnContextClassRef.php b/modules/saml/lib/Auth/Process/ExpectedAuthnContextClassRef.php index 3d41d13715d68054968ca5514ac3e4e918013d69..b8e77dc709c354a7d9ed0b4a0583bed1604fa80a 100644 --- a/modules/saml/lib/Auth/Process/ExpectedAuthnContextClassRef.php +++ b/modules/saml/lib/Auth/Process/ExpectedAuthnContextClassRef.php @@ -1,4 +1,6 @@ <?php + + /** * Attribute filter to validate AuthnContextClassRef values. * @@ -16,18 +18,21 @@ */ class sspmod_saml_Auth_Process_ExpectedAuthnContextClassRef extends SimpleSAML_Auth_ProcessingFilter { + /** * Array of accepted AuthnContextClassRef * @var array */ private $accepted; + /** * AuthnContextClassRef of the assertion * @var string */ private $AuthnContextClassRef; + /** * Initialize this filter, parse configuration * @@ -36,10 +41,11 @@ class sspmod_saml_Auth_Process_ExpectedAuthnContextClassRef extends SimpleSAML_A * * @throws SimpleSAML_Error_Exception if the mandatory 'accepted' configuration option is missing. */ - public function __construct(array $config, $reserved) + public function __construct($config, $reserved) { parent::__construct($config, $reserved); + assert(is_array($config)); if (empty($config['accepted'])) { SimpleSAML\Logger::error( 'ExpectedAuthnContextClassRef: Configuration error. There is no accepted AuthnContextClassRef.' @@ -51,12 +57,14 @@ class sspmod_saml_Auth_Process_ExpectedAuthnContextClassRef extends SimpleSAML_A $this->accepted = $config['accepted']; } + /** * * @param array &$request The current request */ - public function process(array &$request) + public function process(&$request) { + assert(is_array($request)); assert(array_key_exists('Attributes', $request)); $this->AuthnContextClassRef = $request['saml:sp:State']['saml:sp:AuthnContext']; @@ -66,6 +74,7 @@ class sspmod_saml_Auth_Process_ExpectedAuthnContextClassRef extends SimpleSAML_A } } + /** * When the process logic determines that the user is not * authorized for this service, then forward the user to @@ -78,7 +87,7 @@ class sspmod_saml_Auth_Process_ExpectedAuthnContextClassRef extends SimpleSAML_A * * @param array $request */ - protected function unauthorized(array &$request) + protected function unauthorized(&$request) { SimpleSAML\Logger::error( 'ExpectedAuthnContextClassRef: Invalid authentication context: '.$this->AuthnContextClassRef. diff --git a/modules/saml/lib/Auth/Process/FilterScopes.php b/modules/saml/lib/Auth/Process/FilterScopes.php index d5bec1ca41ea2d1f74441a134358c69e0ead86d5..3f497e1e96cdc9d7ab404ba636271a89d9df23e7 100644 --- a/modules/saml/lib/Auth/Process/FilterScopes.php +++ b/modules/saml/lib/Auth/Process/FilterScopes.php @@ -7,10 +7,13 @@ use SimpleSAML\Logger; /** * Filter to remove attribute values which are not properly scoped. * + * @author Adam Lantos, NIIF / Hungarnet + * @author Jaime Pérez Crespo, UNINETT AS <jaime.perez@uninett.no> * @package SimpleSAMLphp */ class FilterScopes extends \SimpleSAML_Auth_ProcessingFilter { + /** * Stores any pre-configured scoped attributes which come from the filter configuration. */ @@ -19,27 +22,30 @@ class FilterScopes extends \SimpleSAML_Auth_ProcessingFilter 'eduPersonPrincipalName' ); + /** * Constructor for the processing filter. * * @param array &$config Configuration for this filter. * @param mixed $reserved For future use. */ - public function __construct(array &$config, $reserved) + public function __construct(&$config, $reserved) { parent::__construct($config, $reserved); + assert(is_array($config)); if (array_key_exists('attributes', $config) && !empty($config['attributes'])) { $this->scopedAttributes = $config['attributes']; } } + /** * This method applies the filter, removing any values * * @param array &$request the current request */ - public function process(array &$request) + public function process(&$request) { $src = $request['Source']; if (!count($this->scopedAttributes)) { diff --git a/modules/saml/lib/Auth/Process/NameIDAttribute.php b/modules/saml/lib/Auth/Process/NameIDAttribute.php index 35f0d3be3bd19be092971b250ec7b05513935894..c3c6bf4706130939ee5c789dae26b037434d097e 100644 --- a/modules/saml/lib/Auth/Process/NameIDAttribute.php +++ b/modules/saml/lib/Auth/Process/NameIDAttribute.php @@ -1,4 +1,6 @@ <?php + + /** * Authentication processing filter to create an attribute from a NameID. * @@ -6,6 +8,7 @@ */ class sspmod_saml_Auth_Process_NameIDAttribute extends SimpleSAML_Auth_ProcessingFilter { + /** * The attribute we should save the NameID in. * @@ -13,6 +16,7 @@ class sspmod_saml_Auth_Process_NameIDAttribute extends SimpleSAML_Auth_Processin */ private $attribute; + /** * The format of the NameID in the attribute. * @@ -20,15 +24,17 @@ class sspmod_saml_Auth_Process_NameIDAttribute extends SimpleSAML_Auth_Processin */ private $format; + /** * Initialize this filter, parse configuration. * * @param array $config Configuration information about this filter. * @param mixed $reserved For future use. */ - public function __construct(array $config, $reserved) + public function __construct($config, $reserved) { parent::__construct($config, $reserved); + assert(is_array($config)); if (isset($config['attribute'])) { $this->attribute = (string) $config['attribute']; @@ -45,6 +51,7 @@ class sspmod_saml_Auth_Process_NameIDAttribute extends SimpleSAML_Auth_Processin $this->format = self::parseFormat($format); } + /** * Parse a NameID format string into an array. * @@ -90,13 +97,15 @@ class sspmod_saml_Auth_Process_NameIDAttribute extends SimpleSAML_Auth_Processin return $ret; } + /** * Convert NameID to attribute. * * @param array &$state The request state. */ - public function process(array &$state) + public function process(&$state) { + assert(is_array($state)); assert(isset($state['Source']['entityid'])); assert(isset($state['Destination']['entityid'])); diff --git a/modules/saml/lib/Auth/Process/PersistentNameID.php b/modules/saml/lib/Auth/Process/PersistentNameID.php index bb825077ecb7b001fe11298920316729d49f26b4..4d6d0bc2260ac4e8e72a458066cb888f4f9f6539 100644 --- a/modules/saml/lib/Auth/Process/PersistentNameID.php +++ b/modules/saml/lib/Auth/Process/PersistentNameID.php @@ -1,4 +1,6 @@ <?php + + /** * Authentication processing filter to generate a persistent NameID. * @@ -6,6 +8,7 @@ */ class sspmod_saml_Auth_Process_PersistentNameID extends sspmod_saml_BaseNameIDGenerator { + /** * Which attribute contains the unique identifier of the user. * @@ -13,6 +16,7 @@ class sspmod_saml_Auth_Process_PersistentNameID extends sspmod_saml_BaseNameIDGe */ private $attribute; + /** * Initialize this filter, parse configuration. * @@ -21,9 +25,10 @@ class sspmod_saml_Auth_Process_PersistentNameID extends sspmod_saml_BaseNameIDGe * * @throws SimpleSAML_Error_Exception If the required option 'attribute' is missing. */ - public function __construct(array $config, $reserved) + public function __construct($config, $reserved) { parent::__construct($config, $reserved); + assert(is_array($config)); $this->format = \SAML2\Constants::NAMEID_PERSISTENT; @@ -33,6 +38,7 @@ class sspmod_saml_Auth_Process_PersistentNameID extends sspmod_saml_BaseNameIDGe $this->attribute = $config['attribute']; } + /** * Get the NameID value. * @@ -41,6 +47,7 @@ class sspmod_saml_Auth_Process_PersistentNameID extends sspmod_saml_BaseNameIDGe */ protected function getValue(array &$state) { + if (!isset($state['Destination']['entityid'])) { SimpleSAML\Logger::warning('No SP entity ID - not generating persistent NameID.'); return null; diff --git a/modules/saml/lib/Auth/Process/PersistentNameID2TargetedID.php b/modules/saml/lib/Auth/Process/PersistentNameID2TargetedID.php index 4b315d7b7391d7f8ea743c744e39e8f6375fc1bc..604c2214713adf5edee4694b93289b6e845bf13d 100644 --- a/modules/saml/lib/Auth/Process/PersistentNameID2TargetedID.php +++ b/modules/saml/lib/Auth/Process/PersistentNameID2TargetedID.php @@ -1,5 +1,6 @@ <?php + /** * Authentication processing filter to create the eduPersonTargetedID attribute from the persistent NameID. * @@ -7,6 +8,7 @@ */ class sspmod_saml_Auth_Process_PersistentNameID2TargetedID extends SimpleSAML_Auth_ProcessingFilter { + /** * The attribute we should save the NameID in. * @@ -14,6 +16,7 @@ class sspmod_saml_Auth_Process_PersistentNameID2TargetedID extends SimpleSAML_Au */ private $attribute; + /** * Whether we should insert it as an saml:NameID element. * @@ -21,15 +24,17 @@ class sspmod_saml_Auth_Process_PersistentNameID2TargetedID extends SimpleSAML_Au */ private $nameId; + /** * Initialize this filter, parse configuration. * * @param array $config Configuration information about this filter. * @param mixed $reserved For future use. */ - public function __construct(array $config, $reserved) + public function __construct($config, $reserved) { parent::__construct($config, $reserved); + assert(is_array($config)); if (isset($config['attribute'])) { $this->attribute = (string) $config['attribute']; @@ -44,13 +49,16 @@ class sspmod_saml_Auth_Process_PersistentNameID2TargetedID extends SimpleSAML_Au } } + /** * Store a NameID to attribute. * * @param array &$state The request state. */ - public function process(array &$state) + public function process(&$state) { + assert(is_array($state)); + if (!isset($state['saml:NameID'][\SAML2\Constants::NAMEID_PERSISTENT])) { SimpleSAML\Logger::warning( 'Unable to generate eduPersonTargetedID because no persistent NameID was available.' diff --git a/modules/saml/lib/Auth/Process/SQLPersistentNameID.php b/modules/saml/lib/Auth/Process/SQLPersistentNameID.php index b2011eeb2ca93f75b25e9cc52620e04f64d6611d..00891824a7ce7cafb972820a222a3aa96cf50d1d 100644 --- a/modules/saml/lib/Auth/Process/SQLPersistentNameID.php +++ b/modules/saml/lib/Auth/Process/SQLPersistentNameID.php @@ -1,4 +1,6 @@ <?php + + /** * Authentication processing filter to generate a persistent NameID. * @@ -6,6 +8,7 @@ */ class sspmod_saml_Auth_Process_SQLPersistentNameID extends sspmod_saml_BaseNameIDGenerator { + /** * Which attribute contains the unique identifier of the user. * @@ -34,6 +37,7 @@ class sspmod_saml_Auth_Process_SQLPersistentNameID extends sspmod_saml_BaseNameI */ private $alwaysCreate = false; + /** * Initialize this filter, parse configuration. * @@ -42,9 +46,10 @@ class sspmod_saml_Auth_Process_SQLPersistentNameID extends sspmod_saml_BaseNameI * * @throws SimpleSAML_Error_Exception If the 'attribute' option is not specified. */ - public function __construct(array $config, $reserved) + public function __construct($config, $reserved) { parent::__construct($config, $reserved); + assert(is_array($config)); $this->format = \SAML2\Constants::NAMEID_PERSISTENT; @@ -66,6 +71,7 @@ class sspmod_saml_Auth_Process_SQLPersistentNameID extends sspmod_saml_BaseNameI } } + /** * Get the NameID value. * @@ -76,6 +82,7 @@ class sspmod_saml_Auth_Process_SQLPersistentNameID extends sspmod_saml_BaseNameI */ protected function getValue(array &$state) { + if (!isset($state['saml:NameIDFormat']) && !$this->allowUnspecified) { SimpleSAML\Logger::debug( 'SQLPersistentNameID: Request did not specify persistent NameID format, '. diff --git a/modules/saml/lib/Auth/Process/TransientNameID.php b/modules/saml/lib/Auth/Process/TransientNameID.php index 672eadba8764b1b3a90df0bb51457f0f695e30e1..c43c19a00a6501c3a91f4abb9d2ec31800640797 100644 --- a/modules/saml/lib/Auth/Process/TransientNameID.php +++ b/modules/saml/lib/Auth/Process/TransientNameID.php @@ -1,4 +1,6 @@ <?php + + /** * Authentication processing filter to generate a transient NameID. * @@ -6,19 +8,22 @@ */ class sspmod_saml_Auth_Process_TransientNameID extends sspmod_saml_BaseNameIDGenerator { + /** * Initialize this filter, parse configuration * * @param array $config Configuration information about this filter. * @param mixed $reserved For future use. */ - public function __construct(array $config, $reserved) + public function __construct($config, $reserved) { parent::__construct($config, $reserved); + assert(is_array($config)); $this->format = \SAML2\Constants::NAMEID_TRANSIENT; } + /** * Get the NameID value. * diff --git a/modules/saml/lib/Auth/Source/SP.php b/modules/saml/lib/Auth/Source/SP.php index b63ed1c4eee526d3df67ca99817fa44f50c7ee01..6d325025483f3bd798484467ca7218f4e4e71cd4 100644 --- a/modules/saml/lib/Auth/Source/SP.php +++ b/modules/saml/lib/Auth/Source/SP.php @@ -36,8 +36,11 @@ class sspmod_saml_Auth_Source_SP extends SimpleSAML_Auth_Source * @param array $info Information about this authentication source. * @param array $config Configuration. */ - public function __construct(array $info, array $config) + public function __construct($info, $config) { + assert(is_array($info)); + assert(is_array($config)); + // Call the parent constructor first, as required by the interface parent::__construct($info, $config); @@ -375,8 +378,10 @@ class sspmod_saml_Auth_Source_SP extends SimpleSAML_Auth_Source * * @param array &$state Information about the current authentication. */ - public function authenticate(array &$state) + public function authenticate(&$state) { + assert(is_array($state)); + /* We are going to need the authId in order to retrieve this authentication source later. */ $state['saml:sp:AuthId'] = $this->authId; @@ -433,6 +438,8 @@ class sspmod_saml_Auth_Source_SP extends SimpleSAML_Auth_Source */ public function reauthenticate(array &$state) { + assert(is_array($state)); + $session = SimpleSAML_Session::getSessionFromRequest(); $data = $session->getAuthState($this->authId); foreach ($data as $k => $v) { @@ -604,8 +611,9 @@ class sspmod_saml_Auth_Source_SP extends SimpleSAML_Auth_Source * * @param array $state The logout state. */ - public function startSLO2(array &$state) + public function startSLO2(&$state) { + assert(is_array($state)); assert(array_key_exists('saml:logout:IdP', $state)); assert(array_key_exists('saml:logout:NameID', $state)); assert(array_key_exists('saml:logout:SessionIndex', $state)); @@ -651,8 +659,9 @@ class sspmod_saml_Auth_Source_SP extends SimpleSAML_Auth_Source * * @param array $state The logout state. */ - public function logout(array &$state) + public function logout(&$state) { + assert(is_array($state)); assert(array_key_exists('saml:logout:Type', $state)); $logoutType = $state['saml:logout:Type']; diff --git a/modules/smartattributes/lib/Auth/Process/SmartID.php b/modules/smartattributes/lib/Auth/Process/SmartID.php index 278ea921d2f0adb18dc3ea6fe18d7477438bb86f..99771048218f5bad716c38c281388ac9ca8318c7 100644 --- a/modules/smartattributes/lib/Auth/Process/SmartID.php +++ b/modules/smartattributes/lib/Auth/Process/SmartID.php @@ -1,111 +1,116 @@ <?php -class sspmod_smartattributes_Auth_Process_SmartID extends SimpleSAML_Auth_ProcessingFilter -{ - /** - * Which attributes to use as identifiers? - * - * IMPORTANT: If you use the (default) attributemaps (twitter2name, facebook2name, - * etc., be sure to comment out the entries that map xxx_targetedID to - * eduPersonTargetedID, or there will be no way to see its origin any more. - */ - private $_candidates = array( - 'eduPersonTargetedID', - 'eduPersonPrincipalName', - 'openid', - 'facebook_targetedID', - 'twitter_targetedID', - 'windowslive_targetedID', - 'linkedin_targetedID', - ); - - /** - * The name of the generated ID attribute. - */ - private $_id_attribute = 'smart_id'; - - /** - * Whether to append the AuthenticatingAuthority, separated by '!' - * This only works when SSP is used as a gateway. - */ - private $_add_authority = true; - - /** - * Whether to prepend the CandidateID, separated by ':' - */ - private $_add_candidate = true; - - /** - * Attributes which should be added/appended. - * - * Associative array of arrays. - */ - private $attributes = array(); - - public function __construct(array $config, $reserved) { - parent::__construct($config, $reserved); - - if (array_key_exists('candidates', $config)) { - $this->_candidates = $config['candidates']; - if (!is_array($this->_candidates)) { - throw new Exception('SmartID authproc configuration error: \'candidates\' should be an array.'); - } - } - - if (array_key_exists('id_attribute', $config)) { - $this->_id_attribute = $config['id_attribute']; - if (!is_string($this->_id_attribute)) { - throw new Exception('SmartID authproc configuration error: \'id_attribute\' should be a string.'); - } - } - - if (array_key_exists('add_authority', $config)) { - $this->_add_authority = $config['add_authority']; - if (!is_bool($this->_add_authority)) { - throw new Exception('SmartID authproc configuration error: \'add_authority\' should be a boolean.'); - } - } - - if (array_key_exists('add_candidate', $config)) { - $this->_add_candidate = $config['add_candidate']; - if (!is_bool($this->_add_candidate)) { - throw new Exception('SmartID authproc configuration error: \'add_candidate\' should be a boolean.'); - } - } - - } - - private function addID(array $attributes, array $request) { - foreach ($this->_candidates as $idCandidate) { - if (isset($attributes[$idCandidate][0])) { - if(($this->_add_authority) && (isset($request['saml:AuthenticatingAuthority'][0]))) { - return ($this->_add_candidate ? $idCandidate.':' : '').$attributes[$idCandidate][0] . '!' . $request['saml:AuthenticatingAuthority'][0]; - } else { - return ($this->_add_candidate ? $idCandidate.':' : '').$attributes[$idCandidate][0]; - } - } - } - /* - * At this stage no usable id_candidate has been detected. - */ - throw new SimpleSAML_Error_Exception('This service needs at least one of the following - attributes to identity users: '.implode(', ', $this->_candidates).'. Unfortunately not - one of them was detected. Please ask your institution administrator to release one of - them, or try using another identity provider.'); - } - - /** - * Apply filter to add or replace attributes. - * - * Add or replace existing attributes with the configured values. - * - * @param array &$request The current request - */ - public function process(array &$request) { - assert(array_key_exists('Attributes', $request)); - - $ID = $this->addID($request['Attributes'], $request); - - if(isset($ID)) $request['Attributes'][$this->_id_attribute] = array($ID); - } +class sspmod_smartattributes_Auth_Process_SmartID extends SimpleSAML_Auth_ProcessingFilter { + + /** + * Which attributes to use as identifiers? + * + * IMPORTANT: If you use the (default) attributemaps (twitter2name, facebook2name, + * etc., be sure to comment out the entries that map xxx_targetedID to + * eduPersonTargetedID, or there will be no way to see its origin any more. + */ + private $_candidates = array( + 'eduPersonTargetedID', + 'eduPersonPrincipalName', + 'openid', + 'facebook_targetedID', + 'twitter_targetedID', + 'windowslive_targetedID', + 'linkedin_targetedID', + ); + + /** + * The name of the generated ID attribute. + */ + private $_id_attribute = 'smart_id'; + + /** + * Whether to append the AuthenticatingAuthority, separated by '!' + * This only works when SSP is used as a gateway. + */ + private $_add_authority = true; + + /** + * Whether to prepend the CandidateID, separated by ':' + */ + private $_add_candidate = true; + + /** + * Attributes which should be added/appended. + * + * Associative array of arrays. + */ + private $attributes = array(); + + + public function __construct($config, $reserved) { + parent::__construct($config, $reserved); + + assert(is_array($config)); + + if (array_key_exists('candidates', $config)) { + $this->_candidates = $config['candidates']; + if (!is_array($this->_candidates)) { + throw new Exception('SmartID authproc configuration error: \'candidates\' should be an array.'); + } + } + + if (array_key_exists('id_attribute', $config)) { + $this->_id_attribute = $config['id_attribute']; + if (!is_string($this->_id_attribute)) { + throw new Exception('SmartID authproc configuration error: \'id_attribute\' should be a string.'); + } + } + + if (array_key_exists('add_authority', $config)) { + $this->_add_authority = $config['add_authority']; + if (!is_bool($this->_add_authority)) { + throw new Exception('SmartID authproc configuration error: \'add_authority\' should be a boolean.'); + } + } + + if (array_key_exists('add_candidate', $config)) { + $this->_add_candidate = $config['add_candidate']; + if (!is_bool($this->_add_candidate)) { + throw new Exception('SmartID authproc configuration error: \'add_candidate\' should be a boolean.'); + } + } + + } + + private function addID($attributes, $request) { + foreach ($this->_candidates as $idCandidate) { + if (isset($attributes[$idCandidate][0])) { + if(($this->_add_authority) && (isset($request['saml:AuthenticatingAuthority'][0]))) { + return ($this->_add_candidate ? $idCandidate.':' : '').$attributes[$idCandidate][0] . '!' . $request['saml:AuthenticatingAuthority'][0]; + } else { + return ($this->_add_candidate ? $idCandidate.':' : '').$attributes[$idCandidate][0]; + } + } + } + /* + * At this stage no usable id_candidate has been detected. + */ + throw new SimpleSAML_Error_Exception('This service needs at least one of the following + attributes to identity users: '.implode(', ', $this->_candidates).'. Unfortunately not + one of them was detected. Please ask your institution administrator to release one of + them, or try using another identity provider.'); + } + + + /** + * Apply filter to add or replace attributes. + * + * Add or replace existing attributes with the configured values. + * + * @param array &$request The current request + */ + public function process(&$request) { + assert(is_array($request)); + assert(array_key_exists('Attributes', $request)); + + $ID = $this->addID($request['Attributes'], $request); + + if(isset($ID)) $request['Attributes'][$this->_id_attribute] = array($ID); + } } diff --git a/modules/smartattributes/lib/Auth/Process/SmartName.php b/modules/smartattributes/lib/Auth/Process/SmartName.php index bb0f41cfb3a235402ee016cfd1183e798a7be2e3..44323f9196a22ab4ae2597eb76a117e95c493162 100644 --- a/modules/smartattributes/lib/Auth/Process/SmartName.php +++ b/modules/smartattributes/lib/Auth/Process/SmartName.php @@ -1,80 +1,76 @@ <?php + /** * Filter to set name in a smart way, based on available name attributes. * + * @author Andreas Åkre Solberg, UNINETT AS. * @package SimpleSAMLphp */ -class sspmod_smartattributes_Auth_Process_SmartName extends SimpleSAML_Auth_ProcessingFilter -{ - /** - * Attributes which should be added/appended. - * - * Associative array of arrays. - */ - private $attributes = []; +class sspmod_smartattributes_Auth_Process_SmartName extends SimpleSAML_Auth_ProcessingFilter { + + /** + * Attributes which should be added/appended. + * + * Assiciative array of arrays. + */ + private $attributes = array(); + - private function getFullName(array $attributes) { - if (isset($attributes['displayName'])) { - return $attributes['displayName'][0]; - } - if (isset($attributes['cn'])) { - if (count(explode(' ', $attributes['cn'][0])) > 1) { - return $attributes['cn'][0]; - } - } - - if (isset($attributes['sn']) && isset($attributes['givenName'])) { - return $attributes['givenName'][0] . ' ' . $attributes['sn'][0]; - } + private function getFullName($attributes) { + if (isset($attributes['displayName'])) + return $attributes['displayName'][0]; + + if (isset($attributes['cn'])) { + if (count(explode(' ', $attributes['cn'][0])) > 1) + return $attributes['cn'][0]; + } + + if (isset($attributes['sn']) && isset($attributes['givenName'])) + return $attributes['givenName'][0] . ' ' . $attributes['sn'][0]; - if (isset($attributes['cn'])) { - return $attributes['cn'][0]; - } + if (isset($attributes['cn'])) + return $attributes['cn'][0]; - if (isset($attributes['sn'])) { - return $attributes['sn'][0]; - } + if (isset($attributes['sn'])) + return $attributes['sn'][0]; - if (isset($attributes['givenName'])) { - return $attributes['givenName'][0]; - } - - if (isset($attributes['eduPersonPrincipalName'])) { - $localname = $this->getLocalUser($attributes['eduPersonPrincipalName'][0]); - if (isset($localname)) return $localname; - } - - return null; - } - - private function getLocalUser($userid) - { - if (strpos($userid, '@') === false) return null; + if (isset($attributes['givenName'])) + return $attributes['givenName'][0]; + + if (isset($attributes['eduPersonPrincipalName'])) { + $localname = $this->getLocalUser($attributes['eduPersonPrincipalName'][0]); + if (isset($localname)) return $localname; + } + + return NULL; + } + + private function getLocalUser($userid) { + if (strpos($userid, '@') === FALSE) return NULL; + $decomposed = explode('@', $userid); + if(count($decomposed) === 2) { + return $decomposed[0]; + } + return NULL; + } - $decomposed = explode('@', $userid); - if(count($decomposed) === 2) { - return $decomposed[0]; - } - return null; - } + /** + * Apply filter to add or replace attributes. + * + * Add or replace existing attributes with the configured values. + * + * @param array &$request The current request + */ + public function process(&$request) { + assert(is_array($request)); + assert(array_key_exists('Attributes', $request)); - /** - * Apply filter to add or replace attributes. - * - * Add or replace existing attributes with the configured values. - * - * @param array &$request The current request - */ - public function process(array &$request) - { - assert(array_key_exists('Attributes', $request)); + $attributes =& $request['Attributes']; + + $fullname = $this->getFullName($attributes); + + if(isset($fullname)) $request['Attributes']['smartname-fullname'] = array($fullname); + + } - $attributes =& $request['Attributes']; - - $fullname = $this->getFullName($attributes); - - if(isset($fullname)) { - $request['Attributes']['smartname-fullname'] = array($fullname); - } - } } diff --git a/modules/sqlauth/lib/Auth/Source/SQL.php b/modules/sqlauth/lib/Auth/Source/SQL.php index 39dfe244f24eed5210406df46d850b2a5831fad5..67995ab63bdcc5ebe1adf0a8ed6c2440753e7355 100644 --- a/modules/sqlauth/lib/Auth/Source/SQL.php +++ b/modules/sqlauth/lib/Auth/Source/SQL.php @@ -1,4 +1,5 @@ <?php + /** * Simple SQL authentication source * @@ -43,8 +44,11 @@ class sspmod_sqlauth_Auth_Source_SQL extends sspmod_core_Auth_UserPassBase * @param array $info Information about this authentication source. * @param array $config Configuration. */ - public function __construct(array $info, array $config) + public function __construct($info, $config) { + assert(is_array($info)); + assert(is_array($config)); + // Call the parent constructor first, as required by the interface parent::__construct($info, $config); @@ -72,6 +76,7 @@ class sspmod_sqlauth_Auth_Source_SQL extends sspmod_core_Auth_UserPassBase } } + /** * Create a database connection. * @@ -106,6 +111,7 @@ class sspmod_sqlauth_Auth_Source_SQL extends sspmod_core_Auth_UserPassBase return $db; } + /** * Attempt to log in using the given username and password. *