PHP OpenID consumer
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

urlbuilder.inc.php 7.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. <?PHP
  2. /* Poidsy 0.6 - http://chris.smith.name/projects/poidsy
  3. * Copyright (c) 2008-2010 Chris Smith
  4. *
  5. * Permission is hereby granted, free of charge, to any person obtaining a copy
  6. * of this software and associated documentation files (the "Software"), to deal
  7. * in the Software without restriction, including without limitation the rights
  8. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. * copies of the Software, and to permit persons to whom the Software is
  10. * furnished to do so, subject to the following conditions:
  11. *
  12. * The above copyright notice and this permission notice shall be included in
  13. * all copies or substantial portions of the Software.
  14. *
  15. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  21. * SOFTWARE.
  22. */
  23. require_once(dirname(__FILE__) . '/logging.inc.php');
  24. require_once(dirname(__FILE__) . '/keymanager.inc.php');
  25. class URLBuilder {
  26. const MIN_VERSION_FOR_NS = 2;
  27. private static $namespace = array(
  28. 1 => 'http://openid.net/signon/1.1',
  29. 2 => 'http://specs.openid.net/auth/2.0'
  30. );
  31. public static function addArguments($base, $arguments) {
  32. $first = true;
  33. $res = $base === false ? '' : $base;
  34. if ($base !== false && strrpos($base, '?', -2) === false) {
  35. if ($base[strlen($base) - 1] != '?') {
  36. $res .= '?';
  37. }
  38. } else if ($base !== false) {
  39. $res .= '&';
  40. }
  41. foreach ($arguments as $key => $value) {
  42. if ($first) {
  43. $first = false;
  44. } else {
  45. $res .= '&';
  46. }
  47. $res .= urlencode($key) . '=' . urlencode($value);
  48. }
  49. return $res;
  50. }
  51. public static function buildRequest($type, $base, $delegate, $identity, $returnURL, $handle, $version = 1) {
  52. $args = array(
  53. 'openid.mode' => 'checkid_' . $type,
  54. 'openid.identity' => $delegate,
  55. 'openid.claimed_id' => $identity,
  56. ($version == 1 ? 'openid.trust_root' : 'openid.realm') => self::getTrustRoot($returnURL),
  57. 'openid.return_to' => self::addArguments($returnURL,
  58. array('openid.nonce' => $_SESSION['openid']['nonce']))
  59. );
  60. if ($version >= self::MIN_VERSION_FOR_NS) {
  61. $args['openid.ns'] = self::$namespace[$version];
  62. }
  63. if ($handle !== null) {
  64. $args['openid.assoc_handle'] = $handle;
  65. }
  66. self::decorateArgs($args);
  67. return self::addArguments($base, $args);
  68. }
  69. public static function getTrustRoot($base = null, $curl = null) {
  70. $curr = $curl == null ? self::getCurrentURL() : $curl;
  71. if (defined('OPENID_TRUSTROOT')) {
  72. $root = OPENID_TRUSTROOT;
  73. } else {
  74. $root = $base == null ? $curr : $base;
  75. }
  76. // Note that this may end up going back to 'http:/' if
  77. // the domains don't match.
  78. while (substr($curr, 0, strlen($root)) != $root) {
  79. $root = dirname($root) . '/';
  80. }
  81. return $root;
  82. }
  83. private static function decorateArgs(&$args) {
  84. global $_POIDSY;
  85. if (empty($_POIDSY['decorators'])) { return; }
  86. $id = 1;
  87. foreach ($_POIDSY['decorators'] as $decorator) {
  88. $decorator->decorate($args, 'ext' . ($id++));
  89. }
  90. }
  91. public static function buildAssociate($server, $version = 1, $assocType = null, $sessionType = null) {
  92. if ($assocType == null) { $assocType = 'HMAC-SHA1'; }
  93. if ($sessionType == null) { $sessionType = 'DH-SHA1'; }
  94. $args = array(
  95. 'openid.mode' => 'associate',
  96. 'openid.assoc_type' => $assocType,
  97. );
  98. if ($version >= self::MIN_VERSION_FOR_NS) {
  99. $args['openid.ns'] = self::$namespace[$version];
  100. }
  101. if (KeyManager::supportsDH()) {
  102. $args['openid.session_type'] = $sessionType;
  103. $args['openid.dh_modulus'] = KeyManager::getDhModulus();
  104. $args['openid.dh_gen'] = KeyManager::getDhGen();
  105. $args['openid.dh_consumer_public'] = KeyManager::getDhPublicKey($server);
  106. } else {
  107. $args['openid.session_type'] = '';
  108. }
  109. return self::addArguments(false, $args);
  110. }
  111. public static function buildAuth($params, $version = 1) {
  112. $args = array(
  113. 'openid.mode' => 'check_authentication'
  114. );
  115. if ($version >= self::MIN_VERSION_FOR_NS) {
  116. $args['openid.ns'] = self::$namespace[$version];
  117. }
  118. $toadd = array('assoc_handle', 'sig', 'signed');
  119. $toadd = array_merge($toadd, explode(',', $params['openid_signed']));
  120. foreach ($toadd as $arg) {
  121. if (!isset($args['openid.' . $arg])) {
  122. $args['openid.' . $arg] = $params['openid_' . str_replace('.', '_', $arg)];
  123. }
  124. }
  125. return self::addArguments(false, $args);
  126. }
  127. public static function isValidReturnToURL($url) {
  128. // 11.1: The URL scheme, authority, and path MUST be the same between the two URLs.
  129. // Any query parameters that are present in the "openid.return_to" URL MUST
  130. // also be present with the same values in the URL of the HTTP request the
  131. // RP received.
  132. return self::isSameURL(self::getCurrentURL(true), $url);
  133. }
  134. public static function isSameURL($url1, $url2) {
  135. $actual = parse_url($url1);
  136. $return = parse_url($url2);
  137. foreach (array('scheme', 'host', 'port', 'user', 'pass', 'path') as $part) {
  138. if ($part == 'port') {
  139. if (!isset($actual['port'])) { $actual['port'] = $actual['scheme'] == 'https' ? 443 : 80; }
  140. if (!isset($return['port'])) { $return['port'] = $return['scheme'] == 'https' ? 443 : 80; }
  141. }
  142. if (isset($actual[$part]) ^ isset($return[$part])) {
  143. // Present in one but not the other
  144. return false;
  145. } else if (isset($actual[$part]) && $actual[$part] != $return[$part]) {
  146. // Present in both but different
  147. return false;
  148. }
  149. }
  150. parse_str($actual['query'], $actualVars);
  151. parse_str($return['query'], $returnVars);
  152. foreach ($returnVars as $key => $value) {
  153. if (!isset($actualVars[$key]) || $actualVars[$key] != $value) {
  154. return false;
  155. }
  156. }
  157. return true;
  158. }
  159. public static function getCurrentURL($raw = false) {
  160. $https = false;
  161. $res = 'http';
  162. if (isset($_SERVER['HTTPS']) && !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') {
  163. $https = true;
  164. $res .= 's';
  165. }
  166. $res .= '://' . $_SERVER['SERVER_NAME'];
  167. if ($_SERVER['SERVER_PORT'] != ($https ? 443 : 80)) {
  168. $res .= ':' . $_SERVER['SERVER_PORT'];
  169. }
  170. $url = $_SERVER['REQUEST_URI'];
  171. if (!$raw) {
  172. while (preg_match('/([\?&])openid[\._](.*?)=(.*?)(&|$)/', $url, $m)) {
  173. $url = str_replace($m[0], $m[1], $url);
  174. }
  175. }
  176. $url = preg_replace('/\??&*$/', '', $url);
  177. return $res . $url;
  178. }
  179. /**
  180. * Redirects the user back to their original page.
  181. */
  182. public static function redirect() {
  183. if (defined('OPENID_REDIRECTURL')) {
  184. $url = OPENID_REDIRECTURL;
  185. } else if (isset($_SESSION['openid']['redirect'])) {
  186. $url = $_SESSION['openid']['redirect'];
  187. } else {
  188. $url = self::getCurrentURL();
  189. }
  190. self::doRedirect($url);
  191. }
  192. /**
  193. * Redirects the user to the specified URL.
  194. *
  195. * @param $url The URL to redirect the user to
  196. */
  197. public static function doRedirect($url) {
  198. Logger::log('Redirecting to %s', $url);
  199. header('Location: ' . $url);
  200. echo '<html><head><title>Redirecting</title></head><body>';
  201. echo '<p>Redirecting to <a href="', htmlentities($url), '">';
  202. echo htmlentities($url), '</a></p></body></html>';
  203. exit();
  204. }
  205. }
  206. ?>