/[drupal]/contributions/modules/openid/openid.inc
ViewVC logotype

Contents of /contributions/modules/openid/openid.inc

Parent Directory Parent Directory | Revision Log Revision Log | View Revision Graph Revision Graph


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

  ViewVC Help
Powered by ViewVC 1.1.2