Commit 18d54304 authored by Piers Harding's avatar Piers Harding
Browse files

auth/saml: add the the SAML authentication plugin into core.


Signed-off-by: default avatarPiers Harding <piers@catalyst.net.nz>
parent 66cbd293
<?php
/**
* Mahara: Electronic portfolio, weblog, resume builder and social networking
* Copyright (C) 2006-2009 Catalyst IT Ltd (http://www.catalyst.net.nz)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* @package mahara
* @subpackage auth-saml
* @author Piers Harding <piers@catalyst.net.nz>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL
* @copyright (C) 2006-2009 Catalyst IT Ltd http://catalyst.net.nz
*
* This file incorporates work covered by the following copyright and
* permission notice:
*
* Moodle - Modular Object-Oriented Dynamic Learning Environment
* http://moodle.com
*
* Copyright (C) 2001-3001 Martin Dougiamas http://dougiamas.com
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details:
*
* http://www.gnu.org/copyleft/gpl.html
*/
define('INTERNAL', 1);
define('PUBLIC', 1);
define('SAML_RETRIES', 5);
global $CFG, $USER, $SESSION;
// do our own partial initialisation so that we can get at the config
// this version of init.php has the user session initiation stuff ripped out
// this is because SimpleSAMLPHP does all kinds of things with the PHP session
// handling including changing the cookie names etc.
require(dirname(__FILE__) . '/init.php');
// get the config pointing to the SAML library - and load it
$samllib = get_config_plugin('auth', 'saml', 'simplesamlphplib');
require_once($samllib.'/lib/_autoload.php');
// point at the configured config directory
$samlconfig = get_config_plugin('auth', 'saml', 'simplesamlphpconfig');
// get all the things that we will need from the SAML authentication
// and then shutdown the session control
SimpleSAML_Configuration::init($samlconfig);
$as = new SimpleSAML_Auth_Simple('default-sp');
$saml_config = SimpleSAML_Configuration::getInstance();
$saml_session = SimpleSAML_Session::getInstance();
$valid_saml_session = $saml_session->isValid('default-sp');
// do we have a logout request?
if(isset($_GET["logout"])) {
// logout the saml session
$as->logout($CFG->wwwroot);
}
// now - are we logged in?
$as->requireAuth();
$saml_attributes = $as->getAttributes();
session_write_close();
// now - let's continue with the session handling that would normally be done
// by Maharas init.php
// the main thin is that it sets the session cookie name back to what it should be
// session_name(get_config('cookieprefix') . 'mahara');
// and starts the session again
// ***********************************************************************
// copied from original init.php
// ***********************************************************************
// Only do authentication once we know the page theme, so that the login form
// can have the correct theming.
require_once(dirname(dirname(dirname(__FILE__))) . '/auth/lib.php');
$SESSION = Session::singleton();
$USER = new LiveUser();
$THEME = new Theme($USER);
// The installer does its own auth_setup checking, because some upgrades may
// break logging in and so need to allow no logins.
if (!defined('INSTALLER')) {
auth_setup();
}
if (get_config('siteclosed')) {
if ($USER->admin) {
if (get_config('disablelogin')) {
$USER->logout();
}
else if (!defined('INSTALLER')) {
redirect('/admin/upgrade.php');
}
}
if (!$USER->admin) {
if ($USER->is_logged_in()) {
$USER->logout();
}
if (!defined('HOME') && !defined('INSTALLER')) {
redirect();
}
}
}
// check to see if we're installed...
if (!get_config('installed')) {
ensure_install_sanity();
$scriptfilename = str_replace('\\', '/', $_SERVER['SCRIPT_FILENAME']);
if (false === strpos($scriptfilename, 'admin/index.php')
&& false === strpos($scriptfilename, 'admin/upgrade.php')
&& false === strpos($scriptfilename, 'admin/upgrade.json.php')) {
redirect('/admin/');
}
}
if (defined('JSON') && !defined('NOSESSKEY')) {
$sesskey = param_variable('sesskey', null);
global $USER;
if ($sesskey === null || $USER->get('sesskey') != $sesskey) {
$USER->logout();
json_reply('global', get_string('invalidsesskey'), 1);
}
}
// ***********************************************************************
// END of copied stuff from original init.php
// ***********************************************************************
// restart the session for Mahara
@session_start();
require_once(get_config('docroot') .'auth/saml/lib.php');
require_once(get_config('libroot') .'institution.php');
// if the user is not logged in, then lets start it going
if(!$USER->is_logged_in()) {
simplesaml_init($saml_config, $valid_saml_session, $saml_attributes, $as);
}
// they are logged in, so they dont need to be here
else {
header('Location: '.$CFG->wwwroot);
}
/**
* check the validity of the users current SAML 2.0 session
* if its bad, force log them out of Mahara, and redirect them to the IdP
* if it's good, find an applicable saml auth instance, and try logging them in with it
* passing in the attributes found from the IdP
*
* @param object $saml_config saml configuration object
* @param boolean $valid_saml_session is there a valid saml2 session
* @param array $saml_attributes saml attributes passed in by the IdP
* @param object $as new saml user object
* @return nothing
*/
function simplesaml_init($saml_config, $valid_saml_session, $saml_attributes, $as) {
global $CFG, $USER, $SESSION;
// $idp = get_config_plugin('auth', 'saml', 'idpidentity');
$retry = $SESSION->get('retry');
if ($retry > SAML_RETRIES) {
throw new AccessTotallyDeniedException(get_string('errorretryexceeded','auth.saml', $retry));
}
else if (!$valid_saml_session) { #
if ($USER->is_logged_in()) {
$USER->logout();
}
$SESSION->set('messages', array());
$SESSION->set('retry', $retry + 1);
// not valid session. Ship user off to the Identity Provider
$as->requireAuth();
} else {
// find all the possible institutions/auth instances
$instances = recordset_to_array(get_recordset_sql("SELECT * FROM auth_instance_config aic, auth_instance ai WHERE ai.id = aic.instance AND ai.authname = 'saml' AND aic.field = 'institutionattribute'"));
// find the one (it should be only one) that has the right field, and the right field value for institution
$instance = false;
foreach ($instances as $row) {
if (isset($saml_attributes[$row->value])) {
// does this institution use a regex match against the institution check value?
if ($configvalue = get_record('auth_instance_config', 'instance', $row->instance, 'field', 'institutionregex')) {
$is_regex = (boolean) $configvalue->value;
}
else {
$is_regex = false;
}
if ($configvalue = get_record('auth_instance_config', 'instance', $row->instance, 'field', 'institutionvalue')) {
$institution_value = $configvalue->value;
}
else {
$institution_value = $row->institution;
}
if ($is_regex) {
foreach ($saml_attributes[$row->value] as $attr) {
if (preg_match('/'.trim($institution_value).'/', $attr)) {
$instance = $row;
break;
}
}
}
else {
foreach ($saml_attributes[$row->value] as $attr) {
if ($attr == $institution_value) {
$instance = $row;
break;
}
}
}
}
}
if (!$instance) {
throw new UserNotFoundException(get_string('errorbadinstitution','auth.saml'));
}
try {
$auth = new AuthSaml($instance->id);
if ($auth->request_user_authorise($saml_attributes)) {
session_write_close();
redirect($CFG->wwwroot);
}
else {
throw new UserNotFoundException(get_string('errnosamluser','auth.saml'));
}
} catch (AccessDeniedException $e) {
throw new UserNotFoundException(get_string('errnosamluser','auth.saml'));
}
}
}
?>
\ No newline at end of file
<?php
/**
* Mahara: Electronic portfolio, weblog, resume builder and social networking
* Copyright (C) 2006-2008 Catalyst IT Ltd (http://www.catalyst.net.nz)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* @package mahara
* @subpackage core
* @author Catalyst IT Ltd
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL
* @copyright (C) 2006-2009 Catalyst IT Ltd http://catalyst.net.nz
*
*/
// XXX NOTE - this has been copied from docroot/init.php
// This was because init bootstrapped the session too early for the
// needs of auth/saml
defined('INTERNAL') || die();
$CFG = new StdClass;
// XXX modified the path as its not in docroot
$CFG->docroot = dirname(dirname(dirname(__FILE__))) . '/';
// Figure out our include path
if (!empty($_SERVER['MAHARA_LIBDIR'])) {
$CFG->libroot = $_SERVER['MAHARA_LIBDIR'];
}
else {
// XXX modified the path as its not in docroot
$CFG->libroot = dirname(dirname(dirname(__FILE__))) . '/lib/';
}
set_include_path($CFG->libroot . PATH_SEPARATOR . $CFG->libroot . 'pear/' . PATH_SEPARATOR . get_include_path());
// Ensure that, by default, the response is not cached
header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
header('Expires: '. gmdate('D, d M Y H:i:s', 507686400) .' GMT');
header('Pragma: no-cache');
// Set up error handling
require('errors.php');
if (!is_readable($CFG->docroot . 'config.php')) {
// @todo Later, this will redirect to the installer script. For now, we
// just log and exit.
log_environ('Not installed! Please create config.php from config-dist.php');
exit;
}
init_performance_info();
require($CFG->docroot . 'config.php');
$CFG = (object)array_merge((array)$cfg, (array)$CFG);
require_once('config-defaults.php');
$CFG = (object)array_merge((array)$cfg, (array)$CFG);
// Fix up paths in $CFG
foreach (array('docroot', 'dataroot') as $path) {
$CFG->{$path} = (substr($CFG->{$path}, -1) != DIRECTORY_SEPARATOR) ? $CFG->{$path} . DIRECTORY_SEPARATOR : $CFG->{$path};
}
// xmldb stuff
$CFG->xmldbdisablenextprevchecking = true;
$CFG->xmldbdisablecommentchecking = true;
// ensure directorypermissions is set
if (empty($CFG->directorypermissions)) {
$CFG->directorypermissions = 0700;
}
// core libraries
require('mahara.php');
ensure_sanity();
require('dml.php');
require('web.php');
require('user.php');
// Database access functions
require('adodb/adodb-exceptions.inc.php');
require('adodb/adodb.inc.php');
try {
// ADODB does not provide the raw driver error message if the connection
// fails for some reason, so we use output buffering to catch whatever
// the error is instead.
ob_start();
if (is_postgres()) {
$CFG->dbtype = 'postgres7';
}
else if (is_mysql()) {
$CFG->dbtype = 'mysql';
}
$db = &ADONewConnection($CFG->dbtype);
if (empty($CFG->dbhost)) {
$CFG->dbhost = '';
}
else if (!empty($CFG->dbport)) {
$CFG->dbhost .= ':'.$CFG->dbport;
}
if (!empty($CFG->dbpersist)) { // Use persistent connection (default)
$dbconnected = $db->PConnect($CFG->dbhost,$CFG->dbuser,$CFG->dbpass,$CFG->dbname);
}
else { // Use single connection
$dbconnected = $db->Connect($CFG->dbhost,$CFG->dbuser,$CFG->dbpass,$CFG->dbname);
}
// Now we have a connection, verify the server is a new enough version
$dbversion = $db->ServerInfo();
if (is_postgres()) {
$okversion = '8.1';
$dbfriendlyname = 'PostgreSQL';
}
else if (is_mysql()) {
$okversion = '5.0.25';
$dbfriendlyname = 'MySQL';
}
if ($dbversion['version'] < $okversion) {
throw new ConfigSanityException(get_string('dbversioncheckfailed', 'error', $dbfriendlyname, $dbversion['version'], $okversion));
}
$db->SetFetchMode(ADODB_FETCH_ASSOC);
configure_dbconnection();
ensure_internal_plugins_exist();
ob_end_clean();
}
catch (Exception $e) {
if ($e instanceof ConfigSanityException) {
throw $e;
}
$errormessage = ob_get_contents();
if (!$errormessage) {
$errormessage = $e->getMessage();
}
ob_end_clean();
$errormessage = get_string('dbconnfailed', 'error') . $errormessage;
throw new ConfigSanityException($errormessage);
}
try {
db_ignore_sql_exceptions(true);
load_config();
db_ignore_sql_exceptions(false);
}
catch (SQLException $e) {
db_ignore_sql_exceptions(false);
}
// Make sure wwwroot is set and available, either in the database or in the
// config file. Cron requires it for some purposes.
if (!isset($CFG->wwwroot) && isset($_SERVER['HTTP_HOST'])) {
$proto = (isset($_SERVER['HTTPS'])) ? 'https://' : 'http://';
$host = (isset($_SERVER['HTTP_X_FORWARDED_HOST'])) ? $_SERVER['HTTP_X_FORWARDED_HOST'] : $_SERVER['HTTP_HOST'];
if (false !== strpos($host, ',')) {
list($host) = explode(',', $host);
$host = trim($host);
}
$path = substr(dirname(__FILE__), strlen($_SERVER['DOCUMENT_ROOT']));
if ($path) {
if (substr($path, 0, 1) != '/') {
$path = '/' . $path;
}
$path .= '/';
} else {
$path = '/';
}
$wwwroot = $proto . $host . $path;
try {
set_config('wwwroot', $wwwroot);
}
catch (Exception $e) {
// Just set it directly. The system will most likely not be installed, so we don't care
$CFG->wwwroot = $wwwroot;
}
}
if (!isset($CFG->noreplyaddress) && isset($_SERVER['HTTP_HOST'])) {
$noreplyaddress = 'noreply@';
$host = (isset($_SERVER['HTTP_X_FORWARDED_HOST'])) ? $_SERVER['HTTP_X_FORWARDED_HOST'] : $_SERVER['HTTP_HOST'];
if (false !== strpos($host, ',')) {
list($host) = explode(',', $host);
$host = trim($host);
}
$noreplyaddress .= $host;
try {
set_config('noreplyaddress', $noreplyaddress);
}
catch (Exception $e) {
// Do nothing again, same reason as above
$CFG->noreplyaddress = $noreplyaddress;
}
}
if (!get_config('theme')) {
// if it's not set, we're probably not installed,
// so set it in $CFG directly rather than the db which doesn't yet exist
$CFG->theme = 'default';
}
if (defined('INSTALLER')) {
// Custom themes sometimes cause upgrades to fail.
$CFG->theme = 'default';
}
// Make sure the search plugin is configured
if (!get_config('searchplugin')) {
try {
set_config('searchplugin', 'internal');
}
catch (Exception $e) {
$CFG->searchplugin = 'internal';
}
}
header('Content-type: text/html; charset=UTF-8');
// XXX everything from here down in docroot/init.php
// has been moved into auth/saml/index.php
// so that it happens at the correct time
//
//// Only do authentication once we know the page theme, so that the login form
//// can have the correct theming.
//require_once('auth/lib.php');
//$SESSION = Session::singleton();
//$USER = new LiveUser();
//$THEME = new Theme($USER);
//// The installer does its own auth_setup checking, because some upgrades may
//// break logging in and so need to allow no logins.
//if (!defined('INSTALLER')) {
// auth_setup();
//}
//
//if (get_config('siteclosed')) {
// if ($USER->admin) {
// if (get_config('disablelogin')) {
// $USER->logout();
// }
// else if (!defined('INSTALLER')) {
// redirect('/admin/upgrade.php');
// }
// }
// if (!$USER->admin) {
// if ($USER->is_logged_in()) {
// $USER->logout();
// }
// if (!defined('HOME') && !defined('INSTALLER')) {
// redirect();
// }
// }
//}
//
//// check to see if we're installed...
//if (!get_config('installed')) {
// ensure_install_sanity();
//
// $scriptfilename = str_replace('\\', '/', $_SERVER['SCRIPT_FILENAME']);
// if (false === strpos($scriptfilename, 'admin/index.php')
// && false === strpos($scriptfilename, 'admin/upgrade.php')
// && false === strpos($scriptfilename, 'admin/upgrade.json.php')) {
// redirect('/admin/');
// }
//}
//
//if (defined('JSON') && !defined('NOSESSKEY')) {
// $sesskey = param_variable('sesskey', null);
// global $USER;
// if ($sesskey === null || $USER->get('sesskey') != $sesskey) {
// $USER->logout();
// json_reply('global', get_string('invalidsesskey'), 1);
// }
//}
/*
* Initializes our performance info early.
*
* Pairs up with get_performance_info() which is actually
* in lib/mahara.php. This function is here so that we can
* call it before all the libs are pulled in.
*
* @uses $PERF
*/
function init_performance_info() {
global $PERF;
$PERF = new StdClass;
$PERF->dbreads = $PERF->dbwrites = 0;
$PERF->logwrites = 0;
if (function_exists('microtime')) {
$PERF->starttime = microtime();
}
if (function_exists('memory_get_usage')) {
$PERF->startmemory = memory_get_usage();
}
if (function_exists('posix_times')) {
$PERF->startposixtimes = posix_times();
}
}
?>
<?php
/**
* Mahara: Electronic portfolio, weblog, resume builder and social networking
* Copyright (C) 2006-2008 Catalyst IT Ltd (http://www.catalyst.net.nz)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* @package mahara
* @subpackage auth-internal
* @author Piers Harding <piers@catalyst.net.nz>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL
* @copyright (C) 2006-2008 Catalyst IT Ltd http://catalyst.net.nz
*
*/
defined('INTERNAL') || die();
//$string['defaultidpidentity'] = 'Default IdP Identity Service';
$string['defaultinstitution'] = 'Default institution';
$string['description'] = 'Authenticate against a SAML 2.0 IdP service';
$string['errorbadinstitution'] = 'Institution for connecting user not resolved';
$string['errorretryexceeded'] = 'Maximum number of retries exceeded (%s) - there must be a problem with the Identity Service';
$string['errnosamluser'] = 'No User found';
$string['errorbadlib'] = 'SimpleSAMLPHP lib directory %s is not correct.';
$string['errorbadconfig'] = 'SimpleSAMLPHP config directory %s is in correct.';
//$string['idpidentity'] = 'IdP Identity Service';
$string['institutionattribute'] = 'Institution attribute (contains "%s")';
$string['institutionvalue'] = 'Institution value to check against attribute';
$string['institutionregex'] = 'Do partial string match with institution shortname';
$string['notusable'] = 'Please install the SimpleSAMLPHP SP libraries';
$string['samlfieldforemail'] = 'SSO field for Email';
$string['samlfieldforfirstname'] = 'SSO field for First Name';
$string['samlfieldforsurname'] = 'SSO field for Surname';
$string['title'] = 'SAML';
$string['updateuserinfoonlogin'] = 'Update user details on login';
$string['userattribute'] = 'User attribute';
$string['simplesamlphplib'] = 'SimpleSAMLPHP lib directory';
$string['simplesamlphpconfig'] = 'SimpleSAMLPHP config directory';