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.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  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. '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. * Checks that the user isn't making requests too frequently, and redirects
  84. * them with an appropriate error if they are.
  85. *
  86. * @return An array containing details about the requests that have been made
  87. */
  88. function checkRequests() {
  89. if (isset($_SESSION['openid']['requests'])) {
  90. $requests = $_SESSION['openid']['requests'];
  91. } else {
  92. $requests = array('lasttime' => 0, 'count' => 0);
  93. }
  94. if ($requests['lasttime'] < time() - OPENID_THROTTLE_GAP) {
  95. // Last request was a while ago, reset the timer
  96. $requests['count'] = 0;
  97. } else if ($requests['count'] > OPENID_THROTTLE_NUM) {
  98. // More than the legal number of requests
  99. error('throttled', 'You are trying to authenticate too often');
  100. }
  101. $requests['count']++;
  102. $requests['lasttime'] = time();
  103. return $requests;
  104. }
  105. /**
  106. * Attempts to perform discovery on the specified URL, redirecting the user
  107. * with an appropriate error if discovery fails.
  108. *
  109. * @param String $url The URL to perform discovery on
  110. * @return An appropriate Discoverer object
  111. */
  112. function tryDiscovery($url) {
  113. try {
  114. $disc = new Discoverer($url);
  115. if ($disc->getServer() == null) {
  116. error('notvalid', 'Claimed identity is not a valid identifier');
  117. }
  118. return $disc;
  119. } catch (Exception $e) {
  120. error('discovery', $e->getMessage());
  121. }
  122. return null;
  123. }
  124. /**
  125. * Retrieves an association handle for the specified server. If we don't
  126. * currently have one, attempts to associate with the server.
  127. *
  128. * @param String $server The server whose handle we're retrieving
  129. * @return The association handle of the server or null on failure
  130. */
  131. function getHandle($server) {
  132. if (KEYMANAGER) {
  133. if (!KeyManager::hasHandle($server)) {
  134. KeyManager::associate($server);
  135. }
  136. return KeyManager::getHandle($server);
  137. } else {
  138. return null;
  139. }
  140. }
  141. /**
  142. * Checks that the nonce specified in the current request equals the one
  143. * stored in the user's session, and redirects them if it doesn't.
  144. */
  145. function checkNonce() {
  146. if ($_REQUEST['openid_nonce'] != $_SESSION['openid']['nonce']) {
  147. error('nonce', 'Nonce doesn\'t match - possible replay attack');
  148. } else {
  149. $_SESSION['openid']['nonce'] = uniqid(microtime(true), true);
  150. }
  151. }
  152. /**
  153. * Checks to see if the request contains an instruction to invalidate the
  154. * handle we used. If it does, the request is authenticated and the handle
  155. * removed (or the user is redirected with an error if the IdP doesn't
  156. * authenticate the message).
  157. *
  158. * @return True if the message has been authenticated, false otherwise
  159. */
  160. function checkHandleRevocation() {
  161. $valid = false;
  162. if (KEYMANAGER && isset($_REQUEST['openid_invalidate_handle'])) {
  163. $valid = KeyManager::dumbAuth();
  164. if ($valid) {
  165. KeyManager::removeKey($_SESSION['openid']['server'], $_REQUEST['openid_invalidate_handle']);
  166. } else {
  167. error('noauth', 'Provider didn\'t authenticate message');
  168. }
  169. }
  170. return $valid;
  171. }
  172. /**
  173. * Processes id_res requests.
  174. *
  175. * @param Boolean $valid True if the request has already been authenticated
  176. */
  177. function processIdRes($valid) {
  178. if (isset($_REQUEST['openid_identity'])) {
  179. processPositiveResponse($valid);
  180. } else if (isset($_REQUEST['openid_user_setup_url'])) {
  181. processSetupRequest();
  182. }
  183. }
  184. /**
  185. * Processes a response where the provider is requesting to interact with the
  186. * user in order to confirm their identity.
  187. */
  188. function processSetupRequest() {
  189. if (defined('OPENID_IMMEDIATE') && OPENID_IMMEDIATE) {
  190. error('noimmediate', 'Couldn\'t perform immediate auth');
  191. }
  192. $handle = getHandle($_SESSION['openid']['server']);
  193. $url = URLBuilder::buildRequest('setup', $_REQUEST['openid_user_setup_url'],
  194. $_SESSION['openid']['delegate'],
  195. $_SESSION['openid']['identity'],
  196. URLBuilder::getCurrentURL(), $handle);
  197. URLBuilder::doRedirect($url);
  198. }
  199. /**
  200. * Processes a positive authentication response.
  201. *
  202. * @param Boolean $valid True if the request has already been authenticated
  203. */
  204. function processPositiveResponse($valid) {
  205. if ($_REQUEST['openid_identity'] != $_SESSION['openid']['delegate']) {
  206. if ($_SESSION['openid']['delegate'] == 'http://specs.openid.net/auth/2.0/identifier_select') {
  207. $_SESSION['openid']['delegate'] = $_REQUEST['openid_identity'];
  208. } else {
  209. error('diffid', 'Identity provider validated wrong identity. Expected it to '
  210. . 'validate ' . $_SESSION['openid']['delegate'] . ' but it '
  211. . 'validated ' . $_REQUEST['openid_identity']);
  212. }
  213. }
  214. if (!$valid) {
  215. $dumbauth = true;
  216. if (KEYMANAGER) {
  217. try {
  218. $valid = KeyManager::authenticate($_SESSION['openid']['server'], $_REQUEST);
  219. $dumbauth = false;
  220. } catch (Exception $ex) {
  221. // Ignore it - try dumb auth
  222. }
  223. }
  224. if ($dumbauth) {
  225. $valid = KeyManager::dumbAuthenticate();
  226. }
  227. }
  228. $_SESSION['openid']['validated'] = $valid;
  229. if (!$valid) {
  230. error('noauth', 'Provider didn\'t authenticate response');
  231. }
  232. parseSRegResponse();
  233. URLBuilder::redirect();
  234. }
  235. /**
  236. * Processes cancel modes.
  237. *
  238. * @param Boolean $valid True if the request has already been authenticated
  239. */
  240. function processCancel($valid) {
  241. error('cancelled', 'Provider cancelled the authentication attempt');
  242. }
  243. /**
  244. * Processes error modes.
  245. *
  246. * @param Boolean $valid True if the request has already been authenticated
  247. */
  248. function processError($valid) {
  249. error('perror', 'Provider error: ' . $_REQUEST['openid_error']);
  250. }
  251. /**
  252. * Populates the session array with the details of the specified error and
  253. * redirects the user appropriately.
  254. *
  255. * @param String $code The error code that occured
  256. * @param String $message A description of the error
  257. */
  258. function error($code, $message) {
  259. $_SESSION['openid']['error'] = $message;
  260. $_SESSION['openid']['errorcode'] = $code;
  261. URLBuilder::redirect();
  262. }
  263. // Here we go!
  264. process();
  265. ?>