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 9.0KB

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