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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  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. return $disc;
  146. } catch (Exception $e) {
  147. Logger::log('Error during discovery on %s: %s', $url, $e->getMessage());
  148. error('discovery', $e->getMessage());
  149. }
  150. return null;
  151. }
  152. /**
  153. * Retrieves an association handle for the specified server. If we don't
  154. * currently have one, attempts to associate with the server.
  155. *
  156. * @param String $server The server whose handle we're retrieving
  157. * @return The association handle of the server or null on failure
  158. */
  159. function getHandle($server) {
  160. if (KEYMANAGER) {
  161. if (!KeyManager::hasHandle($server)) {
  162. KeyManager::associate($server);
  163. }
  164. return KeyManager::getHandle($server);
  165. } else {
  166. return null;
  167. }
  168. }
  169. /**
  170. * Checks that the nonce specified in the current request equals the one
  171. * stored in the user's session, and redirects them if it doesn't.
  172. */
  173. function checkNonce() {
  174. if ($_REQUEST['openid_nonce'] != $_SESSION['openid']['nonce']) {
  175. error('nonce', 'Nonce doesn\'t match - possible replay attack');
  176. } else {
  177. $_SESSION['openid']['nonce'] = uniqid(microtime(true), true);
  178. }
  179. }
  180. /**
  181. * Checks to see if the request contains an instruction to invalidate the
  182. * handle we used. If it does, the request is authenticated and the handle
  183. * removed (or the user is redirected with an error if the IdP doesn't
  184. * authenticate the message).
  185. *
  186. * @return True if the message has been authenticated, false otherwise
  187. */
  188. function checkHandleRevocation() {
  189. $valid = false;
  190. if (KEYMANAGER && isset($_REQUEST['openid_invalidate_handle'])) {
  191. Logger::log('Request to invalidate handle received');
  192. $valid = KeyManager::dumbAuth();
  193. if ($valid) {
  194. KeyManager::removeKey($_SESSION['openid']['endpointUrl'], $_REQUEST['openid_invalidate_handle']);
  195. } else {
  196. error('noauth', 'Provider didn\'t authenticate message');
  197. }
  198. }
  199. return $valid;
  200. }
  201. /**
  202. * Processes id_res requests.
  203. *
  204. * @param Boolean $valid True if the request has already been authenticated
  205. */
  206. function processIdRes($valid) {
  207. if (isset($_REQUEST['openid_identity'])) {
  208. processPositiveResponse($valid);
  209. } else if (isset($_REQUEST['openid_user_setup_url'])) {
  210. processSetupRequest();
  211. }
  212. }
  213. /**
  214. * Processes a response where the provider is requesting to interact with the
  215. * user in order to confirm their identity.
  216. */
  217. function processSetupRequest() {
  218. if (defined('OPENID_IMMEDIATE') && OPENID_IMMEDIATE) {
  219. error('noimmediate', 'Couldn\'t perform immediate auth');
  220. }
  221. $handle = getHandle($_SESSION['openid']['endpointUrl']);
  222. $url = URLBuilder::buildRequest('setup', $_REQUEST['openid_user_setup_url'],
  223. $_SESSION['openid']['opLocalId'],
  224. $_SESSION['openid']['claimedId'],
  225. URLBuilder::getCurrentURL(), $handle);
  226. URLBuilder::doRedirect($url);
  227. }
  228. /**
  229. * Processes a positive authentication response.
  230. *
  231. * @param Boolean $valid True if the request has already been authenticated
  232. */
  233. function processPositiveResponse($valid) {
  234. Logger::log('Positive response: identity = %s, expected = %s', $_REQUEST['openid_identity'], $_SESSION['openid']['claimedId']);
  235. if (!URLBuilder::isValidReturnToURL($_REQUEST['openid_return_to'])) {
  236. Logger::log('Return_to check failed: %s, URL: %s', $_REQUEST['openid_return_to'], URLBuilder::getCurrentURL(true));
  237. error('diffreturnto', 'The identity provider stated return URL was '
  238. . $_REQUEST['openid_return_to'] . ' but it actually seems to be '
  239. . URLBuilder::getCurrentURL());
  240. }
  241. $id = $_REQUEST[isset($_REQUEST['openid_claimed_id']) ? 'openid_claimed_id' : 'openid_identity'];
  242. if (!URLBuilder::isSameURL($id, $_SESSION['openid']['claimedId']) && !URLBuilder::isSameURL($id, $_SESSION['openid']['opLocalId'])) {
  243. if ($_SESSION['openid']['claimedId'] == 'http://specs.openid.net/auth/2.0/identifier_select') {
  244. $disc = new Discoverer($_REQUEST['openid_claimed_id'], false);
  245. if ($disc->hasServer($_SESSION['openid']['endpointUrl'])) {
  246. $_SESSION['openid']['identity'] = $_REQUEST['openid_identity'];
  247. $_SESSION['openid']['opLocalId'] = $_REQUEST['openid_claimed_id'];
  248. } else {
  249. 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()));
  250. }
  251. } else {
  252. error('diffid', 'Identity provider validated wrong identity. Expected it to '
  253. . 'validate ' . $_SESSION['openid']['claimedId'] . ' but it '
  254. . 'validated ' . $id);
  255. }
  256. }
  257. resetRequests(true);
  258. if (!$valid) {
  259. $dumbauth = true;
  260. if (KEYMANAGER) {
  261. try {
  262. Logger::log('Attempting to authenticate using association...');
  263. $valid = KeyManager::authenticate($_SESSION['openid']['endpointUrl'], $_REQUEST);
  264. $dumbauth = false;
  265. } catch (Exception $ex) {
  266. // Ignore it - try dumb auth
  267. }
  268. }
  269. if ($dumbauth) {
  270. Logger::log('Attempting to authenticate using dumb auth...');
  271. $valid = KeyManager::dumbAuthenticate();
  272. }
  273. }
  274. $_SESSION['openid']['validated'] = $valid;
  275. if (!$valid) {
  276. Logger::log('Validation failed!');
  277. error('noauth', 'Provider didn\'t authenticate response');
  278. }
  279. Processor::callHandlers();
  280. URLBuilder::redirect();
  281. }
  282. /**
  283. * Processes cancel modes.
  284. *
  285. * @param Boolean $valid True if the request has already been authenticated
  286. */
  287. function processCancel($valid) {
  288. error('cancelled', 'Provider cancelled the authentication attempt');
  289. }
  290. /**
  291. * Processes error modes.
  292. *
  293. * @param Boolean $valid True if the request has already been authenticated
  294. */
  295. function processError($valid) {
  296. error('perror', 'Provider error: ' . $_REQUEST['openid_error']);
  297. }
  298. /**
  299. * Populates the session array with the details of the specified error and
  300. * redirects the user appropriately.
  301. *
  302. * @param String $code The error code that occured
  303. * @param String $message A description of the error
  304. */
  305. function error($code, $message) {
  306. $_SESSION['openid']['error'] = $message;
  307. $_SESSION['openid']['errorcode'] = $code;
  308. URLBuilder::redirect();
  309. }
  310. class Processor {
  311. public static function callHandlers() {
  312. global $_POIDSY;
  313. if (empty($_POIDSY['handlers'])) { return; }
  314. foreach ($_POIDSY['handlers'] as $handler) {
  315. $handler->parseResponse();
  316. }
  317. }
  318. }
  319. // Here we go!
  320. process();
  321. ?>