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

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