openid.lib.php 10 KB

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