[ Index ]

PHP Cross Reference of Joomla 1.5.26 DE

title

Body

[close]

/libraries/openid/Auth/OpenID/ -> TrustRoot.php (source)

   1  <?php
   2  /**
   3   * Functions for dealing with OpenID trust roots
   4   *
   5   * PHP versions 4 and 5
   6   *
   7   * LICENSE: See the COPYING file included in this distribution.
   8   *
   9   * @package OpenID
  10   * @author JanRain, Inc. <openid@janrain.com>
  11   * @copyright 2005-2008 Janrain, Inc.
  12   * @license http://www.apache.org/licenses/LICENSE-2.0 Apache
  13   */
  14  
  15  // Do not allow direct access
  16  defined( '_JEXEC' ) or die( 'Restricted access' );
  17  
  18  require_once 'Auth/OpenID/Discover.php';
  19  
  20  /**
  21   * A regular expression that matches a domain ending in a top-level domains.
  22   * Used in checking trust roots for sanity.
  23   *
  24   * @access private
  25   */
  26  define('Auth_OpenID___TLDs',
  27         '/\.(ac|ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|asia' .
  28         '|at|au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br' .
  29         '|bs|bt|bv|bw|by|bz|ca|cat|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co' .
  30         '|com|coop|cr|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg' .
  31         '|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl' .
  32         '|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie' .
  33         '|il|im|in|info|int|io|iq|ir|is|it|je|jm|jo|jobs|jp|ke|kg|kh' .
  34         '|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly' .
  35         '|ma|mc|md|me|mg|mh|mil|mk|ml|mm|mn|mo|mobi|mp|mq|mr|ms|mt' .
  36         '|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no' .
  37         '|np|nr|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt' .
  38         '|pw|py|qa|re|ro|rs|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl' .
  39         '|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tel|tf|tg|th|tj|tk|tl|tm' .
  40         '|tn|to|tp|tr|travel|tt|tv|tw|tz|ua|ug|uk|us|uy|uz|va|vc|ve' .
  41         '|vg|vi|vn|vu|wf|ws|xn--0zwm56d|xn--11b5bs3a9aj6g' .
  42         '|xn--80akhbyknj4f|xn--9t4b11yi5a|xn--deba0ad|xn--g6w251d' .
  43         '|xn--hgbk6aj7f53bba|xn--hlcj6aya9esc7a|xn--jxalpdlp' .
  44         '|xn--kgbechtv|xn--zckzah|ye|yt|yu|za|zm|zw)\.?$/');
  45  
  46  define('Auth_OpenID___HostSegmentRe',
  47         "/^(?:[-a-zA-Z0-9!$&'\\(\\)\\*+,;=._~]|%[a-zA-Z0-9]{2})*$/");
  48  
  49  /**
  50   * A wrapper for trust-root related functions
  51   */
  52  class Auth_OpenID_TrustRoot {
  53      /*
  54       * Return a discovery URL for this realm.
  55       *
  56       * Return null if the realm could not be parsed or was not valid.
  57       *
  58       * @param return_to The relying party return URL of the OpenID
  59       * authentication request
  60       *
  61       * @return The URL upon which relying party discovery should be
  62       * run in order to verify the return_to URL
  63       */
  64      function buildDiscoveryURL($realm)
  65      {
  66          $parsed = Auth_OpenID_TrustRoot::_parse($realm);
  67  
  68          if ($parsed === false) {
  69              return false;
  70          }
  71  
  72          if ($parsed['wildcard']) {
  73              // Use "www." in place of the star
  74              if ($parsed['host'][0] != '.') {
  75                  return false;
  76              }
  77  
  78              $www_domain = 'www' . $parsed['host'];
  79  
  80              return sprintf('%s://%s%s', $parsed['scheme'],
  81                             $www_domain, $parsed['path']);
  82          } else {
  83              return $parsed['unparsed'];
  84          }
  85      }
  86  
  87      /**
  88       * Parse a URL into its trust_root parts.
  89       *
  90       * @static
  91       *
  92       * @access private
  93       *
  94       * @param string $trust_root The url to parse
  95       *
  96       * @return mixed $parsed Either an associative array of trust root
  97       * parts or false if parsing failed.
  98       */
  99      function _parse($trust_root)
 100      {
 101          $trust_root = Auth_OpenID_urinorm($trust_root);
 102          if ($trust_root === null) {
 103              return false;
 104          }
 105  
 106          if (preg_match("/:\/\/[^:]+(:\d+){2,}(\/|$)/", $trust_root)) {
 107              return false;
 108          }
 109  
 110          $parts = @parse_url($trust_root);
 111          if ($parts === false) {
 112              return false;
 113          }
 114  
 115          $required_parts = array('scheme', 'host');
 116          $forbidden_parts = array('user', 'pass', 'fragment');
 117          $keys = array_keys($parts);
 118          if (array_intersect($keys, $required_parts) != $required_parts) {
 119              return false;
 120          }
 121  
 122          if (array_intersect($keys, $forbidden_parts) != array()) {
 123              return false;
 124          }
 125  
 126          if (!preg_match(Auth_OpenID___HostSegmentRe, $parts['host'])) {
 127              return false;
 128          }
 129  
 130          $scheme = strtolower($parts['scheme']);
 131          $allowed_schemes = array('http', 'https');
 132          if (!in_array($scheme, $allowed_schemes)) {
 133              return false;
 134          }
 135          $parts['scheme'] = $scheme;
 136  
 137          $host = strtolower($parts['host']);
 138          $hostparts = explode('*', $host);
 139          switch (count($hostparts)) {
 140          case 1:
 141              $parts['wildcard'] = false;
 142              break;
 143          case 2:
 144              if ($hostparts[0] ||
 145                  ($hostparts[1] && substr($hostparts[1], 0, 1) != '.')) {
 146                  return false;
 147              }
 148              $host = $hostparts[1];
 149              $parts['wildcard'] = true;
 150              break;
 151          default:
 152              return false;
 153          }
 154          if (strpos($host, ':') !== false) {
 155              return false;
 156          }
 157  
 158          $parts['host'] = $host;
 159  
 160          if (isset($parts['path'])) {
 161              $path = strtolower($parts['path']);
 162              if (substr($path, 0, 1) != '/') {
 163                  return false;
 164              }
 165          } else {
 166              $path = '/';
 167          }
 168  
 169          $parts['path'] = $path;
 170          if (!isset($parts['port'])) {
 171              $parts['port'] = false;
 172          }
 173  
 174  
 175          $parts['unparsed'] = $trust_root;
 176  
 177          return $parts;
 178      }
 179  
 180      /**
 181       * Is this trust root sane?
 182       *
 183       * A trust root is sane if it is syntactically valid and it has a
 184       * reasonable domain name. Specifically, the domain name must be
 185       * more than one level below a standard TLD or more than two
 186       * levels below a two-letter tld.
 187       *
 188       * For example, '*.com' is not a sane trust root, but '*.foo.com'
 189       * is.  '*.co.uk' is not sane, but '*.bbc.co.uk' is.
 190       *
 191       * This check is not always correct, but it attempts to err on the
 192       * side of marking sane trust roots insane instead of marking
 193       * insane trust roots sane. For example, 'kink.fm' is marked as
 194       * insane even though it "should" (for some meaning of should) be
 195       * marked sane.
 196       *
 197       * This function should be used when creating OpenID servers to
 198       * alert the users of the server when a consumer attempts to get
 199       * the user to accept a suspicious trust root.
 200       *
 201       * @static
 202       * @param string $trust_root The trust root to check
 203       * @return bool $sanity Whether the trust root looks OK
 204       */
 205      function isSane($trust_root)
 206      {
 207          $parts = Auth_OpenID_TrustRoot::_parse($trust_root);
 208          if ($parts === false) {
 209              return false;
 210          }
 211  
 212          // Localhost is a special case
 213          if ($parts['host'] == 'localhost') {
 214              return true;
 215          }
 216          
 217          $host_parts = explode('.', $parts['host']);
 218          if ($parts['wildcard']) {
 219              // Remove the empty string from the beginning of the array
 220              array_shift($host_parts);
 221          }
 222  
 223          if ($host_parts && !$host_parts[count($host_parts) - 1]) {
 224              array_pop($host_parts);
 225          }
 226  
 227          if (!$host_parts) {
 228              return false;
 229          }
 230  
 231          // Don't allow adjacent dots
 232          if (in_array('', $host_parts, true)) {
 233              return false;
 234          }
 235  
 236          // Get the top-level domain of the host. If it is not a valid TLD,
 237          // it's not sane.
 238          preg_match(Auth_OpenID___TLDs, $parts['host'], $matches);
 239          if (!$matches) {
 240              return false;
 241          }
 242          $tld = $matches[1];
 243  
 244          if (count($host_parts) == 1) {
 245              return false;
 246          }
 247  
 248          if ($parts['wildcard']) {
 249              // It's a 2-letter tld with a short second to last segment
 250              // so there needs to be more than two segments specified
 251              // (e.g. *.co.uk is insane)
 252              $second_level = $host_parts[count($host_parts) - 2];
 253              if (strlen($tld) == 2 && strlen($second_level) <= 3) {
 254                  return count($host_parts) > 2;
 255              }
 256          }
 257  
 258          return true;
 259      }
 260  
 261      /**
 262       * Does this URL match the given trust root?
 263       *
 264       * Return whether the URL falls under the given trust root. This
 265       * does not check whether the trust root is sane. If the URL or
 266       * trust root do not parse, this function will return false.
 267       *
 268       * @param string $trust_root The trust root to match against
 269       *
 270       * @param string $url The URL to check
 271       *
 272       * @return bool $matches Whether the URL matches against the
 273       * trust root
 274       */
 275      function match($trust_root, $url)
 276      {
 277          $trust_root_parsed = Auth_OpenID_TrustRoot::_parse($trust_root);
 278          $url_parsed = Auth_OpenID_TrustRoot::_parse($url);
 279          if (!$trust_root_parsed || !$url_parsed) {
 280              return false;
 281          }
 282  
 283          // Check hosts matching
 284          if ($url_parsed['wildcard']) {
 285              return false;
 286          }
 287          if ($trust_root_parsed['wildcard']) {
 288              $host_tail = $trust_root_parsed['host'];
 289              $host = $url_parsed['host'];
 290              if ($host_tail &&
 291                  substr($host, -(strlen($host_tail))) != $host_tail &&
 292                  substr($host_tail, 1) != $host) {
 293                  return false;
 294              }
 295          } else {
 296              if ($trust_root_parsed['host'] != $url_parsed['host']) {
 297                  return false;
 298              }
 299          }
 300  
 301          // Check path and query matching
 302          $base_path = $trust_root_parsed['path'];
 303          $path = $url_parsed['path'];
 304          if (!isset($trust_root_parsed['query'])) {
 305              if ($base_path != $path) {
 306                  if (substr($path, 0, strlen($base_path)) != $base_path) {
 307                      return false;
 308                  }
 309                  if (substr($base_path, strlen($base_path) - 1, 1) != '/' &&
 310                      substr($path, strlen($base_path), 1) != '/') {
 311                      return false;
 312                  }
 313              }
 314          } else {
 315              $base_query = $trust_root_parsed['query'];
 316              $query = @$url_parsed['query'];
 317              $qplus = substr($query, 0, strlen($base_query) + 1);
 318              $bqplus = $base_query . '&';
 319              if ($base_path != $path ||
 320                  ($base_query != $query && $qplus != $bqplus)) {
 321                  return false;
 322              }
 323          }
 324  
 325          // The port and scheme need to match exactly
 326          return ($trust_root_parsed['scheme'] == $url_parsed['scheme'] &&
 327                  $url_parsed['port'] === $trust_root_parsed['port']);
 328      }
 329  }
 330  
 331  /*
 332   * If the endpoint is a relying party OpenID return_to endpoint,
 333   * return the endpoint URL. Otherwise, return None.
 334   *
 335   * This function is intended to be used as a filter for the Yadis
 336   * filtering interface.
 337   *
 338   * @see: C{L{openid.yadis.services}}
 339   * @see: C{L{openid.yadis.filters}}
 340   *
 341   * @param endpoint: An XRDS BasicServiceEndpoint, as returned by
 342   * performing Yadis dicovery.
 343   *
 344   * @returns: The endpoint URL or None if the endpoint is not a
 345   * relying party endpoint.
 346   */
 347  function filter_extractReturnURL(&$endpoint)
 348  {
 349      if ($endpoint->matchTypes(array(Auth_OpenID_RP_RETURN_TO_URL_TYPE))) {
 350          return $endpoint;
 351      } else {
 352          return null;
 353      }
 354  }
 355  
 356  function &Auth_OpenID_extractReturnURL(&$endpoint_list)
 357  {
 358      $result = array();
 359  
 360      foreach ($endpoint_list as $endpoint) {
 361          if (filter_extractReturnURL($endpoint)) {
 362              $result[] = $endpoint;
 363          }
 364      }
 365  
 366      return $result;
 367  }
 368  
 369  /*
 370   * Is the return_to URL under one of the supplied allowed return_to
 371   * URLs?
 372   */
 373  function Auth_OpenID_returnToMatches($allowed_return_to_urls, $return_to)
 374  {
 375      foreach ($allowed_return_to_urls as $allowed_return_to) {
 376          // A return_to pattern works the same as a realm, except that
 377          // it's not allowed to use a wildcard. We'll model this by
 378          // parsing it as a realm, and not trying to match it if it has
 379          // a wildcard.
 380  
 381          $return_realm = Auth_OpenID_TrustRoot::_parse($allowed_return_to);
 382          if (// Parses as a trust root
 383              ($return_realm !== false) &&
 384              // Does not have a wildcard
 385              (!$return_realm['wildcard']) &&
 386              // Matches the return_to that we passed in with it
 387              (Auth_OpenID_TrustRoot::match($allowed_return_to, $return_to))) {
 388              return true;
 389          }
 390      }
 391  
 392      // No URL in the list matched
 393      return false;
 394  }
 395  
 396  /*
 397   * Given a relying party discovery URL return a list of return_to
 398   * URLs.
 399   */
 400  function Auth_OpenID_getAllowedReturnURLs($relying_party_url, &$fetcher,
 401                $discover_function=null)
 402  {
 403      if ($discover_function === null) {
 404          $discover_function = array('Auth_Yadis_Yadis', 'discover');
 405      }
 406  
 407      $xrds_parse_cb = array('Auth_OpenID_ServiceEndpoint', 'fromXRDS');
 408  
 409      list($rp_url_after_redirects, $endpoints) =
 410          Auth_Yadis_getServiceEndpoints($relying_party_url, $xrds_parse_cb,
 411                                         $discover_function, $fetcher);
 412  
 413      if ($rp_url_after_redirects != $relying_party_url) {
 414          // Verification caused a redirect
 415          return false;
 416      }
 417  
 418      call_user_func_array($discover_function,
 419                           array($relying_party_url, $fetcher));
 420  
 421      $return_to_urls = array();
 422      $matching_endpoints = Auth_OpenID_extractReturnURL($endpoints);
 423  
 424      foreach ($matching_endpoints as $e) {
 425          $return_to_urls[] = $e->server_url;
 426      }
 427  
 428      return $return_to_urls;
 429  }
 430  
 431  /*
 432   * Verify that a return_to URL is valid for the given realm.
 433   *
 434   * This function builds a discovery URL, performs Yadis discovery on
 435   * it, makes sure that the URL does not redirect, parses out the
 436   * return_to URLs, and finally checks to see if the current return_to
 437   * URL matches the return_to.
 438   *
 439   * @return true if the return_to URL is valid for the realm
 440   */
 441  function Auth_OpenID_verifyReturnTo($realm_str, $return_to, &$fetcher,
 442                $_vrfy='Auth_OpenID_getAllowedReturnURLs')
 443  {
 444      $disco_url = Auth_OpenID_TrustRoot::buildDiscoveryURL($realm_str);
 445  
 446      if ($disco_url === false) {
 447          return false;
 448      }
 449  
 450      $allowable_urls = call_user_func_array($_vrfy,
 451                             array($disco_url, &$fetcher));
 452  
 453      // The realm_str could not be parsed.
 454      if ($allowable_urls === false) {
 455          return false;
 456      }
 457  
 458      if (Auth_OpenID_returnToMatches($allowable_urls, $return_to)) {
 459          return true;
 460      } else {
 461          return false;
 462      }
 463  }
 464  
 465  ?>


Generated: Wed Mar 28 15:54:07 2012 Cross-referenced by PHPXref 0.7.1