ILIAS  release_5-3 Revision v5.3.23-19-g915713cf615
SimpleSAML\Utils\HTTP Class Reference
+ Collaboration diagram for SimpleSAML\Utils\HTTP:

Static Public Member Functions

static getServerHTTPS ()
 Retrieve HTTPS status from $_SERVER environment variables. More...
 
static getServerPort ()
 Retrieve the port number from $_SERVER environment variables. More...
 
static checkSessionCookie ($retryURL=null)
 Check for session cookie, and show missing-cookie page if it is missing. More...
 
static checkURLAllowed ($url, array $trustedSites=null)
 Check if a URL is valid and is in our list of allowed URLs. More...
 
static fetch ($url, $context=array(), $getHeaders=false)
 Helper function to retrieve a file or URL with proxy support, also supporting proxy basic authorization. More...
 
static getAcceptLanguage ()
 This function parses the Accept-Language HTTP header and returns an associative array with each language and the score for that language. More...
 
static guessBasePath ()
 Try to guess the base SimpleSAMLphp path from the current request. More...
 
static getBaseURL ()
 Retrieve the base URL of the SimpleSAMLphp installation. More...
 
static getFirstPathElement ($trailingslash=true)
 Retrieve the first element of the URL path. More...
 
static getPOSTRedirectURL ($destination, $data)
 Create a link which will POST data. More...
 
static getSelfHost ()
 Retrieve our own host. More...
 
static getSelfHostWithPath ()
 Retrieve our own host together with the URL path. More...
 
static getSelfURLNoQuery ()
 Retrieve the current URL using the base URL in the configuration, without the query parameters. More...
 
static isHTTPS ()
 This function checks if we are using HTTPS as protocol. More...
 
static normalizeURL ($url)
 Normalizes a URL to an absolute URL and validate it. More...
 
static parseQueryString ($query_string)
 Parse a query string into an array. More...
 
static redirectTrustedURL ($url, $parameters=array())
 This function redirects to the specified URL without performing any security checks. More...
 
static redirectUntrustedURL ($url, $parameters=array())
 This function redirects to the specified URL after performing the appropriate security checks on it. More...
 
static resolveURL ($url, $base=null)
 Resolve a (possibly relative) URL relative to a given base URL. More...
 
static setCookie ($name, $value, $params=null, $throw=true)
 Set a cookie. More...
 
static submitPOSTData ($destination, $data)
 Submit a POST form to a specific destination. More...
 

Static Private Member Functions

static getSecurePOSTRedirectURL ($destination, $data)
 Obtain a URL where we can redirect to securely post a form with the given data to a specific destination. More...
 
static getServerHost ()
 Retrieve Host value from $_SERVER environment variables. More...
 
static redirect ($url, $parameters=array())
 This function redirects the user to the specified address. More...
 
static savePOSTData (\SimpleSAML_Session $session, $destination, $data)
 Save the given HTTP POST data and the destination where it should be posted to a given session. More...
 

Detailed Description

Definition at line 12 of file HTTP.php.

Member Function Documentation

◆ checkSessionCookie()

static SimpleSAML\Utils\HTTP::checkSessionCookie (   $retryURL = null)
static

Check for session cookie, and show missing-cookie page if it is missing.

Parameters
string | null$retryURLThe URL the user should access to retry the operation. Defaults to null.
Returns
void If there is a session cookie, nothing will be returned. Otherwise, the user will be redirected to a page telling about the missing cookie.
Exceptions

Definition at line 287 of file HTTP.php.

Referenced by SimpleSAML_Utilities\checkCookie(), sspmod_saml_IdP_SAML1\receiveAuthnRequest(), and sspmod_saml_IdP_SAML2\receiveAuthnRequest().

288  {
289  if (!is_null($retryURL) && !is_string($retryURL)) {
290  throw new \InvalidArgumentException('Invalid input parameters.');
291  }
292 
294  if ($session->hasSessionCookie()) {
295  return;
296  }
297 
298  // we didn't have a session cookie. Redirect to the no-cookie page
299 
300  $url = Module::getModuleURL('core/no_cookie.php');
301  if ($retryURL !== null) {
302  $url = self::addURLParameters($url, array('retryURL' => $retryURL));
303  }
304  self::redirectTrustedURL($url);
305  }
$session
static getModuleURL($resource, array $parameters=array())
Get absolute URL to a specified module resource.
Definition: Module.php:303
Create styles array
The data for the language used.
$url
static getSessionFromRequest()
Retrieves the current session.
Definition: Session.php:243
+ Here is the caller graph for this function:

◆ checkURLAllowed()

static SimpleSAML\Utils\HTTP::checkURLAllowed (   $url,
array  $trustedSites = null 
)
static

Check if a URL is valid and is in our list of allowed URLs.

Parameters
string$urlThe URL to check.
array$trustedSitesAn optional white list of domains. If none specified, the 'trusted.url.domains' configuration directive will be used.
Returns
string The normalized URL itself if it is allowed. An empty string if the $url parameter is empty as defined by the empty() function.
Exceptions

Definition at line 322 of file HTTP.php.

Referenced by SimpleSAML_XHTML_IdPDisco\__construct().

323  {
324  if (empty($url)) {
325  return '';
326  }
327  $url = self::normalizeURL($url);
328 
329  if (filter_var($url, FILTER_VALIDATE_URL) === false) {
330  throw new \SimpleSAML_Error_Exception('Invalid URL: '.$url);
331  }
332 
333  // get the white list of domains
334  if ($trustedSites === null) {
335  $trustedSites = \SimpleSAML_Configuration::getInstance()->getValue('trusted.url.domains', array());
336  }
337 
338  // validates the URL's host is among those allowed
339  if (is_array($trustedSites)) {
340  assert(is_array($trustedSites));
341  $components = parse_url($url);
342  $hostname = $components['host'];
343 
344  // check for userinfo
345  if ((isset($components['user']) && strpos($components['user'], '\\') !== false) ||
346  (isset($components['pass']) && strpos($components['pass'], '\\') !== false)
347  ) {
348  throw new \SimpleSAML_Error_Exception('Invalid URL: '.$url);
349  }
350 
351  // allow URLs with standard ports specified (non-standard ports must then be allowed explicitly)
352  if (isset($components['port']) &&
353  (($components['scheme'] === 'http' && $components['port'] !== 80) ||
354  ($components['scheme'] === 'https' && $components['port'] !== 443))
355  ) {
356  $hostname = $hostname.':'.$components['port'];
357  }
358 
359  $self_host = self::getSelfHostWithNonStandardPort();
360 
361  $trustedRegex = \SimpleSAML_Configuration::getInstance()->getValue('trusted.url.regex', false);
362 
363  $trusted = false;
364  if ($trustedRegex) {
365  // add self host to the white list
366  $trustedSites[] = preg_quote($self_host);
367  foreach ($trustedSites as $regex) {
368  // Add start and end delimiters.
369  $regex = "@^{$regex}$@";
370  if (preg_match($regex, $hostname)) {
371  $trusted = true;
372  break;
373  }
374  }
375  } else {
376  // add self host to the white list
377  $trustedSites[] = $self_host;
378  $trusted = in_array($hostname, $trustedSites, true);
379  }
380 
381  // throw exception due to redirection to untrusted site
382  if (!$trusted) {
383  throw new \SimpleSAML_Error_Exception('URL not allowed: '.$url);
384  }
385  }
386  return $url;
387  }
Create styles array
The data for the language used.
$url
static getInstance($instancename='simplesaml')
Get a configuration file by its instance name.
+ Here is the caller graph for this function:

◆ fetch()

static SimpleSAML\Utils\HTTP::fetch (   $url,
  $context = array(),
  $getHeaders = false 
)
static

Helper function to retrieve a file or URL with proxy support, also supporting proxy basic authorization.

An exception will be thrown if we are unable to retrieve the data.

Parameters
string$urlThe path or URL we should fetch.
array$contextExtra context options. This parameter is optional.
boolean$getHeadersWhether to also return response headers. Optional.
Returns
string|array An array if $getHeaders is set, containing the data and the headers respectively; string otherwise.
Exceptions

Definition at line 409 of file HTTP.php.

Referenced by sspmod_cas_Auth_Source_CAS\casServiceValidate(), sspmod_cas_Auth_Source_CAS\casValidate(), SimpleSAML\Bindings\Shib13\Artifact\extractResponse(), sspmod_authwindowslive_Auth_Source_LiveID\finalStep(), sspmod_metarefresh_MetaLoader\loadSource(), SimpleSAML_Metadata_SAMLParser\parseDescriptorsFile(), and SimpleSAML_Metadata_SAMLParser\parseFile().

410  {
411  if (!is_string($url)) {
412  throw new \InvalidArgumentException('Invalid input parameters.');
413  }
414 
416 
417  $proxy = $config->getString('proxy', null);
418  if ($proxy !== null) {
419  if (!isset($context['http']['proxy'])) {
420  $context['http']['proxy'] = $proxy;
421  }
422  $proxy_auth = $config->getString('proxy.auth', false);
423  if ($proxy_auth !== false) {
424  $context['http']['header'] = "Proxy-Authorization: Basic".base64_encode($proxy_auth);
425  }
426  if (!isset($context['http']['request_fulluri'])) {
427  $context['http']['request_fulluri'] = true;
428  }
429  /*
430  * If the remote endpoint over HTTPS uses the SNI extension (Server Name Indication RFC 4366), the proxy
431  * could introduce a mismatch between the names in the Host: HTTP header and the SNI_server_name in TLS
432  * negotiation (thanks to Cristiano Valli @ GARR-IDEM to have pointed this problem).
433  * See: https://bugs.php.net/bug.php?id=63519
434  * These controls will force the same value for both fields.
435  * Marco Ferrante (marco@csita.unige.it), Nov 2012
436  */
437  if (preg_match('#^https#i', $url)
438  && defined('OPENSSL_TLSEXT_SERVER_NAME')
439  && OPENSSL_TLSEXT_SERVER_NAME
440  ) {
441  // extract the hostname
442  $hostname = parse_url($url, PHP_URL_HOST);
443  if (!empty($hostname)) {
444  $context['ssl'] = array(
445  'SNI_server_name' => $hostname,
446  'SNI_enabled' => true,
447  );
448  } else {
449  Logger::warning('Invalid URL format or local URL used through a proxy');
450  }
451  }
452  }
453 
454  $context = stream_context_create($context);
455  $data = file_get_contents($url, false, $context);
456  if ($data === false) {
457  $error = error_get_last();
458  throw new \SimpleSAML_Error_Exception('Error fetching '.var_export($url, true).':'.
459  (is_array($error) ? $error['message'] : 'no error available'));
460  }
461 
462  // data and headers
463  if ($getHeaders) {
464  if (isset($http_response_header)) {
465  $headers = array();
466  foreach ($http_response_header as $h) {
467  if (preg_match('@^HTTP/1\.[01]\s+\d{3}\s+@', $h)) {
468  $headers = array(); // reset
469  $headers[0] = $h;
470  continue;
471  }
472  $bits = explode(':', $h, 2);
473  if (count($bits) === 2) {
474  $headers[strtolower($bits[0])] = trim($bits[1]);
475  }
476  }
477  } else {
478  // no HTTP headers, probably a different protocol, e.g. file
479  $headers = null;
480  }
481  return array($data, $headers);
482  }
483 
484  return $data;
485  }
$h
$error
Definition: Error.php:17
static warning($string)
Definition: Logger.php:179
Create styles array
The data for the language used.
$url
defined( 'APPLICATION_ENV')||define( 'APPLICATION_ENV'
Definition: bootstrap.php:27
static getInstance($instancename='simplesaml')
Get a configuration file by its instance name.
+ Here is the caller graph for this function:

◆ getAcceptLanguage()

static SimpleSAML\Utils\HTTP::getAcceptLanguage ( )
static

This function parses the Accept-Language HTTP header and returns an associative array with each language and the score for that language.

If a language includes a region, then the result will include both the language with the region and the language without the region.

The returned array will be in the same order as the input.

Returns
array An associative array with each language and the score for that language.
Author
Olav Morken, UNINETT AS olav..nosp@m.mork.nosp@m.en@un.nosp@m.inet.nosp@m.t.no

Definition at line 499 of file HTTP.php.

Referenced by SimpleSAML\Locale\Language\getHTTPLanguage().

500  {
501  if (!array_key_exists('HTTP_ACCEPT_LANGUAGE', $_SERVER)) {
502  // no Accept-Language header, return an empty set
503  return array();
504  }
505 
506  $languages = explode(',', strtolower($_SERVER['HTTP_ACCEPT_LANGUAGE']));
507 
508  $ret = array();
509 
510  foreach ($languages as $l) {
511  $opts = explode(';', $l);
512 
513  $l = trim(array_shift($opts)); // the language is the first element
514 
515  $q = 1.0;
516 
517  // iterate over all options, and check for the quality option
518  foreach ($opts as $o) {
519  $o = explode('=', $o);
520  if (count($o) < 2) {
521  // skip option with no value
522  continue;
523  }
524 
525  $name = trim($o[0]);
526  $value = trim($o[1]);
527 
528  if ($name === 'q') {
529  $q = (float) $value;
530  }
531  }
532 
533  // remove the old key to ensure that the element is added to the end
534  unset($ret[$l]);
535 
536  // set the quality in the result
537  $ret[$l] = $q;
538 
539  if (strpos($l, '-')) {
540  // the language includes a region part
541 
542  // extract the language without the region
543  $l = explode('-', $l);
544  $l = $l[0];
545 
546  // add this language to the result (unless it is defined already)
547  if (!array_key_exists($l, $ret)) {
548  $ret[$l] = $q;
549  }
550  }
551  }
552  return $ret;
553  }
if((!isset($_SERVER['DOCUMENT_ROOT'])) OR(empty($_SERVER['DOCUMENT_ROOT']))) $_SERVER['DOCUMENT_ROOT']
if($format !==null) $name
Definition: metadata.php:146
Create styles array
The data for the language used.
global $l
Definition: afr.php:30
$ret
Definition: parser.php:6
+ Here is the caller graph for this function:

◆ getBaseURL()

static SimpleSAML\Utils\HTTP::getBaseURL ( )
static

Retrieve the base URL of the SimpleSAMLphp installation.

The URL will always end with a '/'. For example: https://idp.example.org/simplesaml/

Returns
string The absolute base URL for the SimpleSAMLphp installation.
Exceptions

Definition at line 598 of file HTTP.php.

Referenced by SimpleSAML_Metadata_MetaDataStorageHandlerFlatFile\generateDynamicHostedEntityID(), SimpleSAML_Metadata_MetaDataStorageHandlerPdo\generateDynamicHostedEntityID(), and SimpleSAML_Error_Error\show().

599  {
601  $baseURL = $globalConfig->getString('baseurlpath', 'simplesaml/');
602 
603  if (preg_match('#^https?://.*/?$#D', $baseURL, $matches)) {
604  // full URL in baseurlpath, override local server values
605  return rtrim($baseURL, '/').'/';
606  } elseif (
607  (preg_match('#^/?([^/]?.*/)$#D', $baseURL, $matches)) ||
608  (preg_match('#^\*(.*)/$#D', $baseURL, $matches)) ||
609  ($baseURL === '')
610  ) {
611  // get server values
612  $protocol = 'http';
613  $protocol .= (self::getServerHTTPS()) ? 's' : '';
614  $protocol .= '://';
615 
616  $hostname = self::getServerHost();
617  $port = self::getServerPort();
618  $path = $globalConfig->getBasePath();
619 
620  return $protocol.$hostname.$port.$path;
621  } else {
622  /*
623  * Invalid 'baseurlpath'. We cannot recover from this, so throw a critical exception and try to be graceful
624  * with the configuration. Use a guessed base path instead of the one provided.
625  */
626  $c = $globalConfig->toArray();
627  $c['baseurlpath'] = self::guessBasePath();
628  throw new \SimpleSAML\Error\CriticalConfigurationError(
629  'Invalid value for \'baseurlpath\' in config.php. Valid format is in the form: '.
630  '[(http|https)://(hostname|fqdn)[:port]]/[path/to/simplesaml/]. It must end with a \'/\'.',
631  null,
632  $c
633  );
634  }
635  }
$globalConfig
static getInstance($instancename='simplesaml')
Get a configuration file by its instance name.
+ Here is the caller graph for this function:

◆ getFirstPathElement()

static SimpleSAML\Utils\HTTP::getFirstPathElement (   $trailingslash = true)
static

Retrieve the first element of the URL path.

Parameters
boolean$trailingslashWhether to add a trailing slash to the element or not. Defaults to true.
Returns
string The first element of the URL path, with an optional, trailing slash.
Author
Andreas Solberg, UNINETT AS andre.nosp@m.as.s.nosp@m.olber.nosp@m.g@un.nosp@m.inett.nosp@m..no

Definition at line 647 of file HTTP.php.

648  {
649  if (preg_match('|^/(.*?)/|', $_SERVER['SCRIPT_NAME'], $matches)) {
650  return ($trailingslash ? '/' : '').$matches[1];
651  }
652  return '';
653  }
if((!isset($_SERVER['DOCUMENT_ROOT'])) OR(empty($_SERVER['DOCUMENT_ROOT']))) $_SERVER['DOCUMENT_ROOT']

◆ getPOSTRedirectURL()

static SimpleSAML\Utils\HTTP::getPOSTRedirectURL (   $destination,
  $data 
)
static

Create a link which will POST data.

Parameters
string$destinationThe destination URL.
array$dataThe name-value pairs which will be posted to the destination.
Returns
string A URL which can be accessed to post the data.
Exceptions

Definition at line 668 of file HTTP.php.

Referenced by SimpleSAML\Auth\Simple\login().

669  {
670  if (!is_string($destination) || !is_array($data)) {
671  throw new \InvalidArgumentException('Invalid input parameters.');
672  }
673 
675  $allowed = $config->getBoolean('enable.http_post', false);
676 
677  if ($allowed && preg_match("#^http:#", $destination) && self::isHTTPS()) {
678  // we need to post the data to HTTP
679  $url = self::getSecurePOSTRedirectURL($destination, $data);
680  } else { // post the data directly
682  $id = self::savePOSTData($session, $destination, $data);
683  $url = Module::getModuleURL('core/postredirect.php', array('RedirId' => $id));
684  }
685 
686  return $url;
687  }
$session
$destination
if(!array_key_exists('StateId', $_REQUEST)) $id
static getModuleURL($resource, array $parameters=array())
Get absolute URL to a specified module resource.
Definition: Module.php:303
Create styles array
The data for the language used.
$url
static getSessionFromRequest()
Retrieves the current session.
Definition: Session.php:243
static getInstance($instancename='simplesaml')
Get a configuration file by its instance name.
+ Here is the caller graph for this function:

◆ getSecurePOSTRedirectURL()

static SimpleSAML\Utils\HTTP::getSecurePOSTRedirectURL (   $destination,
  $data 
)
staticprivate

Obtain a URL where we can redirect to securely post a form with the given data to a specific destination.

Parameters
string$destinationThe destination URL.
array$dataAn associative array containing the data to be posted to $destination.
Exceptions

Definition at line 26 of file HTTP.php.

References $data, $destination, $id, $info, $session, $url, SimpleSAML\Utils\Crypto\aesEncrypt(), array, SimpleSAML\Module\getModuleURL(), and SimpleSAML_Session\getSessionFromRequest().

27  {
29  $id = self::savePOSTData($session, $destination, $data);
30 
31  // get the session ID
32  $session_id = $session->getSessionId();
33  if (is_null($session_id)) {
34  // this is a transient session, it is pointless to continue
35  throw new \SimpleSAML_Error_Exception('Cannot save POST data to a transient session.');
36  }
37 
38  // encrypt the session ID and the random ID
39  $info = base64_encode(Crypto::aesEncrypt($session_id.':'.$id));
40 
41  $url = Module::getModuleURL('core/postredirect.php', array('RedirInfo' => $info));
42  return preg_replace('#^https:#', 'http:', $url);
43  }
static aesEncrypt($data)
Encrypt data using AES-256-CBC and the system-wide secret salt as key.
Definition: Crypto.php:146
$session
$destination
if(!array_key_exists('StateId', $_REQUEST)) $id
static getModuleURL($resource, array $parameters=array())
Get absolute URL to a specified module resource.
Definition: Module.php:303
Create styles array
The data for the language used.
$url
$info
Definition: index.php:5
static getSessionFromRequest()
Retrieves the current session.
Definition: Session.php:243
+ Here is the call graph for this function:

◆ getSelfHost()

static SimpleSAML\Utils\HTTP::getSelfHost ( )
static

Retrieve our own host.

E.g. www.example.com

Returns
string The current host.
Author
Jaime Perez, UNINETT AS jaime.nosp@m..per.nosp@m.ez@un.nosp@m.inet.nosp@m.t.no

Definition at line 699 of file HTTP.php.

Referenced by SimpleSAML_Metadata_MetaDataStorageHandler\getMetaDataCurrentEntityID(), SimpleSAML\Auth\Simple\getProcessedURL(), and SimpleSAML_Metadata_MetaDataStorageSource\lookupIndexFromEntityId().

700  {
701  $decomposed = explode(':', self::getSelfHostWithNonStandardPort());
702  return array_shift($decomposed);
703  }
+ Here is the caller graph for this function:

◆ getSelfHostWithPath()

static SimpleSAML\Utils\HTTP::getSelfHostWithPath ( )
static

Retrieve our own host together with the URL path.

Please note this function will return the base URL for the current SP, as defined in the global configuration.

Returns
string The current host (with non-default ports included) plus the URL path.
Author
Andreas Solberg, UNINETT AS andre.nosp@m.as.s.nosp@m.olber.nosp@m.g@un.nosp@m.inett.nosp@m..no
Olav Morken, UNINETT AS olav..nosp@m.mork.nosp@m.en@un.nosp@m.inet.nosp@m.t.no

Definition at line 738 of file HTTP.php.

Referenced by SimpleSAML_Metadata_MetaDataStorageHandler\getMetaDataCurrentEntityID().

739  {
740  $baseurl = explode("/", self::getBaseURL());
741  $elements = array_slice($baseurl, 3 - count($baseurl), count($baseurl) - 4);
742  $path = implode("/", $elements);
743  return self::getSelfHostWithNonStandardPort()."/".$path;
744  }
$baseurl
Definition: demo.php:25
getBaseURL($t, $type='get', $key=null, $value=null)
Definition: showstats.php:133
+ Here is the caller graph for this function:

◆ getSelfURLNoQuery()

static SimpleSAML\Utils\HTTP::getSelfURLNoQuery ( )
static

Retrieve the current URL using the base URL in the configuration, without the query parameters.

Returns
string The current URL, not including query parameters.
Author
Andreas Solberg, UNINETT AS andre.nosp@m.as.s.nosp@m.olber.nosp@m.g@un.nosp@m.inett.nosp@m..no
Jaime Perez, UNINETT AS jaime.nosp@m..per.nosp@m.ez@un.nosp@m.inet.nosp@m.t.no

Definition at line 846 of file HTTP.php.

Referenced by sspmod_saml_Message\processAssertion(), sspmod_saml_Message\processResponse(), and SimpleSAML_Error_Error\saveError().

847  {
848  $url = self::getSelfURL();
849  $pos = strpos($url, '?');
850  if (!$pos) {
851  return $url;
852  }
853  return substr($url, 0, $pos);
854  }
$url
+ Here is the caller graph for this function:

◆ getServerHost()

static SimpleSAML\Utils\HTTP::getServerHost ( )
staticprivate

Retrieve Host value from $_SERVER environment variables.

Returns
string The current host name, including the port if needed. It will use localhost when unable to determine the current host.
Author
Olav Morken, UNINETT AS olav..nosp@m.mork.nosp@m.en@un.nosp@m.inet.nosp@m.t.no

Definition at line 54 of file HTTP.php.

References $_SERVER, and $current.

55  {
56  if (array_key_exists('HTTP_HOST', $_SERVER)) {
57  $current = $_SERVER['HTTP_HOST'];
58  } elseif (array_key_exists('SERVER_NAME', $_SERVER)) {
59  $current = $_SERVER['SERVER_NAME'];
60  } else {
61  // almost certainly not what you want, but...
62  $current = 'localhost';
63  }
64 
65  if (strstr($current, ":")) {
66  $decomposed = explode(":", $current);
67  $port = array_pop($decomposed);
68  if (!is_numeric($port)) {
69  array_push($decomposed, $port);
70  }
71  $current = implode($decomposed, ":");
72  }
73  return $current;
74  }
if((!isset($_SERVER['DOCUMENT_ROOT'])) OR(empty($_SERVER['DOCUMENT_ROOT']))) $_SERVER['DOCUMENT_ROOT']

◆ getServerHTTPS()

static SimpleSAML\Utils\HTTP::getServerHTTPS ( )
static

Retrieve HTTPS status from $_SERVER environment variables.

Returns
boolean True if the request was performed through HTTPS, false otherwise.
Author
Olav Morken, UNINETT AS olav..nosp@m.mork.nosp@m.en@un.nosp@m.inet.nosp@m.t.no

Definition at line 84 of file HTTP.php.

References $_SERVER.

Referenced by SimpleSAML\Auth\Simple\getProcessedURL().

85  {
86  if (!array_key_exists('HTTPS', $_SERVER)) {
87  // not an https-request
88  return false;
89  }
90 
91  if ($_SERVER['HTTPS'] === 'off') {
92  // IIS with HTTPS off
93  return false;
94  }
95 
96  // otherwise, HTTPS will be non-empty
97  return !empty($_SERVER['HTTPS']);
98  }
if((!isset($_SERVER['DOCUMENT_ROOT'])) OR(empty($_SERVER['DOCUMENT_ROOT']))) $_SERVER['DOCUMENT_ROOT']
+ Here is the caller graph for this function:

◆ getServerPort()

static SimpleSAML\Utils\HTTP::getServerPort ( )
static

Retrieve the port number from $_SERVER environment variables.

Returns
string The port number prepended by a colon, if it is different than the default port for the protocol (80 for HTTP, 443 for HTTPS), or an empty string otherwise.
Author
Olav Morken, UNINETT AS olav..nosp@m.mork.nosp@m.en@un.nosp@m.inet.nosp@m.t.no

Definition at line 109 of file HTTP.php.

References $_SERVER.

Referenced by SimpleSAML\Auth\Simple\getProcessedURL().

110  {
111  $port = (isset($_SERVER['SERVER_PORT'])) ? $_SERVER['SERVER_PORT'] : '80';
112  if (self::getServerHTTPS()) {
113  if ($port !== '443') {
114  return ':'.$port;
115  }
116  } else {
117  if ($port !== '80') {
118  return ':'.$port;
119  }
120  }
121  return '';
122  }
if((!isset($_SERVER['DOCUMENT_ROOT'])) OR(empty($_SERVER['DOCUMENT_ROOT']))) $_SERVER['DOCUMENT_ROOT']
+ Here is the caller graph for this function:

◆ guessBasePath()

static SimpleSAML\Utils\HTTP::guessBasePath ( )
static

Try to guess the base SimpleSAMLphp path from the current request.

This method offers just a guess, so don't rely on it.

Returns
string The guessed base path that should correspond to the root installation of SimpleSAMLphp.

Definition at line 563 of file HTTP.php.

Referenced by SimpleSAML\Error\CriticalConfigurationError\__construct(), and SimpleSAML_Configuration\getBasePath().

564  {
565  if (!array_key_exists('REQUEST_URI', $_SERVER) || !array_key_exists('SCRIPT_FILENAME', $_SERVER)) {
566  return '/';
567  }
568  // get the name of the current script
569  $path = explode('/', $_SERVER['SCRIPT_FILENAME']);
570  $script = array_pop($path);
571 
572  // get the portion of the URI up to the script, i.e.: /simplesaml/some/directory/script.php
573  if (!preg_match('#^/(?:[^/]+/)*'.$script.'#', $_SERVER['REQUEST_URI'], $matches)) {
574  return '/';
575  }
576  $uri_s = explode('/', $matches[0]);
577  $file_s = explode('/', $_SERVER['SCRIPT_FILENAME']);
578 
579  // compare both arrays from the end, popping elements matching out of them
580  while ($uri_s[count($uri_s) - 1] === $file_s[count($file_s) - 1]) {
581  array_pop($uri_s);
582  array_pop($file_s);
583  }
584  // we are now left with the minimum part of the URI that does not match anything in the file system, use it
585  return join('/', $uri_s).'/';
586  }
if((!isset($_SERVER['DOCUMENT_ROOT'])) OR(empty($_SERVER['DOCUMENT_ROOT']))) $_SERVER['DOCUMENT_ROOT']
+ Here is the caller graph for this function:

◆ isHTTPS()

static SimpleSAML\Utils\HTTP::isHTTPS ( )
static

This function checks if we are using HTTPS as protocol.

Returns
boolean True if the HTTPS is used, false otherwise.
Author
Olav Morken, UNINETT AS olav..nosp@m.mork.nosp@m.en@un.nosp@m.inet.nosp@m.t.no
Jaime Perez, UNINETT AS jaime.nosp@m..per.nosp@m.ez@un.nosp@m.inet.nosp@m.t.no

Definition at line 865 of file HTTP.php.

866  {
867  return strpos(self::getSelfURL(), 'https://') === 0;
868  }

◆ normalizeURL()

static SimpleSAML\Utils\HTTP::normalizeURL (   $url)
static

Normalizes a URL to an absolute URL and validate it.

In addition to resolving the URL, this function makes sure that it is a link to an http or https site.

Parameters
string$urlThe relative URL.
Returns
string An absolute URL for the given relative URL.
Exceptions

Definition at line 883 of file HTTP.php.

884  {
885  if (!is_string($url)) {
886  throw new \InvalidArgumentException('Invalid input parameters.');
887  }
888 
889  $url = self::resolveURL($url, self::getSelfURL());
890 
891  // verify that the URL is to a http or https site
892  if (!preg_match('@^https?://@i', $url)) {
893  throw new \InvalidArgumentException('Invalid URL: '.$url);
894  }
895 
896  return $url;
897  }
$url

◆ parseQueryString()

static SimpleSAML\Utils\HTTP::parseQueryString (   $query_string)
static

Parse a query string into an array.

This function parses a query string into an array, similar to the way the builtin 'parse_str' works, except it doesn't handle arrays, and it doesn't do "magic quotes".

Query parameters without values will be set to an empty string.

Parameters
string$query_stringThe query string which should be parsed.
Returns
array The query string as an associative array.
Exceptions

Definition at line 915 of file HTTP.php.

916  {
917  if (!is_string($query_string)) {
918  throw new \InvalidArgumentException('Invalid input parameters.');
919  }
920 
921  $res = array();
922  if (empty($query_string)) {
923  return $res;
924  }
925 
926  foreach (explode('&', $query_string) as $param) {
927  $param = explode('=', $param);
928  $name = urldecode($param[0]);
929  if (count($param) === 1) {
930  $value = '';
931  } else {
932  $value = urldecode($param[1]);
933  }
934  $res[$name] = $value;
935  }
936  return $res;
937  }
if($format !==null) $name
Definition: metadata.php:146
foreach($_POST as $key=> $value) $res
Create styles array
The data for the language used.

◆ redirect()

static SimpleSAML\Utils\HTTP::redirect (   $url,
  $parameters = array() 
)
staticprivate

This function redirects the user to the specified address.

This function will use the "HTTP 303 See Other" redirection if the current request used the POST method and the HTTP version is 1.1. Otherwise, a "HTTP 302 Found" redirection will be used.

The function will also generate a simple web page with a clickable link to the target page.

Parameters
string$urlThe URL we should redirect to. This URL may include query parameters. If this URL is a relative URL (starting with '/'), then it will be turned into an absolute URL by prefixing it with the absolute URL to the root of the website.
string[]$parameters An array with extra query string parameters which should be appended to the URL. The name of the parameter is the array index. The value of the parameter is the value stored in the index. Both the name and the value will be urlencoded. If the value is NULL, then the parameter will be encoded as just the name, without a value.
Returns
void This function never returns.
Exceptions

Definition at line 148 of file HTTP.php.

References $_SERVER, $code, $url, header, n, and SimpleSAML\Logger\warning().

149  {
150  if (!is_string($url) || empty($url) || !is_array($parameters)) {
151  throw new \InvalidArgumentException('Invalid input parameters.');
152  }
153  if (!empty($parameters)) {
154  $url = self::addURLParameters($url, $parameters);
155  }
156 
157  /* Set the HTTP result code. This is either 303 See Other or
158  * 302 Found. HTTP 303 See Other is sent if the HTTP version
159  * is HTTP/1.1 and the request type was a POST request.
160  */
161  if ($_SERVER['SERVER_PROTOCOL'] === 'HTTP/1.1' &&
162  $_SERVER['REQUEST_METHOD'] === 'POST'
163  ) {
164  $code = 303;
165  } else {
166  $code = 302;
167  }
168 
169  if (strlen($url) > 2048) {
170  Logger::warning('Redirecting to a URL longer than 2048 bytes.');
171  }
172 
173  if (!headers_sent()) {
174  // set the location header
175  header('Location: '.$url, true, $code);
176 
177  // disable caching of this response
178  header('Pragma: no-cache');
179  header('Cache-Control: no-cache, no-store, must-revalidate');
180  }
181 
182  // show a minimal web page with a clickable link to the URL
183  echo '<?xml version="1.0" encoding="UTF-8"?>'."\n";
184  echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"';
185  echo ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">'."\n";
186  echo '<html xmlns="http://www.w3.org/1999/xhtml">'."\n";
187  echo " <head>\n";
188  echo ' <meta http-equiv="content-type" content="text/html; charset=utf-8">'."\n";
189  echo ' <meta http-equiv="refresh" content="0;URL=\''.htmlspecialchars($url).'\'">'."\n";
190  echo " <title>Redirect</title>\n";
191  echo " </head>\n";
192  echo " <body>\n";
193  echo " <h1>Redirect</h1>\n";
194  echo ' <p>You were redirected to: <a id="redirlink" href="'.htmlspecialchars($url).'">';
195  echo htmlspecialchars($url)."</a>\n";
196  echo ' <script type="text/javascript">document.getElementById("redirlink").focus();</script>'."\n";
197  echo " </p>\n";
198  echo " </body>\n";
199  echo '</html>';
200 
201  // end script execution
202  exit;
203  }
if((!isset($_SERVER['DOCUMENT_ROOT'])) OR(empty($_SERVER['DOCUMENT_ROOT']))) $_SERVER['DOCUMENT_ROOT']
$code
Definition: example_050.php:99
if(! $in) print Initializing normalization quick check tables n
static warning($string)
Definition: Logger.php:179
Add a drawing to the header
Definition: 04printing.php:69
$url
+ Here is the call graph for this function:

◆ redirectTrustedURL()

static SimpleSAML\Utils\HTTP::redirectTrustedURL (   $url,
  $parameters = array() 
)
static

This function redirects to the specified URL without performing any security checks.

Please, do NOT use this function with user supplied URLs.

This function will use the "HTTP 303 See Other" redirection if the current request used the POST method and the HTTP version is 1.1. Otherwise, a "HTTP 302 Found" redirection will be used.

The function will also generate a simple web page with a clickable link to the target URL.

Parameters
string$urlThe URL we should redirect to. This URL may include query parameters. If this URL is a relative URL (starting with '/'), then it will be turned into an absolute URL by prefixing it with the absolute URL to the root of the website.
string[]$parameters An array with extra query string parameters which should be appended to the URL. The name of the parameter is the array index. The value of the parameter is the value stored in the index. Both the name and the value will be urlencoded. If the value is NULL, then the parameter will be encoded as just the name, without a value.
Returns
void This function never returns.
Exceptions

Definition at line 962 of file HTTP.php.

Referenced by sspmod_saml_Auth_Source_SP\askForIdPChange(), sspmod_authwindowslive_Auth_Source_LiveID\authenticate(), sspmod_authfacebook_Auth_Source_Facebook\authenticate(), sspmod_exampleauth_Auth_Source_External\authenticate(), sspmod_authYubiKey_Auth_Source_YubiKey\authenticate(), sspmod_multiauth_Auth_Source_MultiAuth\authenticate(), sspmod_core_Auth_UserPassOrgBase\authenticate(), sspmod_core_Auth_UserPassBase\authenticate(), sspmod_cas_Auth_Source_CAS\authenticate(), SimpleSAML_IdP\finishLogoutRedirect(), sspmod_oauth_Consumer\getAuthorizeRequest(), SimpleSAML_XHTML_IdPDisco\handleRequest(), SimpleSAML_Auth_Default\initLogout(), SimpleSAML_Auth_Source\loginCompleted(), sspmod_cas_Auth_Source_CAS\logout(), SimpleSAML_Auth_Default\logoutCompleted(), SimpleSAML\Auth\Simple\logoutCompleted(), SimpleSAML\IdP\TraditionalLogoutHandler\logoutNextSP(), sspmod_consent_Logout\postLogout(), sspmod_exampleauth_Auth_Process_RedirectTest\process(), sspmod_core_Auth_Process_WarnShortSSOInterval\process(), sspmod_preprodwarning_Auth_Process_Warning\process(), sspmod_authX509_Auth_Process_ExpiryWarning\process(), sspmod_expirycheck_Auth_Process_ExpiryDate\process(), sspmod_consent_Auth_Process_Consent\process(), SimpleSAML_Utilities\redirectTrustedURL(), SimpleSAML_Auth_ProcessingChain\resumeProcessing(), sspmod_cdc_Server\send(), sspmod_adfs_IdP_ADFS\sendLogoutResponse(), SimpleSAML_XHTML_IdPDisco\start(), sspmod_saml_Auth_Source_SP\startDisco(), SimpleSAML\IdP\IFrameLogoutHandler\startLogout(), sspmod_saml_Auth_Source_SP\startSSO1(), SimpleSAML_Auth_State\throwException(), sspmod_saml_Auth_Process_ExpectedAuthnContextClassRef\unauthorized(), and sspmod_authorize_Auth_Process_Authorize\unauthorized().

963  {
964  if (!is_string($url) || !is_array($parameters)) {
965  throw new \InvalidArgumentException('Invalid input parameters.');
966  }
967 
968  $url = self::normalizeURL($url);
969  self::redirect($url, $parameters);
970  }
$url
+ Here is the caller graph for this function:

◆ redirectUntrustedURL()

static SimpleSAML\Utils\HTTP::redirectUntrustedURL (   $url,
  $parameters = array() 
)
static

This function redirects to the specified URL after performing the appropriate security checks on it.

Particularly, it will make sure that the provided URL is allowed by the 'redirect.trustedsites' directive in the configuration.

If the aforementioned option is not set or the URL does correspond to a trusted site, it performs a redirection to it. If the site is not trusted, an exception will be thrown.

Parameters
string$urlThe URL we should redirect to. This URL may include query parameters. If this URL is a relative URL (starting with '/'), then it will be turned into an absolute URL by prefixing it with the absolute URL to the root of the website.
string[]$parameters An array with extra query string parameters which should be appended to the URL. The name of the parameter is the array index. The value of the parameter is the value stored in the index. Both the name and the value will be urlencoded. If the value is NULL, then the parameter will be encoded as just the name, without a value.
Returns
void This function never returns.
Exceptions

Definition at line 994 of file HTTP.php.

Referenced by sspmod_saml_Auth_Source_SP\handleUnsolicitedAuth(), SimpleSAML_Auth_State\loadState(), and SimpleSAML_Utilities\redirectUntrustedURL().

995  {
996  if (!is_string($url) || !is_array($parameters)) {
997  throw new \InvalidArgumentException('Invalid input parameters.');
998  }
999 
1000  $url = self::checkURLAllowed($url);
1001  self::redirect($url, $parameters);
1002  }
$url
+ Here is the caller graph for this function:

◆ resolveURL()

static SimpleSAML\Utils\HTTP::resolveURL (   $url,
  $base = null 
)
static

Resolve a (possibly relative) URL relative to a given base URL.

This function supports these forms of relative URLs:

  • ^+: Absolute URL. E.g. "http://www.example.com:port/path?query#fragment".
  • ^// Same protocol. E.g. "//www.example.com:port/path?query#fragment"
  • ^/ Same protocol and host. E.g. "/path?query#fragment".
  • ^? Same protocol, host and path, replace query string & fragment. E.g. "?query#fragment".
  • ^# Same protocol, host, path and query, replace fragment. E.g. "#fragment".
  • The rest: Relative to the base path.
Parameters
string$urlThe relative URL.
string$baseThe base URL. Defaults to the base URL of this installation of SimpleSAMLphp.
Returns
string An absolute URL for the given relative URL.
Exceptions

Definition at line 1026 of file HTTP.php.

Referenced by showEntry().

1027  {
1028  if ($base === null) {
1029  $base = self::getBaseURL();
1030  }
1031 
1032  if (!is_string($url) || !is_string($base)) {
1033  throw new \InvalidArgumentException('Invalid input parameters.');
1034  }
1035 
1036  if (!preg_match('/^((((\w+:)\/\/[^\/]+)(\/[^?#]*))(?:\?[^#]*)?)(?:#.*)?/', $base, $baseParsed)) {
1037  throw new \InvalidArgumentException('Unable to parse base url: '.$base);
1038  }
1039 
1040  $baseDir = dirname($baseParsed[5].'filename');
1041  $baseScheme = $baseParsed[4];
1042  $baseHost = $baseParsed[3];
1043  $basePath = $baseParsed[2];
1044  $baseQuery = $baseParsed[1];
1045 
1046  if (preg_match('$^\w+:$', $url)) {
1047  return $url;
1048  }
1049 
1050  if (substr($url, 0, 2) === '//') {
1051  return $baseScheme.$url;
1052  }
1053 
1054  if ($url[0] === '/') {
1055  return $baseHost.$url;
1056  }
1057  if ($url[0] === '?') {
1058  return $basePath.$url;
1059  }
1060  if ($url[0] === '#') {
1061  return $baseQuery.$url;
1062  }
1063 
1064  // we have a relative path. Remove query string/fragment and save it as $tail
1065  $queryPos = strpos($url, '?');
1066  $fragmentPos = strpos($url, '#');
1067  if ($queryPos !== false || $fragmentPos !== false) {
1068  if ($queryPos === false) {
1069  $tailPos = $fragmentPos;
1070  } elseif ($fragmentPos === false) {
1071  $tailPos = $queryPos;
1072  } elseif ($queryPos < $fragmentPos) {
1073  $tailPos = $queryPos;
1074  } else {
1075  $tailPos = $fragmentPos;
1076  }
1077 
1078  $tail = substr($url, $tailPos);
1079  $dir = substr($url, 0, $tailPos);
1080  } else {
1081  $dir = $url;
1082  $tail = '';
1083  }
1084 
1085  $dir = System::resolvePath($dir, $baseDir);
1086 
1087  return $baseHost.$dir.$tail;
1088  }
$base
Definition: index.php:4
getBaseURL($t, $type='get', $key=null, $value=null)
Definition: showstats.php:133
static resolvePath($path, $base=null)
Resolve a (possibly) relative path from the given base path.
Definition: System.php:118
$url
+ Here is the caller graph for this function:

◆ savePOSTData()

static SimpleSAML\Utils\HTTP::savePOSTData ( \SimpleSAML_Session  $session,
  $destination,
  $data 
)
staticprivate

Save the given HTTP POST data and the destination where it should be posted to a given session.

Parameters
\SimpleSAML_Session$sessionThe session where to temporarily store the data.
string$destinationThe destination URL where the form should be posted.
array$dataAn associative array with the data to be posted to $destination.
Returns
string A random identifier that can be used to retrieve the data from the current session.
Author
Andjelko Horvat
Jaime Perez, UNINETT AS jaime.nosp@m..per.nosp@m.ez@un.nosp@m.inet.nosp@m.t.no

Definition at line 218 of file HTTP.php.

219  {
220  // generate a random ID to avoid replay attacks
222  $postData = array(
223  'post' => $data,
224  'url' => $destination,
225  );
226 
227  // save the post data to the session, tied to the random ID
228  $session->setData('core_postdatalink', $id, $postData);
229 
230  return $id;
231  }
static generateID()
Generate a random identifier, ID_LENGTH bytes long.
Definition: Random.php:26
$session
$destination
if(!array_key_exists('StateId', $_REQUEST)) $id
Create styles array
The data for the language used.
if($session===NULL) $postData

◆ setCookie()

static SimpleSAML\Utils\HTTP::setCookie (   $name,
  $value,
  $params = null,
  $throw = true 
)
static

Set a cookie.

Parameters
string$nameThe name of the cookie.
string | NULL$valueThe value of the cookie. Set to NULL to delete the cookie.
array | NULL$paramsCookie parameters.
bool$throwWhether to throw exception if setcookie() fails.
Exceptions

Definition at line 1107 of file HTTP.php.

Referenced by sspmod_consent_Consent_Store_Cookie\_setConsentCookie(), SimpleSAML_Session\doLogin(), SimpleSAML_AuthMemCookie\doLogout(), sspmod_cdc_Server\handleDelete(), sspmod_cdc_Server\setCDC(), SimpleSAML_XHTML_IdPDisco\setCookie(), SimpleSAML_Utilities\setCookie(), SimpleSAML\Locale\Language\setLanguageCookie(), sspmod_discopower_PowerIdPDisco\setPreviousIdP(), sspmod_multiauth_Auth_Source_MultiAuth\setPreviousSource(), and SimpleSAML_Session\updateSessionCookies().

1108  {
1109  if (!(is_string($name) && // $name must be a string
1110  (is_string($value) || is_null($value)) && // $value can be a string or null
1111  (is_array($params) || is_null($params)) && // $params can be an array or null
1112  is_bool($throw)) // $throw must be boolean
1113  ) {
1114  throw new \InvalidArgumentException('Invalid input parameters.');
1115  }
1116 
1117  $default_params = array(
1118  'lifetime' => 0,
1119  'expire' => null,
1120  'path' => '/',
1121  'domain' => null,
1122  'secure' => false,
1123  'httponly' => true,
1124  'raw' => false,
1125  );
1126 
1127  if ($params !== null) {
1128  $params = array_merge($default_params, $params);
1129  } else {
1130  $params = $default_params;
1131  }
1132 
1133  // Do not set secure cookie if not on HTTPS
1134  if ($params['secure'] && !self::isHTTPS()) {
1135  if ($throw) {
1136  throw new \SimpleSAML\Error\CannotSetCookie(
1137  'Setting secure cookie on plain HTTP is not allowed.',
1139  );
1140  }
1141  Logger::warning('Error setting cookie: setting secure cookie on plain HTTP is not allowed.');
1142  return;
1143  }
1144 
1145  if ($value === null) {
1146  $expire = time() - 365 * 24 * 60 * 60;
1147  } elseif (isset($params['expire'])) {
1148  $expire = $params['expire'];
1149  } elseif ($params['lifetime'] === 0) {
1150  $expire = 0;
1151  } else {
1152  $expire = time() + $params['lifetime'];
1153  }
1154 
1155  if ($params['raw']) {
1156  $success = @setrawcookie(
1157  $name,
1158  $value,
1159  $expire,
1160  $params['path'],
1161  $params['domain'],
1162  $params['secure'],
1163  $params['httponly']
1164  );
1165  } else {
1166  $success = @setcookie(
1167  $name,
1168  $value,
1169  $expire,
1170  $params['path'],
1171  $params['domain'],
1172  $params['secure'],
1173  $params['httponly']
1174  );
1175  }
1176 
1177  if (!$success) {
1178  if ($throw) {
1179  throw new \SimpleSAML\Error\CannotSetCookie(
1180  'Headers already sent.',
1182  );
1183  }
1184  Logger::warning('Error setting cookie: headers already sent.');
1185  }
1186  }
$params
Definition: disable.php:11
$expire
Definition: saml2-acs.php:140
Attribute-related utility methods.
if($format !==null) $name
Definition: metadata.php:146
$success
Definition: Utf8Test.php:86
static warning($string)
Definition: Logger.php:179
Create styles array
The data for the language used.
Add data(end) time
Method that wraps PHPs time in order to allow simulations with the workflow.
+ Here is the caller graph for this function:

◆ submitPOSTData()

static SimpleSAML\Utils\HTTP::submitPOSTData (   $destination,
  $data 
)
static

Submit a POST form to a specific destination.

This function never returns.

Parameters
string$destinationThe destination URL.
array$dataAn associative array with the data to be posted to $destination.
Exceptions

Definition at line 1205 of file HTTP.php.

Referenced by SimpleSAML_Utilities\postRedirect(), sspmod_cdc_Server\send(), and SimpleSAML\Bindings\Shib13\HTTPPost\sendResponse().

1206  {
1207  if (!is_string($destination) || !is_array($data)) {
1208  throw new \InvalidArgumentException('Invalid input parameters.');
1209  }
1210 
1212  $allowed = $config->getBoolean('enable.http_post', false);
1213 
1214  if ($allowed && preg_match("#^http:#", $destination) && self::isHTTPS()) {
1215  // we need to post the data to HTTP
1216  self::redirect(self::getSecurePOSTRedirectURL($destination, $data));
1217  }
1218 
1219  $p = new \SimpleSAML_XHTML_Template($config, 'post.php');
1220  $p->data['destination'] = $destination;
1221  $p->data['post'] = $data;
1222  $p->show();
1223  exit(0);
1224  }
$destination
static getInstance($instancename='simplesaml')
Get a configuration file by its instance name.
+ Here is the caller graph for this function:

The documentation for this class was generated from the following file: