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 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346
|
<?php
/**
* The Session class holds information about a user session, and everything attached to it.
*
* The session will have a duration and validity, and also cache information about the different
* federation protocols, as Shibboleth and SAML 2.0. On the IdP side the Session class holds
* information about all the currently logged in SPs. This is used when the user initiates a
* Single-Log-Out.
*
* @author Andreas Åkre Solberg, UNINETT AS. <andreas.solberg@uninett.no>
* @package simpleSAMLphp
*/
class SimpleSAML_Session {
/**
* This is a timeout value for setData, which indicates that the data should be deleted
* on logout.
* @deprecated
*/
const DATA_TIMEOUT_LOGOUT = 'logoutTimeout';
/**
* This is a timeout value for setData, which indicates that the data
* should never be deleted, i.e. lasts the whole session lifetime.
*/
const DATA_TIMEOUT_SESSION_END = 'sessionEndTimeout';
/**
* The list of loaded session objects.
*
* This is an associative array indexed with the session id.
*
* @var array
*/
private static $sessions = array();
/**
* This variable holds the instance of the session - Singleton approach.
*/
private static $instance = null;
/**
* The session ID of this session.
*
* @var string|NULL
*/
private $sessionId;
/**
* Transient session flag.
*
* @var boolean|FALSE
*/
private $transient = FALSE;
/**
* The track id is a new random unique identifier that is generated for each session.
* This is used in the debug logs and error messages to easily track more information
* about what went wrong.
*
* @var int
*/
private $trackid = 0;
/**
* @deprecated
*/
private $authority = null;
private $rememberMeExpire = null;
/**
* Marks a session as modified, and therefore needs to be saved before destroying
* this object.
*
* @var bool
*/
private $dirty = false;
/**
* This is an array of objects which will expire automatically after a set time. It is used
* where one needs to store some information - for example a logout request, but doesn't
* want it to be stored forever.
*
* The data store contains three levels of nested associative arrays. The first is the data type, the
* second is the identifier, and the third contains the expire time of the data and the data itself.
*
* @var array
*/
private $dataStore = null;
/**
* The list of IdP-SP associations.
*
* This is an associative array with the IdP id as the key, and the list of
* associations as the value.
*
* @var array
*/
private $associations = array();
/**
* The authentication token.
*
* This token is used to prevent session fixation attacks.
*
* @var string|NULL
*/
private $authToken;
/**
* Authentication data.
*
* This is an array with authentication data for the various authsources.
*
* @var array|NULL Associative array of associative arrays.
*/
private $authData;
/**
* Private constructor that restricts instantiation to getInstance().
*
* @param boolean $transient Whether to create a transient session or not.
*/
private function __construct($transient = FALSE) {
$this->authData = array();
if ($transient) {
$this->trackid = 'XXXXXXXXXX';
$this->transient = TRUE;
return;
}
$sh = SimpleSAML_SessionHandler::getSessionHandler();
$this->sessionId = $sh->newSessionId();
$this->trackid = SimpleSAML_Utilities::stringToHex(SimpleSAML_Utilities::generateRandomBytes(5));
$this->dirty = TRUE;
/* Initialize data for session check function if defined */
$globalConfig = SimpleSAML_Configuration::getInstance();
$checkFunction = $globalConfig->getArray('session.check_function', NULL);
if (isset($checkFunction)) {
assert('is_callable($checkFunction)');
call_user_func($checkFunction, $this, TRUE);
}
}
/**
* Destructor for this class. It will save the session to the session handler
* in case the session has been marked as dirty. Do nothing otherwise.
*/
public function __destruct() {
if(!$this->dirty) {
/* Session hasn't changed - don't bother saving it. */
return;
}
$this->dirty = FALSE;
$sh = SimpleSAML_SessionHandler::getSessionHandler();
try {
$sh->saveSession($this);
} catch (Exception $e) {
if (!($e instanceof SimpleSAML_Error_Exception)) {
$e = new SimpleSAML_Error_UnserializableException($e);
}
SimpleSAML_Logger::error('Unable to save session.');
$e->logError();
}
}
/**
* @deprecated
* @see SimpleSAML_Session::getSessionFromRequest()
*/
public static function getInstance() {
return self::getSessionFromRequest();
}
/**
* Retrieves the current session. Will create a new session if there isn't a session.
*
* @return SimpleSAML_Session The current session.
* @throws Exception When session couldn't be initialized and
* the session fallback is disabled by configuration.
*/
public static function getSessionFromRequest() {
/* Check if we already have initialized the session. */
if (isset(self::$instance)) {
return self::$instance;
}
/* Check if we have stored a session stored with the session
* handler.
*/
try {
self::$instance = self::getSession();
} catch (Exception $e) {
/* For some reason, we were unable to initialize this session. Use a transient session instead. */
self::useTransientSession();
$globalConfig = SimpleSAML_Configuration::getInstance();
if ($globalConfig->getBoolean('session.disable_fallback', FALSE) === TRUE) {
throw $e;
}
if ($e instanceof SimpleSAML_Error_Exception) {
SimpleSAML_Logger::error('Error loading session:');
$e->logError();
} else {
SimpleSAML_Logger::error('Error loading session: ' . $e->getMessage());
}
return self::$instance;
}
if(self::$instance !== NULL) {
return self::$instance;
}
/* Create a new session. */
self::$instance = new SimpleSAML_Session();
return self::$instance;
}
/**
* Use a transient session.
*
* Create a session that should not be saved at the end of the request.
* Subsequent calls to getInstance() will return this transient session.
*/
public static function useTransientSession() {
if (isset(self::$instance)) {
/* We already have a session. Don't bother with a transient session. */
return;
}
self::$instance = new SimpleSAML_Session(TRUE);
}
/**
* Retrieve the session ID of this session.
*
* @return string|NULL The session ID, or NULL if this is a transient session.
*/
public function getSessionId() {
return $this->sessionId;
}
/**
* Retrieve if session is transient.
*
* @return boolean The session transient flag.
*/
public function isTransient() {
return $this->transient;
}
/**
* Get a unique ID that will be permanent for this session.
* Used for debugging and tracing log files related to a session.
*
* @return string The unique ID.
*/
public function getTrackID() {
return $this->trackid;
}
/**
* Who authorized this session. Could be for example 'saml2', 'shib13', 'login', 'login-admin' etc.
*
* @return string Who authorized this session.
* @deprecated
*/
public function getAuthority() {
return $this->authority;
}
/**
* This method retrieves from session a cache of a specific Authentication Request
* The complete request is not stored, instead the values that will be needed later
* are stored in an assoc array.
*
* @param string $protocol saml2 or shib13
* @param string $requestid The request id used as a key to lookup the cache.
* @throws Exception If the method can't find a cached version of the request.
* @return array Returns an assoc array of cached variables associated with the
* authentication request.
* @deprecated
*/
public function getAuthnRequest($protocol, $requestid) {
SimpleSAML_Logger::debug('Library - Session: Get authnrequest from cache ' . $protocol . ' time:' . time() .
' id: '. $requestid );
$type = 'AuthnRequest-' . $protocol;
$authnRequest = $this->getData($type, $requestid);
if($authnRequest === NULL) {
/*
* Could not find requested ID. Throw an error. Could be that it is never set, or that it is deleted
* due to age.
*/
throw new Exception('Could not find cached version of authentication request with ID ' . $requestid .
' (' . $protocol . ')');
}
return $authnRequest;
}
/**
* This method sets a cached assoc array to the authentication request cache storage.
*
* @param string $protocol 'saml2' or 'shib13'
* @param string $requestid The request id used as a key to lookup the cache.
* @param array $cache The assoc array that will be stored.
* @deprecated
*/
public function setAuthnRequest($protocol, $requestid, array $cache) {
SimpleSAML_Logger::debug('Library - Session: Set authnrequest ' . $protocol . ' time:' . time() . ' size:' .
count($cache) . ' id: '. $requestid );
$type = 'AuthnRequest-' . $protocol;
$this->setData($type, $requestid, $cache);
}
/**
* Set the IdP we are authenticated against.
*
* @param string|NULL $idp Our current IdP, or NULL if we aren't authenticated with an IdP.
* @deprecated
*/
public function setIdP($idp) {
assert('is_string($idp) || is_null($idp)');
assert('isset($this->authData[$this->authority])');
SimpleSAML_Logger::debug('Library - Session: Set IdP to : ' . $idp);
$this->dirty = true;
if ($idp !== NULL) {
$this->authData[$this->authority]['saml:sp:IdP'] = $idp;
} else {
unset($this->authData[$this->authority]['saml:sp:IdP']);
}
}
/**
* Retrieve the IdP we are currently authenticated against.
*
* @return string|NULL Our current IdP, or NULL if we aren't authenticated with an IdP.
* @deprecated
*/
public function getIdP() {
if (!isset($this->authData[$this->authority]['saml:sp:IdP'])) {
return NULL;
}
return $this->authData[$this->authority]['saml:sp:IdP'];
}
/**
* Set the SessionIndex we received from our IdP.
*
* @param string|NULL $sessionindex Our SessionIndex.
* @deprecated
*/
public function setSessionIndex($sessionindex) {
assert('is_string($sessionindex) || is_null($sessionindex)');
assert('isset($this->authData[$this->authority])');
SimpleSAML_Logger::debug('Library - Session: Set sessionindex: ' . $sessionindex);
$this->dirty = true;
if ($sessionindex !== NULL) {
$this->authData[$this->authority]['saml:sp:SessionIndex'] = $sessionindex;
} else {
unset($this->authData[$this->authority]['saml:sp:SessionIndex']);
}
}
/**
* Retrieve our SessionIndex.
*
* @return string|NULL Our SessionIndex.
* @deprecated
*/
public function getSessionIndex() {
if (!isset($this->authData[$this->authority]['saml:sp:SessionIndex'])) {
return NULL;
}
return $this->authData[$this->authority]['saml:sp:SessionIndex'];
}
/**
* Set our current NameID.
*
* @param array|NULL $nameid The NameID we received from the IdP
* @deprecated
*/
public function setNameID($nameid) {
assert('is_array($nameid) || is_null($nameid)');
assert('isset($this->authData[$this->authority])');
SimpleSAML_Logger::debug('Library - Session: Set nameID: ');
$this->dirty = true;
if ($nameid !== NULL) {
$this->authData[$this->authority]['saml:sp:NameID'] = $nameid;
} else {
unset($this->authData[$this->authority]['saml:sp:NameID']);
}
}
/**
* Get our NameID.
*
* @return array|NULL The NameID we received from the IdP.
* @deprecated
*/
public function getNameID() {
if (!isset($this->authData[$this->authority]['saml:sp:NameID'])) {
return NULL;
}
return $this->authData[$this->authority]['saml:sp:NameID'];
}
/**
* Set remember me expire time.
*
* @param int $expire Unix timestamp when remember me session cookies expire.
*/
public function setRememberMeExpire($expire = NULL) {
assert('is_int($expire) || is_null($expire)');
if ($expire === NULL) {
$globalConfig = SimpleSAML_Configuration::getInstance();
$expire = time() + $globalConfig->getInteger('session.rememberme.lifetime', 14*86400);
}
$this->rememberMeExpire = $expire;
$cookieParams = array('expire' => $this->rememberMeExpire);
$this->updateSessionCookies($cookieParams);
}
/**
* Get remember me expire time.
*
* @return integer|NULL The remember me expire time.
*/
public function getRememberMeExpire() {
return $this->rememberMeExpire;
}
/**
* Update session cookies.
*/
public function updateSessionCookies($params = NULL) {
$sessionHandler = SimpleSAML_SessionHandler::getSessionHandler();
if ($this->sessionId !== NULL) {
$sessionHandler->setCookie($sessionHandler->getSessionCookieName(), $this->sessionId, $params);
}
if ($this->authToken !== NULL) {
$globalConfig = SimpleSAML_Configuration::getInstance();
$sessionHandler->setCookie($globalConfig->getString('session.authtoken.cookiename',
'SimpleSAMLAuthToken'), $this->authToken, $params);
}
}
/**
* Marks the user as logged in with the specified authority.
*
* If the user already has logged in, the user will be logged out first.
*
* @param string $authority The authority the user logged in with.
* @param array|NULL $data The authentication data for this authority.
*/
public function doLogin($authority, array $data = NULL) {
assert('is_string($authority)');
assert('is_array($data) || is_null($data)');
SimpleSAML_Logger::debug('Session: doLogin("' . $authority . '")');
$this->dirty = TRUE;
if (isset($this->authData[$authority])) {
/* We are already logged in. Log the user out first. */
$this->doLogout($authority);
}
if ($data === NULL) {
$data = array();
}
$data['Authority'] = $authority;
$globalConfig = SimpleSAML_Configuration::getInstance();
if (!isset($data['AuthnInstant'])) {
$data['AuthnInstant'] = time();
}
$maxSessionExpire = time() + $globalConfig->getInteger('session.duration', 8*60*60);
if (!isset($data['Expire']) || $data['Expire'] > $maxSessionExpire) {
/* Unset, or beyond our session lifetime. Clamp it to our maximum session lifetime. */
$data['Expire'] = $maxSessionExpire;
}
$this->authData[$authority] = $data;
$this->authority = $authority;
$this->authToken = SimpleSAML_Utilities::generateID();
$sessionHandler = SimpleSAML_SessionHandler::getSessionHandler();
if (!$this->transient && (!empty($data['RememberMe']) || $this->rememberMeExpire) &&
$globalConfig->getBoolean('session.rememberme.enable', FALSE)) {
$this->setRememberMeExpire();
} else {
$sessionHandler->setCookie($globalConfig->getString('session.authtoken.cookiename',
'SimpleSAMLAuthToken'), $this->authToken);
}
}
/**
* Marks the user as logged out.
*
* This function will call any registered logout handlers before marking the user as logged out.
*
* @param string|NULL $authority The authentication source we are logging out of.
*/
public function doLogout($authority = NULL) {
SimpleSAML_Logger::debug('Session: doLogout(' . var_export($authority, TRUE) . ')');
if ($authority === NULL) {
if ($this->authority === NULL) {
SimpleSAML_Logger::debug('Session: No current authsource - not logging out.');
return;
}
$authority = $this->authority;
}
if (!isset($this->authData[$authority])) {
SimpleSAML_Logger::debug('Session: Already logged out of ' . $authority . '.');
return;
}
$this->dirty = TRUE;
$this->callLogoutHandlers($authority);
unset($this->authData[$authority]);
if ($this->authority === $authority) {
$this->authority = NULL;
}
if ($this->authority === NULL && $this->rememberMeExpire) {
$this->rememberMeExpire = NULL;
$this->updateSessionCookies();
}
/* Delete data which expires on logout. */
$this->expireDataLogout();
}
/**
* Set the lifetime for authentication source.
*
* @param string $authority The authentication source we are setting expire time for.
* @param int $expire The number of seconds authentication source is valid.
*/
public function setAuthorityExpire($authority, $expire = NULL) {
assert('isset($this->authData[$authority])');
assert('is_int($expire) || is_null($expire)');
$this->dirty = true;
if ($expire === NULL) {
$globalConfig = SimpleSAML_Configuration::getInstance();
$expire = time() + $globalConfig->getInteger('session.duration', 8*60*60);
}
$this->authData[$authority]['Expire'] = $expire;
}
/**
* Set the lifetime of our current authentication session.
*
* @param int $duration The number of seconds this authentication session is valid.
* @deprecated
*/
public function setSessionDuration($duration) {
assert('is_int($duration)');
assert('isset($this->authData[$this->authority])');
SimpleSAML_Logger::debug('Library - Session: Set session duration ' . $duration);
$this->dirty = true;
$this->authData[$this->authority]['Expire'] = time() + $duration;
}
/**
* Is the session representing an authenticated user, and is the session still alive.
* This function will return false after the user has timed out.
*
* @param string $authority The authentication source that the user should be authenticated with.
* @return TRUE if the user has a valid session, FALSE if not.
*/
public function isValid($authority) {
assert('is_string($authority)');
if (!isset($this->authData[$authority])) {
SimpleSAML_Logger::debug('Session: '. var_export($authority, TRUE) .
' not valid because we are not authenticated.');
return FALSE;
}
if ($this->authData[$authority]['Expire'] <= time()) {
SimpleSAML_Logger::debug('Session: ' . var_export($authority, TRUE) .' not valid because it is expired.');
return FALSE;
}
SimpleSAML_Logger::debug('Session: Valid session found with ' . var_export($authority, TRUE) . '.');
return TRUE;
}
/**
* If the user is authenticated, how much time is left of the session.
*
* @return int The number of seconds until the session expires.
* @deprecated
*/
public function remainingTime() {
if (!isset($this->authData[$this->authority])) {
/* Not authenticated. */
return -1;
}
assert('isset($this->authData[$this->authority]["Expire"])');
return $this->authData[$this->authority]['Expire'] - time();
}
/**
* Is the user authenticated. This function does not check the session duration.
*
* @return bool TRUE if the user is authenticated, FALSE otherwise.
* @deprecated
*/
public function isAuthenticated() {
return isset($this->authData[$this->authority]);
}
/**
* Retrieve the time the user was authenticated.
*
* @return int|NULL The timestamp for when the user was authenticated. NULL if the user hasn't authenticated.
* @deprecated
*/
public function getAuthnInstant() {
if (!isset($this->authData[$this->authority])) {
/* Not authenticated. */
return NULL;
}
assert('isset($this->authData[$this->authority]["AuthnInstant"])');
return $this->authData[$this->authority]['AuthnInstant'];
}
/**
* Retrieve the attributes associated with this session.
*
* @return array|NULL The attributes.
* @deprecated
*/
public function getAttributes() {
if (!isset($this->authData[$this->authority]['Attributes'])) {
return NULL;
}
return $this->authData[$this->authority]['Attributes'];
}
/**
* Retrieve a single attribute.
*
* @param string $name The name of the attribute.
* @return array|NULL The values of the given attribute.
* @deprecated
*/
public function getAttribute($name) {
if (!isset($this->authData[$this->authority]['Attributes'][$name])) {
return NULL;
}
return $this->authData[$this->authority]['Attributes'][$name];
}
/**
* Set the attributes for this session.
*
* @param array|NULL $attributes The attributes of this session.
* @deprecated
*/
public function setAttributes($attributes) {
assert('isset($this->authData[$this->authority])');
$this->dirty = true;
$this->authData[$this->authority]['Attributes'] = $attributes;
}
/**
* Set the values of a single attribute.
*
* @param string $name The name of the attribute.
* @param array $value The values of the attribute.
*/
public function setAttribute($name, $value) {
assert('isset($this->authData[$this->authority])');
$this->dirty = true;
$this->authData[$this->authority]['Attributes'][$name] = $value;
}
/**
* Calculates the size of the session object after serialization
*
* @return int The size of the session measured in bytes.
* @deprecated
*/
public function getSize() {
$s = serialize($this);
return strlen($s);
}
/**
* This function registers a logout handler.
*
* @param string $classname The class which contains the logout handler.
* @param string $functionname The logout handler function.
* @throws Exception If the handler is not a valid function or method.
*/
public function registerLogoutHandler($classname, $functionname) {
assert('isset($this->authData[$this->authority])');
$logout_handler = array($classname, $functionname);
if(!is_callable($logout_handler)) {
throw new Exception('Logout handler is not a vaild function: ' . $classname . '::' .
$functionname);
}
$this->authData[$this->authority]['LogoutHandlers'][] = $logout_handler;
$this->dirty = TRUE;
}
/**
* This function calls all registered logout handlers.
*
* @param string $authority The authentication source we are logging out from.
* @throws Exception If the handler is not a valid function or method.
*/
private function callLogoutHandlers($authority) {
assert('is_string($authority)');
assert('isset($this->authData[$authority])');
if (empty($this->authData[$authority]['LogoutHandlers'])) {
return;
}
foreach($this->authData[$authority]['LogoutHandlers'] as $handler) {
/* Verify that the logout handler is a valid function. */
if(!is_callable($handler)) {
$classname = $handler[0];
$functionname = $handler[1];
throw new Exception('Logout handler is not a vaild function: ' . $classname . '::' .
$functionname);
}
/* Call the logout handler. */
call_user_func($handler);
}
/* We require the logout handlers to register themselves again if they want to be called later. */
unset($this->authData[$authority]['LogoutHandlers']);
}
/**
* This function removes expired data from the data store.
*
* Note that this function doesn't mark the session object as dirty. This means that
* if the only change to the session object is that some data has expired, it will not be
* written back to the session store.
*/
private function expireData() {
if(!is_array($this->dataStore)) {
return;
}
$ct = time();
foreach($this->dataStore as &$typedData) {
foreach($typedData as $id => $info) {
if ($info['expires'] === self::DATA_TIMEOUT_LOGOUT) {
/* This data only expires on logout. */
continue;
}
if ($info['expires'] === self::DATA_TIMEOUT_SESSION_END) {
/* This data never expires. */
continue;
}
if($ct > $info['expires']) {
unset($typedData[$id]);
}
}
}
}
/**
* This function deletes data which should be deleted on logout from the data store.
* @deprecated
*/
private function expireDataLogout() {
if(!is_array($this->dataStore)) {
return;
}
$this->dirty = TRUE;
foreach ($this->dataStore as &$typedData) {
foreach ($typedData as $id => $info) {
if ($info['expires'] === self::DATA_TIMEOUT_LOGOUT) {
unset($typedData[$id]);
}
}
}
}
/**
* Delete data from the data store.
*
* This function immediately deletes the data with the given type and id from the data store.
*
* @param string $type The type of the data.
* @param string $id The identifier of the data.
*/
public function deleteData($type, $id) {
assert('is_string($type)');
assert('is_string($id)');
if (!is_array($this->dataStore)) {
return;
}
if(!array_key_exists($type, $this->dataStore)) {
return;
}
unset($this->dataStore[$type][$id]);
$this->dirty = TRUE;
}
/**
* This function stores data in the data store.
*
* The timeout value can be SimpleSAML_Session::DATA_TIMEOUT_LOGOUT, which indicates
* that the data should be deleted on logout (and not before).
*
* @param string $type The type of the data. This is checked when retrieving data from the store.
* @param string $id The identifier of the data.
* @param mixed $data The data.
* @param int|NULL $timeout The number of seconds this data should be stored after its last access.
* This parameter is optional. The default value is set in 'session.datastore.timeout',
* and the default is 4 hours.
* @throws Exception If the data couldn't be stored.
*
*/
public function setData($type, $id, $data, $timeout = NULL) {
assert('is_string($type)');
assert('is_string($id)');
assert('is_int($timeout) || is_null($timeout) || $timeout === self::DATA_TIMEOUT_LOGOUT ||'.
' $timeout === self::DATA_TIMEOUT_SESSION_END');
/* Clean out old data. */
$this->expireData();
if($timeout === NULL) {
/* Use the default timeout. */
$configuration = SimpleSAML_Configuration::getInstance();
$timeout = $configuration->getInteger('session.datastore.timeout', NULL);
if($timeout !== NULL) {
if ($timeout <= 0) {
throw new Exception('The value of the session.datastore.timeout' .
' configuration option should be a positive integer.');
}
} else {
/* For backwards compatibility. */
$timeout = $configuration->getInteger('session.requestcache', 4*(60*60));
if ($timeout <= 0) {
throw new Exception('The value of the session.requestcache' .
' configuration option should be a positive integer.');
}
}
}
if ($timeout === self::DATA_TIMEOUT_LOGOUT) {
$expires = self::DATA_TIMEOUT_LOGOUT;
} elseif ($timeout === self::DATA_TIMEOUT_SESSION_END) {
$expires = self::DATA_TIMEOUT_SESSION_END;
} else {
$expires = time() + $timeout;
}
$dataInfo = array(
'expires' => $expires,
'timeout' => $timeout,
'data' => $data
);
if(!is_array($this->dataStore)) {
$this->dataStore = array();
}
if(!array_key_exists($type, $this->dataStore)) {
$this->dataStore[$type] = array();
}
$this->dataStore[$type][$id] = $dataInfo;
$this->dirty = TRUE;
}
/**
* This function retrieves data from the data store.
*
* Note that this will not change when the data stored in the data store will expire. If that is required,
* the data should be written back with setData.
*
* @param string $type The type of the data. This must match the type used when adding the data.
* @param string|NULL $id The identifier of the data. Can be NULL, in which case NULL will be returned.
* @return mixed The data of the given type with the given id or NULL if the data doesn't exist in the data store.
*/
public function getData($type, $id) {
assert('is_string($type)');
assert('$id === NULL || is_string($id)');
if($id === NULL) {
return NULL;
}
$this->expireData();
if(!is_array($this->dataStore)) {
return NULL;
}
if(!array_key_exists($type, $this->dataStore)) {
return NULL;
}
if(!array_key_exists($id, $this->dataStore[$type])) {
return NULL;
}
return $this->dataStore[$type][$id]['data'];
}
/**
* This function retrieves all data of the specified type from the data store.
*
* The data will be returned as an associative array with the id of the data as the key, and the data
* as the value of each key. The value will be stored as a copy of the original data. setData must be
* used to update the data.
*
* An empty array will be returned if no data of the given type is found.
*
* @param string $type The type of the data.
* @return array An associative array with all data of the given type.
*/
public function getDataOfType($type) {
assert('is_string($type)');
if(!is_array($this->dataStore)) {
return array();
}
if(!array_key_exists($type, $this->dataStore)) {
return array();
}
$ret = array();
foreach($this->dataStore[$type] as $id => $info) {
$ret[$id] = $info['data'];
}
return $ret;
}
/**
* Create a new session and cache it.
*
* @param string $sessionId The new session we should create.
*/
public static function createSession($sessionId) {
assert('is_string($sessionId)');
self::$sessions[$sessionId] = NULL;
}
/**
* Load a session from the session handler.
*
* @param string|NULL $sessionId The session we should load, or NULL to load the current session.
* @return The session which is stored in the session handler, or NULL if the session wasn't found.
*/
public static function getSession($sessionId = NULL) {
assert('is_string($sessionId) || is_null($sessionId)');
$sh = SimpleSAML_SessionHandler::getSessionHandler();
if ($sessionId === NULL) {
$checkToken = TRUE;
$sessionId = $sh->getCookieSessionId();
} else {
$checkToken = FALSE;
}
if (array_key_exists($sessionId, self::$sessions)) {
return self::$sessions[$sessionId];
}
$session = $sh->loadSession($sessionId);
if($session === NULL) {
return NULL;
}
assert('$session instanceof self');
if ($checkToken) {
$globalConfig = SimpleSAML_Configuration::getInstance();
if ($session->authToken !== NULL) {
$authTokenCookieName = $globalConfig->getString('session.authtoken.cookiename',
'SimpleSAMLAuthToken');
if (!isset($_COOKIE[$authTokenCookieName])) {
SimpleSAML_Logger::warning('Missing AuthToken cookie.');
return NULL;
}
if ($_COOKIE[$authTokenCookieName] !== $session->authToken) {
SimpleSAML_Logger::warning('Invalid AuthToken cookie.');
return NULL;
}
}
/* Run session check function if defined */
$checkFunction = $globalConfig->getArray('session.check_function', NULL);
if (isset($checkFunction)) {
assert('is_callable($checkFunction)');
$check = call_user_func($checkFunction, $session);
if ($check !== TRUE) {
SimpleSAML_Logger::warning('Session did not pass check function.');
return NULL;
}
}
}
self::$sessions[$sessionId] = $session;
return $session;
}
/**
* Set the logout state for this session.
*
* @param array $state The state array.
* @deprecated
*/
public function setLogoutState(array $state) {
assert('isset($this->authData[$this->authority])');
$this->dirty = TRUE;
$this->authData[$this->authority]['LogoutState'] = $state;
}
/**
* Retrieve the logout state for this session.
*
* @return array The logout state. If no logout state is set, an empty array will be returned.
* @deprecated
*/
public function getLogoutState() {
assert('isset($this->authData[$this->authority])');
if (!isset($this->authData[$this->authority]['LogoutState'])) {
return array();
}
return $this->authData[$this->authority]['LogoutState'];
}
/**
* Get the current persistent authentication state.
*
* @param string|NULL $authority The authority to retrieve the data from.
* @return array The current persistent authentication state, or NULL if not authenticated.
*/
public function getAuthState($authority = NULL) {
assert('is_string($authority) || is_null($authority)');
if ($authority === NULL) {
$authority = $this->authority;
}
if (!isset($this->authData[$authority])) {
return NULL;
}
return $this->authData[$authority];
}
/**
* Check whether the session cookie is set.
*
* This function will only return FALSE if is is certain that the cookie isn't set.
*
* @return bool TRUE if it was set, FALSE if not.
*/
public function hasSessionCookie() {
$sh = SimpleSAML_SessionHandler::getSessionHandler();
return $sh->hasSessionCookie();
}
/**
* Add an SP association for an IdP.
*
* This function is only for use by the SimpleSAML_IdP class.
*
* @param string $idp The IdP id.
* @param array $association The association we should add.
*/
public function addAssociation($idp, array $association) {
assert('is_string($idp)');
assert('isset($association["id"])');
assert('isset($association["Handler"])');
if (!isset($this->associations)) {
$this->associations = array();
}
if (!isset($this->associations[$idp])) {
$this->associations[$idp] = array();
}
$this->associations[$idp][$association['id']] = $association;
$this->dirty = TRUE;
}
/**
* Retrieve the associations for an IdP.
*
* This function is only for use by the SimpleSAML_IdP class.
*
* @param string $idp The IdP id.
* @return array The IdP associations.
*/
public function getAssociations($idp) {
assert('is_string($idp)');
if (!isset($this->associations)) {
$this->associations = array();
}
if (!isset($this->associations[$idp])) {
return array();
}
foreach ($this->associations[$idp] as $id => $assoc) {
if (!isset($assoc['Expires'])) {
continue;
}
if ($assoc['Expires'] >= time()) {
continue;
}
unset($this->associations[$idp][$id]);
}
return $this->associations[$idp];
}
/**
* Remove an SP association for an IdP.
*
* This function is only for use by the SimpleSAML_IdP class.
*
* @param string $idp The IdP id.
* @param string $associationId The id of the association.
*/
public function terminateAssociation($idp, $associationId) {
assert('is_string($idp)');
assert('is_string($associationId)');
if (!isset($this->associations)) {
return;
}
if (!isset($this->associations[$idp])) {
return;
}
unset($this->associations[$idp][$associationId]);
$this->dirty = TRUE;
}
/**
* Get a list of associated SAML 2 SPs.
*
* This function is just for backwards-compatibility. New code should
* use the SimpleSAML_IdP::getAssociations()-function.
*
* @return array Array of SAML 2 entityIDs.
* @deprecated Will be removed in the future.
*/
public function get_sp_list() {
$metadata = SimpleSAML_Metadata_MetaDataStorageHandler::getMetadataHandler();
try {
$idpEntityId = $metadata->getMetaDataCurrentEntityID('saml20-idp-hosted');
$idp = SimpleSAML_IdP::getById('saml2:' . $idpEntityId);
} catch (Exception $e) {
/* No SAML 2 IdP configured? */
return array();
}
$ret = array();
foreach ($idp->getAssociations() as $assoc) {
if (isset($assoc['saml:entityID'])) {
$ret[] = $assoc['saml:entityID'];
}
}
return $ret;
}
/**
* Retrieve authentication data.
*
* @param string $authority The authentication source we should retrieve data from.
* @param string $name The name of the data we should retrieve.
* @return mixed The value, or NULL if the value wasn't found.
*/
public function getAuthData($authority, $name) {
assert('is_string($authority)');
assert('is_string($name)');
if (!isset($this->authData[$authority][$name])) {
return NULL;
}
return $this->authData[$authority][$name];
}
}
|