1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
|
<?php
declare(strict_types=1);
namespace SimpleSAML\Auth;
use SimpleSAML\Configuration;
use SimpleSAML\Error;
use SimpleSAML\Logger;
use SimpleSAML\Session;
use SimpleSAML\Utils;
/**
* This is a helper class for saving and loading state information.
*
* The state must be an associative array. This class will add additional keys to this
* array. These keys will always start with '\SimpleSAML\Auth\State.'.
*
* It is also possible to add a restart URL to the state. If state information is lost, for
* example because it timed out, or the user loaded a bookmarked page, the loadState function
* will redirect to this URL. To use this, set $state[\SimpleSAML\Auth\State::RESTART] to this
* URL.
*
* Both the saveState and the loadState function takes in a $stage parameter. This parameter is
* a security feature, and is used to prevent the user from taking a state saved one place and
* using it as input a different place.
*
* The $stage parameter must be a unique string. To maintain uniqueness, it must be on the form
* "<classname>.<identifier>" or "<module>:<identifier>".
*
* There is also support for passing exceptions through the state.
* By defining an exception handler when creating the state array, users of the state
* array can call throwException with the state and the exception. This exception will
* be passed to the handler defined by the EXCEPTION_HANDLER_URL or EXCEPTION_HANDLER_FUNC
* elements of the state array. Note that internally this uses the request parameter name
* defined in EXCEPTION_PARAM, which, for technical reasons, cannot contain a ".".
*
* @author Olav Morken, UNINETT AS.
* @package SimpleSAMLphp
*/
class State
{
/**
* The index in the state array which contains the identifier.
*/
public const ID = '\SimpleSAML\Auth\State.id';
/**
* The index in the cloned state array which contains the identifier of the
* original state.
*/
public const CLONE_ORIGINAL_ID = '\SimpleSAML\Auth\State.cloneOriginalId';
/**
* The index in the state array which contains the current stage.
*/
public const STAGE = '\SimpleSAML\Auth\State.stage';
/**
* The index in the state array which contains the restart URL.
*/
public const RESTART = '\SimpleSAML\Auth\State.restartURL';
/**
* The index in the state array which contains the exception handler URL.
*/
public const EXCEPTION_HANDLER_URL = '\SimpleSAML\Auth\State.exceptionURL';
/**
* The index in the state array which contains the exception handler function.
*/
public const EXCEPTION_HANDLER_FUNC = '\SimpleSAML\Auth\State.exceptionFunc';
/**
* The index in the state array which contains the exception data.
*/
public const EXCEPTION_DATA = '\SimpleSAML\Auth\State.exceptionData';
/**
* The stage of a state with an exception.
*/
public const EXCEPTION_STAGE = '\SimpleSAML\Auth\State.exceptionStage';
/**
* The URL parameter which contains the exception state id.
* Note that this does not contain a "." since it's used in the
* _REQUEST superglobal that does not allow dots.
*/
public const EXCEPTION_PARAM = '\SimpleSAML\Auth\State_exceptionId';
/**
* State timeout.
*/
private static $stateTimeout = null;
/**
* Get the persistent authentication state from the state array.
*
* @param array $state The state array to analyze.
*
* @return array The persistent authentication state.
*/
public static function getPersistentAuthData(array $state)
{
// save persistent authentication data
$persistent = [];
if (array_key_exists('PersistentAuthData', $state)) {
foreach ($state['PersistentAuthData'] as $key) {
if (isset($state[$key])) {
$persistent[$key] = $state[$key];
}
}
}
// add those that should always be included
$mandatory = [
'Attributes',
'Expire',
'LogoutState',
'AuthInstant',
'RememberMe',
'saml:sp:NameID'
];
foreach ($mandatory as $key) {
if (isset($state[$key])) {
$persistent[$key] = $state[$key];
}
}
return $persistent;
}
/**
* Retrieve the ID of a state array.
*
* Note that this function will not save the state.
*
* @param array &$state The state array.
* @param bool $rawId Return a raw ID, without a restart URL. Defaults to FALSE.
*
* @return string Identifier which can be used to retrieve the state later.
*/
public static function getStateId(&$state, $rawId = false)
{
assert(is_array($state));
assert(is_bool($rawId));
if (!array_key_exists(self::ID, $state)) {
$state[self::ID] = Utils\Random::generateID();
}
$id = $state[self::ID];
if ($rawId || !array_key_exists(self::RESTART, $state)) {
// Either raw ID or no restart URL. In any case, return the raw ID.
return $id;
}
// We have a restart URL. Return the ID with that URL.
return $id . ':' . $state[self::RESTART];
}
/**
* Retrieve state timeout.
*
* @return integer State timeout.
*/
private static function getStateTimeout(): int
{
if (self::$stateTimeout === null) {
$globalConfig = Configuration::getInstance();
self::$stateTimeout = $globalConfig->getInteger('session.state.timeout', 60 * 60);
}
return self::$stateTimeout;
}
/**
* Save the state.
*
* This function saves the state, and returns an id which can be used to
* retrieve it later. It will also update the $state array with the identifier.
*
* @param array &$state The login request state.
* @param string $stage The current stage in the login process.
* @param bool $rawId Return a raw ID, without a restart URL.
*
* @return string Identifier which can be used to retrieve the state later.
*/
public static function saveState(&$state, $stage, $rawId = false)
{
assert(is_array($state));
assert(is_string($stage));
assert(is_bool($rawId));
$return = self::getStateId($state, $rawId);
$id = $state[self::ID];
// Save stage
$state[self::STAGE] = $stage;
// Save state
$serializedState = serialize($state);
$session = Session::getSessionFromRequest();
$session->setData('\SimpleSAML\Auth\State', $id, $serializedState, self::getStateTimeout());
Logger::debug('Saved state: ' . var_export($return, true));
return $return;
}
/**
* Clone the state.
*
* This function clones and returns the new cloned state.
*
* @param array $state The original request state.
*
* @return array Cloned state data.
*/
public static function cloneState(array $state)
{
$clonedState = $state;
if (array_key_exists(self::ID, $state)) {
$clonedState[self::CLONE_ORIGINAL_ID] = $state[self::ID];
unset($clonedState[self::ID]);
Logger::debug('Cloned state: ' . var_export($state[self::ID], true));
} else {
Logger::debug('Cloned state with undefined id.');
}
return $clonedState;
}
/**
* Retrieve saved state.
*
* This function retrieves saved state information. If the state information has been lost,
* it will attempt to restart the request by calling the restart URL which is embedded in the
* state information. If there is no restart information available, an exception will be thrown.
*
* @param string $id State identifier (with embedded restart information).
* @param string $stage The stage the state should have been saved in.
* @param bool $allowMissing Whether to allow the state to be missing.
*
* @throws \SimpleSAML\Error\NoState If we couldn't find the state and there's no URL defined to redirect to.
* @throws \Exception If the stage of the state is invalid and there's no URL defined to redirect to.
*
* @return array|null State information, or NULL if the state is missing and $allowMissing is true.
*/
public static function loadState($id, $stage, $allowMissing = false)
{
assert(is_string($id));
assert(is_string($stage));
assert(is_bool($allowMissing));
Logger::debug('Loading state: ' . var_export($id, true));
$sid = self::parseStateID($id);
$session = Session::getSessionFromRequest();
$state = $session->getData('\SimpleSAML\Auth\State', $sid['id']);
if ($state === null) {
// Could not find saved data
if ($allowMissing) {
return null;
}
if ($sid['url'] === null) {
throw new Error\NoState();
}
Utils\HTTP::redirectUntrustedURL($sid['url']);
}
$state = unserialize($state);
assert(is_array($state));
assert(array_key_exists(self::ID, $state));
assert(array_key_exists(self::STAGE, $state));
// Verify stage
if ($state[self::STAGE] !== $stage) {
/* This could be a user trying to bypass security, but most likely it is just
* someone using the back-button in the browser. We try to restart the
* request if that is possible. If not, show an error.
*/
$msg = 'Wrong stage in state. Was \'' . $state[self::STAGE] .
'\', should be \'' . $stage . '\'.';
Logger::warning($msg);
if ($sid['url'] === null) {
throw new \Exception($msg);
}
Utils\HTTP::redirectUntrustedURL($sid['url']);
}
return $state;
}
/**
* Delete state.
*
* This function deletes the given state to prevent the user from reusing it later.
*
* @param array &$state The state which should be deleted.
* @return void
*/
public static function deleteState(&$state)
{
assert(is_array($state));
if (!array_key_exists(self::ID, $state)) {
// This state hasn't been saved
return;
}
Logger::debug('Deleting state: ' . var_export($state[self::ID], true));
$session = Session::getSessionFromRequest();
$session->deleteData('\SimpleSAML\Auth\State', $state[self::ID]);
}
/**
* Throw exception to the state exception handler.
*
* @param array $state The state array.
* @param \SimpleSAML\Error\Exception $exception The exception.
*
* @throws \SimpleSAML\Error\Exception If there is no exception handler defined, it will just throw the $exception.
* @return void
*/
public static function throwException($state, Error\Exception $exception)
{
assert(is_array($state));
if (array_key_exists(self::EXCEPTION_HANDLER_URL, $state)) {
// Save the exception
$state[self::EXCEPTION_DATA] = $exception;
$id = self::saveState($state, self::EXCEPTION_STAGE);
// Redirect to the exception handler
Utils\HTTP::redirectTrustedURL(
$state[self::EXCEPTION_HANDLER_URL],
[self::EXCEPTION_PARAM => $id]
);
} elseif (array_key_exists(self::EXCEPTION_HANDLER_FUNC, $state)) {
// Call the exception handler
$func = $state[self::EXCEPTION_HANDLER_FUNC];
assert(is_callable($func));
call_user_func($func, $exception, $state);
assert(false);
} else {
/*
* No exception handler is defined for the current state.
*/
throw $exception;
}
throw new \Exception(); // This should never happen
}
/**
* Retrieve an exception state.
*
* @param string|null $id The exception id. Can be NULL, in which case it will be retrieved from the request.
*
* @return array|null The state array with the exception, or NULL if no exception was thrown.
*/
public static function loadExceptionState($id = null)
{
assert(is_string($id) || $id === null);
if ($id === null) {
if (!array_key_exists(self::EXCEPTION_PARAM, $_REQUEST)) {
// No exception
return null;
}
$id = $_REQUEST[self::EXCEPTION_PARAM];
}
/** @var array $state */
$state = self::loadState($id, self::EXCEPTION_STAGE);
assert(array_key_exists(self::EXCEPTION_DATA, $state));
return $state;
}
/**
* Get the ID and (optionally) a URL embedded in a StateID, in the form 'id:url'.
*
* @param string $stateId The state ID to use.
*
* @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)
{
$tmp = explode(':', $stateId, 2);
$id = $tmp[0];
$url = null;
if (count($tmp) === 2) {
$url = $tmp[1];
}
return ['id' => $id, 'url' => $url];
}
}
|