openid.lib.php 10 KB

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