openid.lib.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. /**
  4. * OpenID utility functions. Taken from Drupal 6 code (from dries)
  5. * @package chamilo.auth.openid
  6. */
  7. /**
  8. * Code
  9. */
  10. // Diffie-Hellman Key Exchange Default Value.
  11. define('OPENID_DH_DEFAULT_MOD', '155172898181473697471232257763715539915724801' .
  12. '966915404479707795314057629378541917580651227423698188993727816152646631' .
  13. '438561595825688188889951272158842675419950341258706556549803580104870537' .
  14. '681476726513255747040765857479291291572334510643245094715007229621094194' .
  15. '349783925984760375594985848253359305585439638443');
  16. // Constants for Diffie-Hellman key exchange computations.
  17. define('OPENID_DH_DEFAULT_GEN', '2');
  18. define('OPENID_SHA1_BLOCKSIZE', 64);
  19. define('OPENID_RAND_SOURCE', '/dev/urandom');
  20. // OpenID namespace URLs
  21. define('OPENID_NS_2_0', 'http://specs.openid.net/auth/2.0');
  22. define('OPENID_NS_1_1', 'http://openid.net/signon/1.1');
  23. define('OPENID_NS_1_0', 'http://openid.net/signon/1.0');
  24. /**
  25. * Performs an HTTP 302 redirect (for the 1.x protocol).
  26. * This function should be deprecated for 1.8.6.2 needs documentation
  27. */
  28. function openid_redirect_http($url, $message) {
  29. $query = array();
  30. foreach ($message as $key => $val) {
  31. $query[] = $key . '=' . urlencode($val);
  32. }
  33. $sep = (strpos($url, '?') === FALSE) ? '?' : '&';
  34. header('Location: ' . $url . $sep . implode('&', $query), TRUE, 302);
  35. //exit;
  36. }
  37. /**
  38. * Creates a js auto-submit redirect for (for the 2.x protocol)
  39. * This function should be deprecated for 1.8.6.2 needs documentation
  40. */
  41. function openid_redirect($url, $message) {
  42. $output = '<html><head><title>' . get_lang('OpenIDRedirect') . "</title></head>\n<body>";
  43. $output .= '<form method="post" action="' . $url . '" id="openid-redirect-form">';
  44. foreach ($message as $key => $value) {
  45. $output .='<input type="hidden" name="' . $key . '" value="' . $value . '">';
  46. }
  47. $output .= '<noscript><input type="submit" name="submit" value="' . get_lang('Send') . '"/></noscript>';
  48. $output .= '</form>';
  49. $output .= '<script type="text/javascript">document.getElementById("openid-redirect-form").submit();</script>';
  50. $output .= "</body></html>";
  51. return $output;
  52. }
  53. /**
  54. * Determine if the given identifier is an XRI ID.
  55. */
  56. function _openid_is_xri($identifier) {
  57. $firstchar = substr($identifier, 0, 1);
  58. if ($firstchar == "@" || $firstchar == "=")
  59. return TRUE;
  60. if (stristr($identifier, 'xri://') !== FALSE) {
  61. return TRUE;
  62. }
  63. return FALSE;
  64. }
  65. /**
  66. * Normalize the given identifier as per spec.
  67. */
  68. function _openid_normalize($identifier) {
  69. if (_openid_is_xri($identifier)) {
  70. return _openid_normalize_xri($identifier);
  71. } else {
  72. return _openid_normalize_url($identifier);
  73. }
  74. }
  75. function _openid_normalize_xri($xri) {
  76. $normalized_xri = $xri;
  77. if (stristr($xri, 'xri://') !== FALSE) {
  78. $normalized_xri = substr($xri, 6);
  79. }
  80. return $normalized_xri;
  81. }
  82. function _openid_normalize_url($url) {
  83. $normalized_url = $url;
  84. if (stristr($url, '://') === FALSE) {
  85. $normalized_url = 'http://' . $url;
  86. }
  87. if (substr_count($normalized_url, '/') < 3) {
  88. $normalized_url .= '/';
  89. }
  90. return $normalized_url;
  91. }
  92. /**
  93. * Create a serialized message packet as per spec: $key:$value\n .
  94. */
  95. function _openid_create_message($data) {
  96. $serialized = '';
  97. foreach ($data as $key => $value) {
  98. if ((strpos($key, ':') !== FALSE) || (strpos($key, "\n") !== FALSE) || (strpos($value, "\n") !== FALSE)) {
  99. return null;
  100. }
  101. $serialized .= "$key:$value\n";
  102. }
  103. return $serialized;
  104. }
  105. /**
  106. * Encode a message from _openid_create_message for HTTP Post
  107. * @param null|string $message
  108. */
  109. function _openid_encode_message($message) {
  110. $encoded_message = '';
  111. $items = explode("\n", $message);
  112. foreach ($items as $item) {
  113. $parts = explode(':', $item, 2);
  114. if (count($parts) == 2) {
  115. if ($encoded_message != '') {
  116. $encoded_message .= '&';
  117. }
  118. $encoded_message .= rawurlencode(trim($parts[0])) . '=' . rawurlencode(trim($parts[1]));
  119. }
  120. }
  121. return $encoded_message;
  122. }
  123. /**
  124. * Convert a direct communication message
  125. * into an associative array.
  126. */
  127. function _openid_parse_message($message) {
  128. $parsed_message = array();
  129. $items = explode("\n", $message);
  130. foreach ($items as $item) {
  131. $parts = explode(':', $item, 2);
  132. if (count($parts) == 2) {
  133. $parsed_message[$parts[0]] = $parts[1];
  134. }
  135. }
  136. return $parsed_message;
  137. }
  138. /**
  139. * Return a nonce value - formatted per OpenID spec.
  140. */
  141. function _openid_nonce() {
  142. // YYYY-MM-DDThh:mm:ssTZD UTC, plus some optional extra unique chars
  143. return gmstrftime('%Y-%m-%dT%H:%M:%S%Z') .
  144. chr(mt_rand(0, 25) + 65) .
  145. chr(mt_rand(0, 25) + 65) .
  146. chr(mt_rand(0, 25) + 65) .
  147. chr(mt_rand(0, 25) + 65);
  148. }
  149. /**
  150. * Pull the href attribute out of an html link element.
  151. * @param string $rel
  152. */
  153. function _openid_link_href($rel, $html) {
  154. $rel = preg_quote($rel);
  155. preg_match('|<link\s+rel=["\'](.*)' . $rel . '(.*)["\'](.*)/?>|iU', $html, $matches);
  156. if (isset($matches[3])) {
  157. preg_match('|href=["\']([^"]+)["\']|iU', $matches[0], $href);
  158. return trim($href[1]);
  159. }
  160. return FALSE;
  161. }
  162. /**
  163. * Pull the http-equiv attribute out of an html meta element
  164. * @param string $equiv
  165. */
  166. function _openid_meta_httpequiv($equiv, $html) {
  167. preg_match('|<meta\s+http-equiv=["\']' . $equiv . '["\'](.*)/?>|iU', $html, $matches);
  168. if (isset($matches[1])) {
  169. preg_match('|content=["\']([^"]+)["\']|iU', $matches[1], $content);
  170. return $content[1];
  171. }
  172. return FALSE;
  173. }
  174. /**
  175. * Sign certain keys in a message
  176. * @param $association - object loaded from openid_association or openid_server_association table
  177. * - important fields are ->assoc_type and ->mac_key
  178. * @param $message_array - array of entire message about to be sent
  179. * @param $keys_to_sign - keys in the message to include in signature (without
  180. * 'openid.' appended)
  181. */
  182. function _openid_signature($association, $message_array, $keys_to_sign) {
  183. $signature = '';
  184. $sign_data = array();
  185. foreach ($keys_to_sign as $key) {
  186. if (isset($message_array['openid.' . $key])) {
  187. $sign_data[$key] = $message_array['openid.' . $key];
  188. }
  189. }
  190. $message = _openid_create_message($sign_data);
  191. $secret = base64_decode($association->mac_key);
  192. $signature = _openid_hmac($secret, $message);
  193. return base64_encode($signature);
  194. }
  195. /**
  196. * @param string $key
  197. * @param null|string $text
  198. */
  199. function _openid_hmac($key, $text) {
  200. if (strlen($key) > OPENID_SHA1_BLOCKSIZE) {
  201. $key = _openid_sha1($key, true);
  202. }
  203. $key = str_pad($key, OPENID_SHA1_BLOCKSIZE, chr(0x00));
  204. $ipad = str_repeat(chr(0x36), OPENID_SHA1_BLOCKSIZE);
  205. $opad = str_repeat(chr(0x5c), OPENID_SHA1_BLOCKSIZE);
  206. $hash1 = _openid_sha1(($key ^ $ipad) . $text, true);
  207. $hmac = _openid_sha1(($key ^ $opad) . $hash1, true);
  208. return $hmac;
  209. }
  210. function _openid_sha1($text) {
  211. $hex = sha1($text);
  212. $raw = '';
  213. for ($i = 0; $i < 40; $i += 2) {
  214. $hexcode = substr($hex, $i, 2);
  215. $charcode = (int) base_convert($hexcode, 16, 10);
  216. $raw .= chr($charcode);
  217. }
  218. return $raw;
  219. }
  220. function _openid_dh_base64_to_long($str) {
  221. $b64 = base64_decode($str);
  222. return _openid_dh_binary_to_long($b64);
  223. }
  224. function _openid_dh_long_to_base64($str) {
  225. return base64_encode(_openid_dh_long_to_binary($str));
  226. }
  227. /**
  228. * @param string $str
  229. */
  230. function _openid_dh_binary_to_long($str) {
  231. $bytes = array_merge(unpack('C*', $str));
  232. $n = 0;
  233. foreach ($bytes as $byte) {
  234. $n = bcmul($n, pow(2, 8));
  235. $n = bcadd($n, $byte);
  236. }
  237. return $n;
  238. }
  239. function _openid_dh_long_to_binary($long) {
  240. $cmp = bccomp($long, 0);
  241. if ($cmp < 0) {
  242. return FALSE;
  243. }
  244. if ($cmp == 0) {
  245. return "\x00";
  246. }
  247. $bytes = array();
  248. while (bccomp($long, 0) > 0) {
  249. array_unshift($bytes, bcmod($long, 256));
  250. $long = bcdiv($long, pow(2, 8));
  251. }
  252. if ($bytes && ($bytes[0] > 127)) {
  253. array_unshift($bytes, 0);
  254. }
  255. $string = '';
  256. foreach ($bytes as $byte) {
  257. $string .= pack('C', $byte);
  258. }
  259. return $string;
  260. }
  261. /**
  262. * @param string $secret
  263. */
  264. function _openid_dh_xorsecret($shared, $secret) {
  265. $dh_shared_str = _openid_dh_long_to_binary($shared);
  266. $sha1_dh_shared = _openid_sha1($dh_shared_str);
  267. $xsecret = "";
  268. for ($i = 0; $i < strlen($secret); $i++) {
  269. $xsecret .= chr(ord($secret[$i]) ^ ord($sha1_dh_shared[$i]));
  270. }
  271. return $xsecret;
  272. }
  273. /**
  274. * @param string $stop
  275. */
  276. function _openid_dh_rand($stop) {
  277. static $duplicate_cache = array();
  278. // Used as the key for the duplicate cache
  279. $rbytes = _openid_dh_long_to_binary($stop);
  280. if (array_key_exists($rbytes, $duplicate_cache)) {
  281. list($duplicate, $nbytes) = $duplicate_cache[$rbytes];
  282. } else {
  283. if ($rbytes[0] == "\x00") {
  284. $nbytes = strlen($rbytes) - 1;
  285. } else {
  286. $nbytes = strlen($rbytes);
  287. }
  288. $mxrand = bcpow(256, $nbytes);
  289. // If we get a number less than this, then it is in the
  290. // duplicated range.
  291. $duplicate = bcmod($mxrand, $stop);
  292. if (count($duplicate_cache) > 10) {
  293. $duplicate_cache = array();
  294. }
  295. $duplicate_cache[$rbytes] = array($duplicate, $nbytes);
  296. }
  297. do {
  298. $bytes = "\x00" . _openid_get_bytes($nbytes);
  299. $n = _openid_dh_binary_to_long($bytes);
  300. // Keep looping if this value is in the low duplicated range.
  301. } while (bccomp($n, $duplicate) < 0);
  302. return bcmod($n, $stop);
  303. }
  304. function _openid_get_bytes($num_bytes) {
  305. static $f = null;
  306. $bytes = '';
  307. if (!isset($f)) {
  308. $f = @fopen(OPENID_RAND_SOURCE, "r");
  309. }
  310. if (!$f) {
  311. // pseudorandom used
  312. $bytes = '';
  313. for ($i = 0; $i < $num_bytes; $i += 4) {
  314. $bytes .= pack('L', mt_rand());
  315. }
  316. $bytes = substr($bytes, 0, $num_bytes);
  317. } else {
  318. $bytes = fread($f, $num_bytes);
  319. }
  320. return $bytes;
  321. }
  322. /**
  323. * Fix PHP's habit of replacing '.' by '_' in posted data.
  324. */
  325. function _openid_fix_post(&$post) {
  326. //$extensions = module_invoke_all('openid', 'extension');
  327. foreach ($post as $key => $value) {
  328. if (strpos($key, 'openid_') === 0) {
  329. $fixed_key = str_replace('openid_', 'openid.', $key);
  330. $fixed_key = str_replace('openid.ns_', 'openid.ns.', $fixed_key);
  331. $fixed_key = str_replace('openid.sreg_', 'openid.sreg.', $fixed_key);
  332. //foreach ($extensions as $ext) {
  333. // $fixed_key = str_replace('openid.'.$ext.'_', 'openid.'.$ext.'.', $fixed_key);
  334. //}
  335. unset($post[$key]);
  336. $post[$fixed_key] = $value;
  337. }
  338. }
  339. }
  340. /**
  341. * Provide bcpowmod support for PHP4.
  342. */
  343. if (!function_exists('bcpowmod')) {
  344. function bcpowmod($base, $exp, $mod) {
  345. $square = bcmod($base, $mod);
  346. $result = 1;
  347. while (bccomp($exp, 0) > 0) {
  348. if (bcmod($exp, 2)) {
  349. $result = bcmod(bcmul($result, $square), $mod);
  350. }
  351. $square = bcmod(bcmul($square, $square), $mod);
  352. $exp = bcdiv($exp, 2);
  353. }
  354. return $result;
  355. }
  356. }