summaryrefslogtreecommitdiffstats
path: root/modules/openidProvider/lib/Server.php
blob: d1446c1443584965725b5770be135633b5c7bd69 (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
<?php

/*
 * Disable strict error reporting, since the OpenID library
 * used is PHP4-compatible, and not PHP5 strict-standards compatible.
 */
SimpleSAML_Utilities::maskErrors(E_NOTICE | E_STRICT);
if (defined('E_DEPRECATED')) {
	/* PHP 5.3 also has E_DEPRECATED. */
	SimpleSAML_Utilities::maskErrors(constant('E_DEPRECATED'));
}

/* Add the OpenID library search path. */
set_include_path(get_include_path() . PATH_SEPARATOR . dirname(dirname(dirname(dirname(__FILE__)))) . '/lib');
include_once  dirname(dirname(dirname(dirname(__FILE__)))) . '/lib/Auth/OpenID/SReg.php';
include_once  dirname(dirname(dirname(dirname(__FILE__)))) . '/lib/Auth/OpenID/AX.php';

/**
 * Helper class for the OpenID provider code.
 *
 * @package simpleSAMLphp
 * @version $Id$
 */
class sspmod_openidProvider_Server {

	/**
	 * The authentication source for this provider.
	 *
	 * @var SimpleSAML_Auth_Simple
	 */
	private $authSource;


	/**
	 * The attribute name where the username is stored.
	 *
	 * @var string
	 */
	private $usernameAttribute;

  /**
   * authproc configuration option
   *
   * @var array
   */
  private $authProc;
  
	/**
	 * The OpenID server.
	 *
	 * @var Auth_OpenID_Server
	 */
	private $server;


	/**
	 * The directory which contains the trust roots for the users.
	 *
	 * @var string
	 */
	private $trustStoreDir;


	/**
	 * The instance of the OpenID provider class.
	 *
	 * @var sspmod_openidProvider_Server
	 */
	private static $instance;


	/**
	 * Retrieve the OpenID provider class.
	 *
	 * @return sspmod_openidProvider_Server  The OpenID Provider class.
	 */
	public static function getInstance() {

		if (self::$instance === NULL) {
			self::$instance = new sspmod_openidProvider_Server();
		}
		return self::$instance;
	}


	/**
	 * The constructor for the OpenID provider class.
	 *
	 * Initializes and validates the configuration.
	 */
	private function __construct() {

		$config = SimpleSAML_Configuration::getConfig('module_openidProvider.php');

		$this->authSource = new SimpleSAML_Auth_Simple($config->getString('auth'));
		$this->usernameAttribute = $config->getString('username_attribute');
		$this->authProc = array( 'authproc' => $config->getArray('authproc', array()));

		try {
			$store = new Auth_OpenID_FileStore($config->getString('filestore'));
			$this->server = new Auth_OpenID_Server($store, $this->getServerURL());
		} catch (Exception $e) {
			throw $e;
		}

		$this->trustStoreDir = realpath($config->getString('filestore')) . '/truststore';
		if (!is_dir($this->trustStoreDir)) {
			$res = mkdir($this->trustStoreDir, 0777, TRUE);
			if (!$res) {
				throw new SimpleSAML_Error_Exception('Failed to create directory: ' . $this->trustStoreDir);
			}
		}

	}


	/**
	 * Retrieve the authentication source used by the OpenID Provider.
	 *
	 * @return SimpleSAML_Auth_Simple  The authentication source.
	 */
	public function getAuthSource() {

		return $this->authSource;
	}


	/**
	 * Retrieve the current user ID.
	 *
	 * @return string  The current user ID, or NULL if the user isn't authenticated.
	 */
	public function getUserId() {

		if (!$this->authSource->isAuthenticated()) {
			return NULL;
		}

		$attributes = $this->authSource->getAttributes();
		if (!array_key_exists($this->usernameAttribute, $attributes)) {
			throw new SimpleSAML_Error_Exception('Missing username attribute ' .
				var_export($this->usernameAttribute, TRUE) . ' in the attributes of the user.');
		}

		$values = array_values($attributes[$this->usernameAttribute]);
		if (empty($values)) {
			throw new SimpleSAML_Error_Exception('Username attribute was empty.');
		}
		if (count($values) > 1) {
			throw new SimpleSAML_Error_Exception('More than one attribute value in username.');
		}

		$userId = $values[0];
		return $userId;
	}


	/**
	 * Retrieve the current identity.
	 *
	 * @return string  The current identity, or NULL if the user isn't authenticated.
	 */
	public function getIdentity() {

		$userId = $this->getUserId();
		if ($userId === NULL) {
			return NULL;
		}

		$identity = SimpleSAML_Module::getModuleURL('openidProvider/user.php/' . $userId);
		return $identity;
	}


	/**
	 * Retrieve the URL of the server.
	 *
	 * @return string  The URL of the OpenID server.
	 */
	public function getServerURL() {

		return SimpleSAML_Module::getModuleURL('openidProvider/server.php');
	}


	/**
	 * Get the file that contains the trust roots for the user.
	 *
	 * @param string $identity  The identity of the user.
	 * @return string  The file name.
	 */
	private function getTrustFile($identity) {
		assert('is_string($identity)');

		$path = $this->trustStoreDir . '/' . sha1($identity) . '.serialized';
		return $path;
	}


	/**
	 * Get the sites the user trusts.
	 *
	 * @param string $identity  The identity of the user.
	 * @param array $trustRoots  The trust roots the user trusts.
	 */
	public function saveTrustRoots($identity, array $trustRoots) {
		assert('is_string($identity)');

		$file = $this->getTrustFile($identity);
		$tmpFile = $file . '.new.' . getmypid();

		$data = serialize($trustRoots);

		$ok = file_put_contents($tmpFile, $data);
		if ($ok === FALSE) {
			throw new SimpleSAML_Error_Exception('Failed to save file ' . var_export($tmpFile, TRUE));
		}

		$ok = rename($tmpFile, $file);
		if ($ok === FALSE) {
			throw new SimpleSAML_Error_Exception('Failed rename ' . var_export($tmpFile, TRUE) .
				' to ' . var_export($file, TRUE) . '.');
		}
	}


	/**
	 * Get the sites the user trusts.
	 *
	 * @param string $identity  The identity of the user.
	 * @return array  The trust roots the user trusts.
	 */
	public function getTrustRoots($identity) {
		assert('is_string($identity)');

		$file = $this->getTrustFile($identity);

		if (!file_exists($file)) {
			return array();
		}

		$data = file_get_contents($file);
		if ($data === FALSE) {
			throw new SimpleSAML_Error_Exception('Failed to load file ' .
				var_export($file, TRUE). '.');
		}

		$data = unserialize($data);
		if ($data === FALSE) {
			throw new SimpleSAML_Error_Exception('Error unserializing trust roots from file ' .
				var_export($file, TRUE) . '.');
		}

		return $data;
	}


	/**
	 * Add the given trust root to the user.
	 *
	 * @param string $identity  The identity of the user.
	 * @param string $trustRoot  The trust root.
	 */
	public function addTrustRoot($identity, $trustRoot) {
		assert('is_string($identity)');
		assert('is_string($trustRoot)');

		$trs = $this->getTrustRoots($identity);
		if (!in_array($trustRoot, $trs, TRUE)) {
			$trs[] = $trustRoot;
		}

		$this->saveTrustRoots($identity, $trs);
	}


	/**
	 * Remove the given trust root from the trust list of the user.
	 *
	 * @param string $identity  The identity of the user.
	 * @param string $trustRoot  The trust root.
	 */
	public function removeTrustRoot($identity, $trustRoot) {
		assert('is_string($identity)');
		assert('is_string($trustRoot)');

		$trs = $this->getTrustRoots($identity);

		$i = array_search($trustRoot, $trs, TRUE);
		if ($i === FALSE) {
			return;
		}
		array_splice($trs, $i, 1, array());
		$this->saveTrustRoots($identity, $trs);
	}


	/**
	 * Is the given trust root trusted by the user?
	 *
	 * @param string $identity  The identity of the user.
	 * @param string $trustRoot  The trust root.
	 * @return TRUE if it is trusted, FALSE if not.
	 */
	private function isTrusted($identity, $trustRoot) {
		assert('is_string($identity)');
		assert('is_string($trustRoot)');

		$trs = $this->getTrustRoots($identity);
		return in_array($trustRoot, $trs, TRUE);
	}


	/**
	 * Save the state, and return a URL that can contain a reference to the state.
	 *
	 * @param string $page  The name of the page.
	 * @param array $state  The state array.
	 * @return string  A URL with the state ID as a parameter.
	 */
	private function getStateURL($page, array $state) {
		assert('is_string($page)');

		$stateId = SimpleSAML_Auth_State::saveState($state, 'openidProvider:resumeState');
		$stateURL = SimpleSAML_Module::getModuleURL('openidProvider/' . $page);
		$stateURL = SimpleSAML_Utilities::addURLparameter($stateURL, array('StateID' => $stateId));

		return $stateURL;
	}


	/**
	 * Retrieve state by ID.
	 *
	 * @param string $stateId  The state ID.
	 * @return array  The state array.
	 */
	public function loadState($stateId) {
		assert('is_string($stateId)');

		// sanitize the input
		$sid = SimpleSAML_Utilities::parseStateID($stateId);
		if (!is_null($sid['url'])) {
			SimpleSAML_Utilities::checkURLAllowed($sid['url']);
		}

		return SimpleSAML_Auth_State::loadState($stateId, 'openidProvider:resumeState');
	}


	/**
	 * Send an OpenID response.
	 *
	 * This function never returns.
	 *
	 * @param Auth_OpenID_ServerResponse $response  The response.
	 */
	private function sendResponse(Auth_OpenID_ServerResponse $response) {

		SimpleSAML_Logger::debug('openidProvider::sendResponse');

		$webresponse = $this->server->encodeResponse($response);

		if ($webresponse->code !== 200) {
			header('HTTP/1.1 ' . $webresponse->code, TRUE, $webresponse->code);
		}

		foreach ($webresponse->headers as $k => $v) {
			header($k . ': ' . $v);
		}
		header('Connection: Close');

		print($webresponse->body);
		exit(0);
	}


	/**
	 * Process a request.
	 *
	 * This function never returns.
	 *
	 * @param Auth_OpenID_Request $request  The request we are processing.
	 */
	public function processRequest(array $state) {
		assert('isset($state["request"])');

		$request = $state['request'];

    	$sreg_req = Auth_OpenID_SRegRequest::fromOpenIDRequest($request);
    	$ax_req = Auth_OpenId_AX_FetchRequest::fromOpenIDRequest($request);
    
     	/* In resume.php there should be a way to display data requested through sreg or ax. */

		if (!$this->authSource->isAuthenticated()) {
			if ($request->immediate) {
				/* Not logged in, and we cannot show a login form. */
				$this->sendResponse($request->answer(FALSE));
			}

			$resumeURL = $this->getStateURL('resume.php', $state);
			$this->authSource->requireAuth(array('ReturnTo' => $resumeURL));
		}

		$identity = $this->getIdentity();
		assert('$identity !== FALSE'); /* Should always be logged in here. */

		if (!$request->idSelect() && $identity !== $request->identity) {
			/* The identity in the request doesn't match the one of the logged in user. */
			throw new SimpleSAML_Error_Exception('Logged in as different user than the one requested.');
		}

		if ($this->isTrusted($identity, $request->trust_root)) {
			$trusted = TRUE;
		} elseif (isset($state['TrustResponse'])) {
			$trusted = (bool)$state['TrustResponse'];
		} else {
			if ($request->immediate) {
				/* Not trusted, and we cannot show a trust-form. */
				$this->sendResponse($request->answer(FALSE));
			}

			$trustURL = $this->getStateURL('trust.php', $state);
			SimpleSAML_Utilities::redirectTrustedURL($trustURL);
		}

		if (!$trusted) {
			/* The user doesn't trust this site. */
			$this->sendResponse($request->answer(FALSE));
		}
      
    	$response = $request->answer(TRUE, NULL, $identity);

    	//Process attributes
    	$attributes = $this->authSource->getAttributes();
    	foreach ($attributes as $key=>$attr) {
            if (is_array($attr) && count($attr) === 1) {
                    $attributes[$key] = $attr[0];
            }
    	}

    	$pc = new SimpleSAML_Auth_ProcessingChain($this->authProc, array(), 'idp');
    	$state = array(
            'Attributes'=>$attributes,
            'isPassive'=>TRUE
    	);

    	$pc->processStatePassive($state);
    	$attributes = $state['Attributes'];

    	//Process SREG requests
    	$sreg_resp = Auth_OpenID_SRegResponse::extractResponse($sreg_req, $attributes);
    	$sreg_resp->toMessage($response->fields);

    	//Process AX requests
    	$ax_resp = new Auth_OpenID_AX_FetchResponse();
    	foreach($ax_req->iterTypes() as $type_uri) {
            if(isset($attributes[$type_uri])) {
                    $ax_resp->addValue($type_uri, $attributes[$type_uri]);
            }
    	}
    	$ax_resp->toMessage($response->fields);

		/* The user is authenticated, and trusts this site. */
		$this->sendResponse($response);
	}


	/**
	 * Receive an incoming request.
	 *
	 * This function never returns.
	 */
	public function receiveRequest() {

		$request = $this->server->decodeRequest();

		if (!in_array($request->mode, array('checkid_immediate', 'checkid_setup'), TRUE)) {
			$this->sendResponse($this->server->handleRequest($request));
		}

		$state = array(
			'request' => $request,
		);

		$this->processRequest($state);
	}

}