login.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. /**
  4. * OpenID login method
  5. *
  6. * The OpenID login method relies on authentication servers providing a public
  7. * URL that can confirm the identity of a person, thus avoiding the spread
  8. * use of password transmissions over non-secure lines (for Dokeos, it is a
  9. * good way of avoiding password theft)
  10. * @package chamilo.auth.openid
  11. */
  12. require_once 'openid.lib.php';
  13. require_once 'xrds.lib.php';
  14. function openid_form()
  15. {
  16. $form = new FormValidator(
  17. 'openid_login',
  18. 'post',
  19. null,
  20. null,
  21. array('class' => 'form-vertical form_login')
  22. );
  23. $form -> addElement('text', 'openid_url', array(get_lang('OpenIDURL'), Display::url(get_lang('OpenIDWhatIs'), 'main/auth/openid/whatis.php')), array('class' => 'openid_input'));
  24. $form -> addElement('button', 'submit', get_lang('Login'));
  25. return $form->returnForm();
  26. }
  27. /**
  28. * The initial step of OpenID authentication responsible for the following:
  29. * - Perform discovery on the claimed OpenID.
  30. * - If possible, create an association with the Provider's endpoint.
  31. * - Create the authentication request.
  32. * - Perform the appropriate redirect.
  33. *
  34. * @param $claimed_id The OpenID to authenticate
  35. * @param $return_to The endpoint to return to from the OpenID Provider
  36. */
  37. function openid_begin($claimed_id, $return_to = '', $form_values = array()) {
  38. $claimed_id = _openid_normalize($claimed_id);
  39. $services = openid_discovery($claimed_id);
  40. if (count($services) == 0) {
  41. echo 'Sorry, that is not a valid OpenID. Please ensure you have spelled your ID correctly.';
  42. return;
  43. }
  44. $op_endpoint = $services[0]['uri'];
  45. // Store the discovered endpoint in the session (so we don't have to rediscover).
  46. $_SESSION['openid_op_endpoint'] = $op_endpoint;
  47. // Store the claimed_id in the session (for handling delegation).
  48. $_SESSION['openid_claimed_id'] = $claimed_id;
  49. // Store the login form values so we can pass them to
  50. // user_exteral_login later.
  51. $_SESSION['openid_user_login_values'] = $form_values;
  52. // If bcmath is present, then create an association
  53. $assoc_handle = '';
  54. if (function_exists('bcadd')) {
  55. $assoc_handle = openid_association($op_endpoint);
  56. }
  57. // Now that there is an association created, move on
  58. // to request authentication from the IdP
  59. $identity = (!empty($services[0]['delegate'])) ? $services[0]['delegate'] : $claimed_id;
  60. if (isset($services[0]['types']) && is_array($services[0]['types']) && in_array(OPENID_NS_2_0 . '/server', $services[0]['types'])) {
  61. $identity = 'http://openid.net/identifier_select/2.0';
  62. }
  63. $authn_request = openid_authentication_request($claimed_id, $identity, $return_to, $assoc_handle, $services[0]['version']);
  64. if ($services[0]['version'] == 2) {
  65. echo openid_redirect($op_endpoint, $authn_request);
  66. } else {
  67. echo openid_redirect_http($op_endpoint, $authn_request);
  68. }
  69. }
  70. /**
  71. * Completes OpenID authentication by validating returned data from the OpenID
  72. * Provider.
  73. * @param array $response Array of returned from the OpenID provider (typically $_REQUEST).
  74. * @return array $response Response values for further processing with $response['status'] set to one of 'success', 'failed' or 'cancel'.
  75. */
  76. function openid_complete($response) {
  77. // Default to failed response
  78. $response['status'] = 'failed';
  79. if (isset($_SESSION['openid_op_endpoint']) && isset($_SESSION['openid_claimed_id'])) {
  80. _openid_fix_post($response);
  81. $op_endpoint = $_SESSION['openid_op_endpoint'];
  82. $claimed_id = $_SESSION['openid_claimed_id'];
  83. unset($_SESSION['openid_op_endpoint']);
  84. unset($_SESSION['openid_claimed_id']);
  85. if (isset($response['openid.mode'])) {
  86. if ($response['openid.mode'] == 'cancel') {
  87. $response['status'] = 'cancel';
  88. } else {
  89. if (openid_verify_assertion($op_endpoint, $response)) {
  90. $response['openid.identity'] = $claimed_id;
  91. $response['status'] = 'success';
  92. }
  93. }
  94. }
  95. }
  96. return $response;
  97. }
  98. /**
  99. * Perform discovery on a claimed ID to determine the OpenID provider endpoint.
  100. *
  101. * @param $claimed_id The OpenID URL to perform discovery on.
  102. *
  103. * @return Array of services discovered (including OpenID version, endpoint
  104. * URI, etc).
  105. */
  106. function openid_discovery($claimed_id)
  107. {
  108. $services = array();
  109. $xrds_url = $claimed_id;
  110. if (_openid_is_xri($claimed_id)) {
  111. $xrds_url = 'http://xri.net/' . $claimed_id;
  112. }
  113. $url = @parse_url($xrds_url);
  114. if ($url['scheme'] == 'http' || $url['scheme'] == 'https') {
  115. // For regular URLs, try Yadis resolution first, then HTML-based discovery
  116. $headers = array('Accept' => 'application/xrds+xml');
  117. //TODO
  118. $result = openid_http_request($xrds_url, $headers);
  119. if (!isset($result->error)) {
  120. if (isset($result->headers['Content-Type']) && preg_match("/application\/xrds\+xml/", $result->headers['Content-Type'])) {
  121. // Parse XML document to find URL
  122. $services = xrds_parse($result->data);
  123. } else {
  124. $xrds_url = NULL;
  125. if (isset($result->headers['X-XRDS-Location'])) {
  126. $xrds_url = $result->headers['X-XRDS-Location'];
  127. } else {
  128. // Look for meta http-equiv link in HTML head
  129. $xrds_url = _openid_meta_httpequiv('X-XRDS-Location', $result->data);
  130. }
  131. if (!empty($xrds_url)) {
  132. $headers = array('Accept' => 'application/xrds+xml');
  133. //TODO
  134. $xrds_result = openid_http_request($xrds_url, $headers);
  135. if (!isset($xrds_result->error)) {
  136. $services = xrds_parse($xrds_result->data);
  137. }
  138. }
  139. }
  140. // Check for HTML delegation
  141. if (count($services) == 0) {
  142. // Look for 2.0 links
  143. $uri = _openid_link_href('openid2.provider', $result->data);
  144. $delegate = _openid_link_href('openid2.local_id', $result->data);
  145. $version = 2;
  146. // 1.0 links
  147. if (empty($uri)) {
  148. $uri = _openid_link_href('openid.server', $result->data);
  149. $delegate = _openid_link_href('openid.delegate', $result->data);
  150. $version = 1;
  151. }
  152. if (!empty($uri)) {
  153. $services[] = array('uri' => $uri, 'delegate' => $delegate, 'version' => $version);
  154. }
  155. }
  156. }
  157. }
  158. return $services;
  159. }
  160. /**
  161. * Attempt to create a shared secret with the OpenID Provider.
  162. * @param $op_endpoint URL of the OpenID Provider endpoint.
  163. * @return object $assoc_handle The association handle.
  164. */
  165. function openid_association($op_endpoint) {
  166. //@todo Remove Old Associations:
  167. $openid_association = Database::get_main_table(TABLE_MAIN_OPENID_ASSOCIATION);
  168. $sql = "DELETE FROM $openid_association
  169. WHERE created + expires_in < '" . api_get_utc_datetime() . "'";
  170. Database::query($sql);
  171. // Check to see if we have an association for this IdP already
  172. $op_endpoint = Database::escape_string($op_endpoint);
  173. $sql = "SELECT assoc_handle
  174. FROM $openid_association
  175. WHERE idp_endpoint_uri = '$op_endpoint'";
  176. $assoc_handle = Database::query($sql);
  177. if (Database::num_rows($assoc_handle) <= 1) {
  178. $mod = OPENID_DH_DEFAULT_MOD;
  179. $gen = OPENID_DH_DEFAULT_GEN;
  180. $r = _openid_dh_rand($mod);
  181. $private = bcadd($r, 1);
  182. $public = bcpowmod($gen, $private, $mod);
  183. // If there is no existing association, then request one
  184. $assoc_request = openid_association_request($public);
  185. $assoc_message = _openid_encode_message(_openid_create_message($assoc_request));
  186. $assoc_headers = array('Content-Type' => 'application/x-www-form-urlencoded; charset=utf-8');
  187. //TODO
  188. $assoc_result = openid_http_request($op_endpoint, $assoc_headers, 'POST', $assoc_message);
  189. if (isset($assoc_result->error)) {
  190. return FALSE;
  191. }
  192. $assoc_response = _openid_parse_message($assoc_result->data);
  193. if (isset($assoc_response['mode']) && $assoc_response['mode'] == 'error') {
  194. return FALSE;
  195. }
  196. if ($assoc_response['session_type'] == 'DH-SHA1') {
  197. $spub = _openid_dh_base64_to_long($assoc_response['dh_server_public']);
  198. $enc_mac_key = base64_decode($assoc_response['enc_mac_key']);
  199. $shared = bcpowmod($spub, $private, $mod);
  200. $assoc_response['mac_key'] = base64_encode(_openid_dh_xorsecret($shared, $enc_mac_key));
  201. }
  202. //TODO
  203. $openid_association = Database::get_main_table(TABLE_MAIN_OPENID_ASSOCIATION);
  204. Database::query(sprintf("INSERT INTO $openid_association (idp_endpoint_uri, session_type, assoc_handle, assoc_type, expires_in, mac_key, created) VALUES('%s', '%s', '%s', '%s', %d, '%s', %d)", $op_endpoint, $assoc_response['session_type'], $assoc_response['assoc_handle'], $assoc_response['assoc_type'], $assoc_response['expires_in'], $assoc_response['mac_key'], api_get_utc_datetime()));
  205. $assoc_handle = $assoc_response['assoc_handle'];
  206. }
  207. return $assoc_handle;
  208. }
  209. /**
  210. * ?
  211. */
  212. function openid_association_request($public) {
  213. $request = array(
  214. 'openid.ns' => OPENID_NS_2_0,
  215. 'openid.mode' => 'associate',
  216. 'openid.session_type' => 'DH-SHA1',
  217. 'openid.assoc_type' => 'HMAC-SHA1'
  218. );
  219. if ($request['openid.session_type'] == 'DH-SHA1' || $request['openid.session_type'] == 'DH-SHA256') {
  220. $cpub = _openid_dh_long_to_base64($public);
  221. $request['openid.dh_consumer_public'] = $cpub;
  222. }
  223. return $request;
  224. }
  225. /**
  226. *
  227. */
  228. function openid_authentication_request($claimed_id, $identity, $return_to = '', $assoc_handle = '', $version = 2) {
  229. $realm = ($return_to) ? $return_to : api_get_self();
  230. $ns = ($version == 2) ? OPENID_NS_2_0 : OPENID_NS_1_0;
  231. $request = array(
  232. 'openid.ns' => $ns,
  233. 'openid.mode' => 'checkid_setup',
  234. 'openid.identity' => $identity,
  235. 'openid.claimed_id' => $claimed_id,
  236. 'openid.assoc_handle' => $assoc_handle,
  237. 'openid.return_to' => $return_to,
  238. );
  239. if ($version == 2) {
  240. $request['openid.realm'] = $realm;
  241. } else {
  242. $request['openid.trust_root'] = $realm;
  243. }
  244. // Simple Registration - we don't ask lastname and firstname because the only
  245. // available similar data is "fullname" and we would have to guess where to split
  246. $request['openid.sreg.required'] = 'nickname,email';
  247. $request['openid.ns.sreg'] = "http://openid.net/extensions/sreg/1.1";
  248. //$request = array_merge($request, module_invoke_all('openid', 'request', $request));
  249. //$request = array_merge($request);
  250. return $request;
  251. }
  252. /**
  253. * Attempt to verify the response received from the OpenID Provider.
  254. *
  255. * @param $op_endpoint The OpenID Provider URL.
  256. * @param $response Array of repsonse values from the provider.
  257. *
  258. * @return boolean
  259. */
  260. function openid_verify_assertion($op_endpoint, $response) {
  261. $valid = FALSE;
  262. //TODO
  263. $openid_association = Database::get_main_table(TABLE_MAIN_OPENID_ASSOCIATION);
  264. $sql = sprintf("SELECT * FROM $openid_association WHERE assoc_handle = '%s'", $response['openid.assoc_handle']);
  265. $res = Database::query($sql);
  266. $association = Database::fetch_object($res);
  267. if ($association && isset($association->session_type)) {
  268. $keys_to_sign = explode(',', $response['openid.signed']);
  269. $self_sig = _openid_signature($association, $response, $keys_to_sign);
  270. if ($self_sig == $response['openid.sig']) {
  271. $valid = TRUE;
  272. } else {
  273. $valid = FALSE;
  274. }
  275. } else {
  276. $request = $response;
  277. $request['openid.mode'] = 'check_authentication';
  278. $message = _openid_create_message($request);
  279. $headers = array('Content-Type' => 'application/x-www-form-urlencoded; charset=utf-8');
  280. $result = openid_http_request($op_endpoint, $headers, 'POST', _openid_encode_message($message));
  281. if (!isset($result->error)) {
  282. $response = _openid_parse_message($result->data);
  283. if (strtolower(trim($response['is_valid'])) == 'true') {
  284. $valid = TRUE;
  285. } else {
  286. $valid = FALSE;
  287. }
  288. }
  289. }
  290. return $valid;
  291. }
  292. /**
  293. * Make a HTTP request - This function has been copied straight over from Drupal 6 code (drupal_http_request)
  294. * @param string $data
  295. */
  296. function openid_http_request($url, $headers = array(), $method = 'GET', $data = NULL, $retry = 3) {
  297. $result = new stdClass();
  298. // Parse the URL and make sure we can handle the schema.
  299. $uri = parse_url($url);
  300. switch ($uri['scheme']) {
  301. case 'http':
  302. $port = isset($uri['port']) ? $uri['port'] : 80;
  303. $host = $uri['host'] . ($port != 80 ? ':' . $port : '');
  304. $fp = @fsockopen($uri['host'], $port, $errno, $errstr, 15);
  305. break;
  306. case 'https':
  307. // Note: Only works for PHP 4.3 compiled with OpenSSL.
  308. $port = isset($uri['port']) ? $uri['port'] : 443;
  309. $host = $uri['host'] . ($port != 443 ? ':' . $port : '');
  310. $fp = @fsockopen('ssl://' . $uri['host'], $port, $errno, $errstr, 20);
  311. break;
  312. default:
  313. $result->error = 'invalid schema ' . $uri['scheme'];
  314. return $result;
  315. }
  316. // Make sure the socket opened properly.
  317. if (!$fp) {
  318. // When a network error occurs, we make sure that it is a negative number so
  319. // it can clash with the HTTP status codes.
  320. $result->code = -$errno;
  321. $result->error = trim($errstr);
  322. return $result;
  323. }
  324. // Construct the path to act on.
  325. $path = isset($uri['path']) ? $uri['path'] : '/';
  326. if (isset($uri['query'])) {
  327. $path .= '?' . $uri['query'];
  328. }
  329. // Create HTTP request.
  330. $defaults = array(
  331. // RFC 2616: "non-standard ports MUST, default ports MAY be included".
  332. // We don't add the port to prevent from breaking rewrite rules checking the
  333. // host that do not take into account the port number.
  334. 'Host' => "Host: $host",
  335. 'User-Agent' => 'User-Agent: Chamilo (+http://www.chamilo.org/)',
  336. 'Content-Length' => 'Content-Length: ' . strlen($data)
  337. );
  338. // If the server url has a user then attempt to use basic authentication
  339. if (isset($uri['user'])) {
  340. $defaults['Authorization'] = 'Authorization: Basic ' . base64_encode($uri['user'] . (!empty($uri['pass']) ? ":" . $uri['pass'] : ''));
  341. }
  342. foreach ($headers as $header => $value) {
  343. $defaults[$header] = $header . ': ' . $value;
  344. }
  345. $request = $method . ' ' . $path . " HTTP/1.0\r\n";
  346. $request .= implode("\r\n", $defaults);
  347. $request .= "\r\n\r\n";
  348. if ($data) {
  349. $request .= $data . "\r\n";
  350. }
  351. $result->request = $request;
  352. fwrite($fp, $request);
  353. // Fetch response.
  354. $response = '';
  355. while (!feof($fp) && $chunk = fread($fp, 1024)) {
  356. $response .= $chunk;
  357. }
  358. fclose($fp);
  359. // Parse response.
  360. list($split, $result->data) = explode("\r\n\r\n", $response, 2);
  361. $split = preg_split("/\r\n|\n|\r/", $split);
  362. list($protocol, $code, $text) = explode(' ', trim(array_shift($split)), 3);
  363. $result->headers = array();
  364. // Parse headers.
  365. while ($line = trim(array_shift($split))) {
  366. list($header, $value) = explode(':', $line, 2);
  367. if (isset($result->headers[$header]) && $header == 'Set-Cookie') {
  368. // RFC 2109: the Set-Cookie response header comprises the token Set-
  369. // Cookie:, followed by a comma-separated list of one or more cookies.
  370. $result->headers[$header] .= ',' . trim($value);
  371. } else {
  372. $result->headers[$header] = trim($value);
  373. }
  374. }
  375. $responses = array(
  376. 100 => 'Continue', 101 => 'Switching Protocols',
  377. 200 => 'OK', 201 => 'Created', 202 => 'Accepted', 203 => 'Non-Authoritative Information', 204 => 'No Content', 205 => 'Reset Content', 206 => 'Partial Content',
  378. 300 => 'Multiple Choices', 301 => 'Moved Permanently', 302 => 'Found', 303 => 'See Other', 304 => 'Not Modified', 305 => 'Use Proxy', 307 => 'Temporary Redirect',
  379. 400 => 'Bad Request', 401 => 'Unauthorized', 402 => 'Payment Required', 403 => 'Forbidden', 404 => 'Not Found', 405 => 'Method Not Allowed', 406 => 'Not Acceptable', 407 => 'Proxy Authentication Required', 408 => 'Request Time-out', 409 => 'Conflict', 410 => 'Gone', 411 => 'Length Required', 412 => 'Precondition Failed', 413 => 'Request Entity Too Large', 414 => 'Request-URI Too Large', 415 => 'Unsupported Media Type', 416 => 'Requested range not satisfiable', 417 => 'Expectation Failed',
  380. 500 => 'Internal Server Error', 501 => 'Not Implemented', 502 => 'Bad Gateway', 503 => 'Service Unavailable', 504 => 'Gateway Time-out', 505 => 'HTTP Version not supported'
  381. );
  382. // RFC 2616 states that all unknown HTTP codes must be treated the same as the
  383. // base code in their class.
  384. if (!isset($responses[$code])) {
  385. $code = floor($code / 100) * 100;
  386. }
  387. switch ($code) {
  388. case 200: // OK
  389. case 304: // Not modified
  390. break;
  391. case 301: // Moved permanently
  392. case 302: // Moved temporarily
  393. case 307: // Moved temporarily
  394. $location = $result->headers['Location'];
  395. if ($retry) {
  396. $result = openid_http_request($result->headers['Location'], $headers, $method, $data, --$retry);
  397. $result->redirect_code = $result->code;
  398. }
  399. $result->redirect_url = $location;
  400. break;
  401. default:
  402. $result->error = $text;
  403. }
  404. $result->code = $code;
  405. return $result;
  406. }