PHP OpenID consumer
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

processor.php 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. <?PHP
  2. /* Poidsy 0.5 - 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__) . '/discoverer.inc.php');
  25. require_once(dirname(__FILE__) . '/poster.inc.php');
  26. require_once(dirname(__FILE__) . '/sreg.inc.php');
  27. require_once(dirname(__FILE__) . '/urlbuilder.inc.php');
  28. require_once(dirname(__FILE__) . '/keymanager.inc.php');
  29. if (session_id() == '') {
  30. // No session - testing maybe?
  31. session_start();
  32. }
  33. // Process any openid_url form fields (compatability with 0.1)
  34. if (!defined('OPENID_URL') && isset($_POST['openid_url'])) {
  35. define('OPENID_URL', $_POST['openid_url']);
  36. } else if (!defined('OPENID_URL') && isset($_POST['openid_identifier'])) {
  37. define('OPENID_URL', $_POST['openid_identifier']);
  38. }
  39. // Maximum number of requests to allow without a OPENID_THROTTLE_GAP second
  40. // gap between two of them
  41. if (!defined('OPENID_THROTTLE_NUM')) {
  42. define('OPENID_THROTTLE_NUM', 3);
  43. }
  44. // Time to require between requests before the request counter is reset
  45. if (!defined('OPENID_THROTTLE_GAP')) {
  46. define('OPENID_THROTTLE_GAP', 30);
  47. }
  48. // Whether or not to use the key manager
  49. define('KEYMANAGER', !defined('OPENID_NOKEYMANAGER') && KeyManager::isSupported());
  50. /**
  51. * Processes the current request.
  52. */
  53. function process() {
  54. if (defined('OPENID_URL')) {
  55. // Initial authentication attempt (they just entered their identifier)
  56. Logger::log('Processing authentication attempt for %s', OPENID_URL);
  57. $reqs = checkRequests();
  58. $disc = tryDiscovery(OPENID_URL);
  59. $_SESSION['openid'] = array(
  60. 'identity' => $disc->getIdentity(),
  61. 'delegate' => $disc->getDelegate(),
  62. 'version' => $disc->getVersion(),
  63. 'validated' => false,
  64. 'server' => $disc->getServer(),
  65. 'nonce' => uniqid(microtime(true), true),
  66. 'requests' => $reqs,
  67. );
  68. $handle = getHandle($disc->getServer());
  69. $url = URLBuilder::buildRequest(defined('OPENID_IMMEDIATE') ? 'immediate' : 'setup',
  70. $disc->getServer(), $disc->getDelegate(),
  71. $disc->getIdentity(), URLBuilder::getCurrentURL(), $handle, $disc->getVersion());
  72. URLBuilder::doRedirect($url);
  73. } else if (isset($_REQUEST['openid_mode'])) {
  74. checkNonce();
  75. $func = 'process' . str_replace(' ', '', ucwords(str_replace('_', ' ',
  76. strtolower($_REQUEST['openid_mode']))));
  77. if (function_exists($func)) {
  78. call_user_func($func, checkHandleRevocation());
  79. }
  80. }
  81. }
  82. /**
  83. * Retrieves or creates the 'requests' session array, which tracks the number
  84. * of authentication attempts the user has made recently.
  85. *
  86. * @return An array (by reference) containing details about recent requests
  87. */
  88. function &getRequests() {
  89. if (!isset($_SESSION['openid']['requests'])) {
  90. $_SESSION['openid']['requests'] = array('lasttime' => 0, 'count' => 0);
  91. }
  92. return $_SESSION['openid']['requests'];
  93. }
  94. /**
  95. * Checks that the user isn't making requests too frequently, and redirects
  96. * them with an appropriate error if they are.
  97. *
  98. * @return An array containing details about the requests that have been made
  99. */
  100. function &checkRequests() {
  101. $requests = getRequests();
  102. if ($requests['lasttime'] < time() - OPENID_THROTTLE_GAP) {
  103. // Last request was a while ago, reset the timer
  104. resetRequests();
  105. } else if ($requests['count'] > OPENID_THROTTLE_NUM) {
  106. Logger::log('Client throttled: %s requests made', $requests['count']);
  107. // More than the legal number of requests
  108. error('throttled', 'You are trying to authenticate too often');
  109. }
  110. $requests['count']++;
  111. $requests['lasttime'] = time();
  112. return $requests;
  113. }
  114. /**
  115. * Resets the recent requests counter (for example, after the required time
  116. * has ellapsed, or after the user has successfully logged in).
  117. *
  118. * @param $decrement If true, the count will be decremented instead of cleared
  119. * @return A copy of the requests array
  120. */
  121. function &resetRequests($decrement = false) {
  122. $requests = getRequests();
  123. if ($decrement) {
  124. $requests['count'] = max($requests['count'] - 1, 0);
  125. } else {
  126. $requests['count'] = 0;
  127. }
  128. return $requests;
  129. }
  130. /**
  131. * Attempts to perform discovery on the specified URL, redirecting the user
  132. * with an appropriate error if discovery fails.
  133. *
  134. * @param String $url The URL to perform discovery on
  135. * @return An appropriate Discoverer object
  136. */
  137. function tryDiscovery($url) {
  138. try {
  139. $disc = new Discoverer($url);
  140. if ($disc->getServer() == null) {
  141. Logger::log('Couldn\'t perform discovery on %s', $url);
  142. error('notvalid', 'Claimed identity is not a valid identifier');
  143. }
  144. return $disc;
  145. } catch (Exception $e) {
  146. Logger::log('Error during discovery on %s: %s', $url, $e->getMessage());
  147. error('discovery', $e->getMessage());
  148. }
  149. return null;
  150. }
  151. /**
  152. * Retrieves an association handle for the specified server. If we don't
  153. * currently have one, attempts to associate with the server.
  154. *
  155. * @param String $server The server whose handle we're retrieving
  156. * @return The association handle of the server or null on failure
  157. */
  158. function getHandle($server) {
  159. if (KEYMANAGER) {
  160. if (!KeyManager::hasHandle($server)) {
  161. KeyManager::associate($server);
  162. }
  163. return KeyManager::getHandle($server);
  164. } else {
  165. return null;
  166. }
  167. }
  168. /**
  169. * Checks that the nonce specified in the current request equals the one
  170. * stored in the user's session, and redirects them if it doesn't.
  171. */
  172. function checkNonce() {
  173. if ($_REQUEST['openid_nonce'] != $_SESSION['openid']['nonce']) {
  174. error('nonce', 'Nonce doesn\'t match - possible replay attack');
  175. } else {
  176. $_SESSION['openid']['nonce'] = uniqid(microtime(true), true);
  177. }
  178. }
  179. /**
  180. * Checks to see if the request contains an instruction to invalidate the
  181. * handle we used. If it does, the request is authenticated and the handle
  182. * removed (or the user is redirected with an error if the IdP doesn't
  183. * authenticate the message).
  184. *
  185. * @return True if the message has been authenticated, false otherwise
  186. */
  187. function checkHandleRevocation() {
  188. $valid = false;
  189. if (KEYMANAGER && isset($_REQUEST['openid_invalidate_handle'])) {
  190. $valid = KeyManager::dumbAuth();
  191. if ($valid) {
  192. KeyManager::removeKey($_SESSION['openid']['server'], $_REQUEST['openid_invalidate_handle']);
  193. } else {
  194. error('noauth', 'Provider didn\'t authenticate message');
  195. }
  196. }
  197. return $valid;
  198. }
  199. /**
  200. * Processes id_res requests.
  201. *
  202. * @param Boolean $valid True if the request has already been authenticated
  203. */
  204. function processIdRes($valid) {
  205. if (isset($_REQUEST['openid_identity'])) {
  206. processPositiveResponse($valid);
  207. } else if (isset($_REQUEST['openid_user_setup_url'])) {
  208. processSetupRequest();
  209. }
  210. }
  211. /**
  212. * Processes a response where the provider is requesting to interact with the
  213. * user in order to confirm their identity.
  214. */
  215. function processSetupRequest() {
  216. if (defined('OPENID_IMMEDIATE') && OPENID_IMMEDIATE) {
  217. error('noimmediate', 'Couldn\'t perform immediate auth');
  218. }
  219. $handle = getHandle($_SESSION['openid']['server']);
  220. $url = URLBuilder::buildRequest('setup', $_REQUEST['openid_user_setup_url'],
  221. $_SESSION['openid']['delegate'],
  222. $_SESSION['openid']['identity'],
  223. URLBuilder::getCurrentURL(), $handle);
  224. URLBuilder::doRedirect($url);
  225. }
  226. /**
  227. * Processes a positive authentication response.
  228. *
  229. * @param Boolean $valid True if the request has already been authenticated
  230. */
  231. function processPositiveResponse($valid) {
  232. Logger::log('Positive response: identity = %s, expected = %s', $_REQUEST['openid_identity'], $_SESSION['openid']['identity']);
  233. if ($_REQUEST['openid_identity'] != $_SESSION['openid']['identity']) {
  234. if ($_SESSION['openid']['identity'] == 'http://specs.openid.net/auth/2.0/identifier_select') {
  235. $disc = new Discoverer($_REQUEST['openid_claimed_id'], false);
  236. if ($disc->hasServer($_SESSION['openid']['server'])) {
  237. $_SESSION['openid']['identity'] = $_REQUEST['openid_identity'];
  238. $_SESSION['openid']['delegate'] = $_REQUEST['openid_claimed_id'];
  239. resetRequests(true);
  240. } else {
  241. error('diffid', 'The OP at ' . $_SESSION['openid']['server'] . ' is attmpting to claim ' . $_REQUEST['openid_claimed_id'] . ' but ' . ($disc->getServer() == null ? 'that isn\'t a valid identifier' : 'that identifier only authorises ' . $disc->getServer()));
  242. }
  243. } else {
  244. error('diffid', 'Identity provider validated wrong identity. Expected it to '
  245. . 'validate ' . $_SESSION['openid']['delegate'] . ' but it '
  246. . 'validated ' . $_REQUEST['openid_identity']);
  247. }
  248. }
  249. if (!$valid) {
  250. $dumbauth = true;
  251. if (KEYMANAGER) {
  252. try {
  253. $valid = KeyManager::authenticate($_SESSION['openid']['server'], $_REQUEST);
  254. $dumbauth = false;
  255. } catch (Exception $ex) {
  256. // Ignore it - try dumb auth
  257. }
  258. }
  259. if ($dumbauth) {
  260. $valid = KeyManager::dumbAuthenticate();
  261. }
  262. }
  263. $_SESSION['openid']['validated'] = $valid;
  264. if (!$valid) {
  265. error('noauth', 'Provider didn\'t authenticate response');
  266. }
  267. parseSRegResponse();
  268. URLBuilder::redirect();
  269. }
  270. /**
  271. * Processes cancel modes.
  272. *
  273. * @param Boolean $valid True if the request has already been authenticated
  274. */
  275. function processCancel($valid) {
  276. error('cancelled', 'Provider cancelled the authentication attempt');
  277. }
  278. /**
  279. * Processes error modes.
  280. *
  281. * @param Boolean $valid True if the request has already been authenticated
  282. */
  283. function processError($valid) {
  284. error('perror', 'Provider error: ' . $_REQUEST['openid_error']);
  285. }
  286. /**
  287. * Populates the session array with the details of the specified error and
  288. * redirects the user appropriately.
  289. *
  290. * @param String $code The error code that occured
  291. * @param String $message A description of the error
  292. */
  293. function error($code, $message) {
  294. $_SESSION['openid']['error'] = $message;
  295. $_SESSION['openid']['errorcode'] = $code;
  296. URLBuilder::redirect();
  297. }
  298. // Here we go!
  299. process();
  300. ?>