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.

processor.php 12KB

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