summaryrefslogtreecommitdiffstats
path: root/Auth/OpenID/Server.php
blob: 37a2980968bb1187443b333425de1f5028e8a16d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
<?php

/**
 * This module contains an implementation of an OpenID server as
 * Auth_OpenID_Server.
 *
 * PHP versions 4 and 5
 *
 * LICENSE: See the COPYING file included in this distribution.
 *
 * @package OpenID
 * @author JanRain, Inc. <openid@janrain.com>
 * @copyright 2005 Janrain, Inc.
 * @license http://www.gnu.org/copyleft/lesser.html LGPL
 */

require_once "Auth/OpenID/Association.php";
require_once "Auth/OpenID/CryptUtil.php";
require_once "Auth/OpenID/DiffieHellman.php";
require_once "Auth/OpenID/KVForm.php";
require_once "Auth/OpenID/Util.php";
require_once "Auth/OpenID/TrustRoot.php";

/**
 * Status code returned when the only option is to show an error page,
 * since we do not have enough information to redirect back to the
 * consumer. The associated value is an error message that should be
 * displayed on an HTML error page.
 */
define('Auth_OpenID_LOCAL_ERROR', 'local_error');

/**
 * Status code returned when there is an error to return in key-value
 * form to the consumer. The caller should return a 400 Bad Request
 * response with content-type text/plain and the value as the body.
 */
define('Auth_OpenID_REMOTE_ERROR', 'remote_error');

/**
 * Status code returned when there is a key-value form OK response to
 * the consumer. The value associated with this code is the
 * response. The caller should return a 200 OK response with
 * content-type text/plain and the value as the body.
 */
define('Auth_OpenID_REMOTE_OK', 'remote_ok');

/**
 * Status code returned when there is a redirect back to the
 * consumer. The value is the URL to redirect back to. The caller
 * should return a 302 Found redirect with a Location: header
 * containing the URL.
 */
define('Auth_OpenID_REDIRECT', 'redirect');

/**
 * Status code returned when the caller needs to authenticate the
 * user. The associated value is a Auth_OpenID_AuthorizationInfo
 * object that can be used to complete the authentication. If the user
 * has taken some authentication action, use the retry() method of the
 * Auth_OpenID_AuthorizationInfo object to complete the request.
 */
define('Auth_OpenID_DO_AUTH', 'do_auth');

/**
 * Status code returned when there were no OpenID arguments
 * passed. This code indicates that the caller should return a 200 OK
 * response and display an HTML page that says that this is an OpenID
 * server endpoint.
 */
define('Auth_OpenID_DO_ABOUT', 'do_about');

/**
 * An object that implements the OpenID protocol for a single URL.
 *
 * Use this object by calling getOpenIDResponse when you get any
 * request for the server URL.
 */
class Auth_OpenID_Server {

    /**
     * A store implementing the interface in Auth/OpenID/Store/Interface.php
     */
    var $store;

    /**
     * The URL of the server that this instance represents.
     */
    var $server_url;

    /**
     * The server URL with a namespace indicating that this
     * association is a shared association.
     *
     * @access private
     */
    var $_normal_key;

    /**
     * The server URL with a namespace indicating that this
     * association is a private (dumb-mode) association.
     *
     * @access private
     */
    var $_dumb_key;

    /**
     * How long an association should be valid for (in seconds)
     */
    var $association_lifetime = 1209600; // 14 days, in seconds

    /**
     * Constructor.
     *
     * @param string $server_url The URL of the OpenID server
     *
     * @param mixed $store The association store for this
     *     instance. See Auth_OpenID_OpenIDStore
     */
    function Auth_OpenID_Server($server_url, $store)
    {
        $this->server_url = $server_url;
        $this->store =& $store;

        $this->_normal_key = $server_url . '|normal';
        $this->_dumb_key = $server_url . '|dumb';
    }

    /**
     * This is the initial entry point for a server URL.
     *
     * @param mixed $is_authorized: the name of a callback to use for
     * determining if a given identity URL should be authorized. It
     * will be called with the identity URL and the trust_root for
     * this request.
     *
     * @param string $method The HTTP method of the current
     * request. If omitted, $_SERVER['HTTP_METHOD'] will be used.
     *
     * @param array $args The arguments parsed from the request. If
     * omitted, the arguments in the environment will be used.
     *
     * @return array $array A pair of elements in which the first is a
     * status code and the meaning of the second depends on the
     * status. See the status codes defined in this file for
     * information about each response.
     */
    function getOpenIDResponse($is_authorized, $method=null, $args=null)
    {
        if (!isset($method)) {
            $method = $_SERVER['REQUEST_METHOD'];
        }

        switch ($method) {

        case 'GET':
            // Convert anything that starts with openid_ to openid.
            if ($args === null) {
                $args = Auth_OpenID_fixArgs($_GET);
            }
            $auth_info =
                new Auth_OpenID_AuthorizationInfo($this->server_url, $args);
            return $auth_info->retry(&$this, $is_authorized);

        case 'POST':
            if ($args === null) {
                $args = Auth_OpenID_fixArgs($_POST);
            }
            $mode = $args['openid.mode'];
            switch ($mode) {

            case 'associate':
                return $this->associate($args);

            case 'check_authentication':
                return $this->checkAuthentication($args);

            default:
                $err = "Invalid openid.mode ($mode) for a POST request";
                return $this->postError($err);
            }

        default:
            $err = "HTTP method $method is not part of OpenID";
            return array(Auth_OpenID_LOCAL_ERROR, $err);
        }
    }

    /**
     * @access private
     *
     * @param object $auth_info The Auth_OpenID_AuthorizationInfo
     * object representing this request.
     *
     * @param bool $authorized Whether the user making this request is
     * capable of approving this authorization request.
     */
    function getAuthResponse(&$auth_info, $authorized)
    {
        $identity = $auth_info->getIdentityURL();
        if (!isset($identity)) {
            return $this->getError($auth_info->args, 'No identity specified');
        }

        list($status, $info) = $this->_checkTrustRoot(&$auth_info);
        if (!$status) {
            return $this->getError($auth_info->args, $info);
        } else {
            $return_to = $info;
        }

        if (!$authorized) {
            return $this->_getAuthNotAuthorized(&$auth_info, $return_to);
        } else {
            return $this->_getAuthAuthorized(&$auth_info, $return_to);
        }
    }

    /**
     * Return whether the return_to URL matches the trust_root for
     * this request.
     *
     * @access private
     */
    function _checkTrustRoot(&$auth_info)
    {
        $return_to = $auth_info->getReturnTo();
        if (!isset($return_to)) {
            return array(false, 'No return_to URL specified');
        }

        $trust_root = $auth_info->getTrustRoot();
        if (isset($trust_root) &&
            !Auth_OpenID_matchTrustRoot($trust_root, $return_to)) {
            return array(false, 'Trust root does not match');
        }
        return array(true, $return_to);
    }

    /**
     * @access private
     */
    function _getAuthNotAuthorized(&$auth_info, $return_to)
    {
        $mode = $auth_info->getMode();
        switch ($mode) {
        case 'checkid_immediate':
            // Build a URL that is just the URL that came here
            // with the mode changed from checkid_immediate to
            // checkid_setup.
            $args = $auth_info->args;
            $args['openid.mode'] = 'checkid_setup';
            $setup_url = Auth_OpenID_appendArgs($this->server_url, $args);

            // Return to the consumer, instructing it that the user
            // needs to do something in order to verify his identity.
            $rargs = array(
                           'openid.mode' => 'id_res',
                           'openid.user_setup_url' => $setup_url
                           );

            $redir_url = Auth_OpenID_appendArgs($return_to, $rargs);
            return array(Auth_OpenID_REDIRECT, $redir_url);

        case 'checkid_setup':
            // Return to the application indicating that the user
            // needs to authenticate.
            return array(Auth_OpenID_DO_AUTH, &$auth_info);

        default:
            $err = sprintf('invalid openid.mode (%s) for GET requests', $mode);
            return $this->getError($auth_info->args, $err);
        }
    }

    /**
     * @access private
     */
    function _getAuthAuthorized(&$auth_info, $return_to)
    {
        $mode = $auth_info->getMode();
        switch ($mode) {
        case 'checkid_immediate':
        case 'checkid_setup':
            break;
        default:
            $err = sprintf('invalid openid.mode (%s) for GET requests', $mode);
            return $this->getError($auth_info->args, $err);
        }

        $reply = array('openid.mode' => 'id_res',
                       'openid.return_to' => $return_to,
                       'openid.identity' => $auth_info->getIdentityURL()
                       );

        $assoc = null;
        $assoc_handle = @$auth_info->args['openid.assoc_handle'];
        if (isset($assoc_handle)) {
            $key = $this->_normal_key;
            $assoc = $this->store->getAssociation($key, $assoc_handle);

            // fall back to dumb mode if assoc_handle not found,
            // and send the consumer an invalidate_handle message
            if (!isset($assoc) || $assoc->getExpiresIn() <= 0) {
                $assoc = null;
                $this->store->removeAssociation($key, $assoc_handle);
                $reply['openid.invalidate_handle'] = $assoc_handle;
            }
        }

        // Use dumb mode if there is no association.
        if ($assoc === null) {
            $assoc = $this->createAssociation('HMAC-SHA1');
            $this->store->storeAssociation($this->_dumb_key, $assoc);
        }

        $reply['openid.assoc_handle'] = $assoc->handle;
        $signed_fields = array('mode', 'identity', 'return_to');
        $assoc->addSignature($signed_fields, &$reply);
        $redir_url = Auth_OpenID_appendArgs($return_to, $reply);
        return array(Auth_OpenID_REDIRECT, $redir_url);
    }

    /**
     * Perform an openid.mode=associate query
     *
     * @access private
     */
    function associate($query)
    {
        $reply = array();

        $assoc_type = @$query['openid.assoc_type'];
        if (!isset($assoc_type)) {
            $assoc_type = 'HMAC-SHA1';
        }

        $assoc = $this->createAssociation($assoc_type);
        if (!isset($assoc)) {
            $fmt = 'unable to create an association for type %s';
            return self.postError(sprinft($fmt, $assoc_type));
        }

        $this->store->storeAssociation($this->_normal_key, $assoc);

        if (isset($assoc_type)) {
            $reply['assoc_type'] = $assoc_type;
        }
        $reply['assoc_handle'] = $assoc->handle;
        $reply['expires_in'] = strval($assoc->getExpiresIn());

        if (defined('Auth_OpenID_NO_MATH_SUPPORT')) {
            $session_type = null;
        } else {
            $session_type = @$query['openid.session_type'];
        }

        switch ($session_type) {
        case 'DH-SHA1':
            $sess_reply = Auth_OpenID_DiffieHellman::
                serverAssociate($query, $assoc->secret);
            break;
        case null:
            $sess_reply = array('mac_key' => base64_encode($assoc->secret));
            break;
        default:
            $sess_reply = false;
        }

        if ($sess_reply === false) {
            $msg = "Association session (type $session_type) failed";
            return $this->postError($msg);
        }

        $reply = array_merge($reply, $sess_reply);
        $reply_kv = Auth_OpenID_arrayToKV($reply);
        return array(Auth_OpenID_REMOTE_OK, $reply_kv);
    }

    /**
     * Perform an openid.mode=check_authentication request
     *
     * @access private
     */
    function checkAuthentication($args)
    {
        $handle = $args['openid.assoc_handle'];
        if (!isset($handle)) {
            return $this->postError('Missing openid.assoc_handle');
        }

        $store =& $this->store;
        $assoc = $store->getAssociation($this->_dumb_key, $handle);
        $reply = array('is_valid' => 'false');
        if ($assoc !== null && $assoc->getExpiresIn() > 0) {
            $signed = $args['openid.signed'];
            if (!isset($signed)) {
                return $this->postError('Missing openid.signed');
            }

            $sig = $args['openid.sig'];
            if (!isset($sig)) {
                return $this->postError('Missing openid.sig');
            }

            $to_verify = $args;
            $to_verify['openid.mode'] = 'id_res';
            $fields = explode(',', trim($signed));
            $tv_sig = $assoc->signDict($fields, $to_verify);
            
            if ($tv_sig == $sig) {
                $normal_key = $this->_normal_key;
                $store->removeAssociation($normal_key, $assoc->handle);
                $reply['is_valid'] = 'true';

                $inv_handle = @$args['openid.invalidate_handle'];
                if (isset($inv_handle)) {
                    $assoc = $store->getAssociation($normal_key, $inv_handle);
                    if (!isset($assoc)) {
                        $reply['invalidate_handle'] = $inv_handle;
                    }
                }
            }
        } elseif ($assoc !== null) {
            $store->removeAssociation($this->_dumb_key, $assoc_handle);
        }
        
        $kv = Auth_OpenID_arrayToKV($reply);
        return array(Auth_OpenID_REMOTE_OK, $kv);
    }

    /**
     * Create a new association and store it
     *
     * @access private
     */
    function createAssociation($assoc_type)
    {
        if ($assoc_type == 'HMAC-SHA1') {
            $secret = Auth_OpenID_getBytes(20);
        } else {
            // XXX: log
            return false;
        }

        $uniq = base64_encode(Auth_OpenID_getBytes(4));
        $handle = sprintf('{%s}{%x}{%s}', $assoc_type, time(), $uniq);

        $ltime = $this->association_lifetime;
        $assoc = Auth_OpenID_Association::
            fromExpiresIn($ltime, $handle, $secret, $assoc_type);

        return $assoc;
    }

    /**
     * Return an error response for GET requests
     *
     * @access private
     */
    function getError($args, $msg)
    {
        $return_to = @$args['openid.return_to'];
        if (isset($return_to)) {
            $err = array(
                         'openid.mode' => 'error',
                         'openid.error' => $msg
                         );
            $redir_url = Auth_OpenID_appendArgs($return_to, $err);
            return array(Auth_OpenID_REDIRECT, $redir_url);
        } else {
            foreach (array_keys($args) as $k) {
                if (preg_match('/^openid\./', $k)) {
                    return array(Auth_OpenID_LOCAL_ERROR, $msg);
                }
            }

            return array(Auth_OpenID_DO_ABOUT, null);
        }
    }

    /**
     * Return an error response for POST requests
     *
     * @access private
     */
    function postError($msg)
    {
        $kv = Auth_OpenID_arrayToKV(array('error' => $msg));
        return array(Auth_OpenID_REMOTE_ERROR, $kv);
    }
}

class Auth_OpenID_AuthorizationInfo {
    function Auth_OpenID_AuthorizationInfo($server_url, $args)
    {
        $this->server_url = $server_url;
        $this->args = $args;
    }

    function getMode()
    {
        return $this->args['openid.mode'];
    }

    function getIdentityURL()
    {
        return @$this->args['openid.identity'];
    }

    function getReturnTo()
    {
        return @$this->args['openid.return_to'];
    }

    function cancel()
    {
        return array(Auth_OpenID_REDIRECT, $this->getCancelURL());
    }

    function getCancelURL()
    {
        $cancel_args = array('openid.mode' => 'cancel');
        $return_to = $this->args['openid.return_to'];
        return Auth_OpenID_appendArgs($return_to, $cancel_args);
    }

    function getRetryURL()
    {
        return Auth_OpenID_appendArgs($this->server_url, $this->args);
    }

    function getTrustRoot()
    {
        if (isset($this->args['openid.trust_root'])) {
            return $this->args['openid.trust_root'];
        } else {
            return @$this->args['openid.return_to'];
        }
    }

    function retry(&$server, $is_authorized)
    {
        $trust_root = $this->getTrustRoot();
        $identity_url = $this->getIdentityURL();

        // If there is no return_to or trust_root or there is no
        // identity_url, then it's impossible to continue.
        if (isset($identity_url) && isset($trust_root)) {
            $authorized = $is_authorized($identity_url, $trust_root);
        } else {
            $authorized = false;
        }

        return $server->getAuthResponse(&$this, $authorized);
    }
}