lib.php 67.8 KB
Newer Older
1 2 3 4 5 6
<?php
/**
 *
 * @package    mahara
 * @subpackage auth-saml
 * @author     Piers Harding <piers@catalyst.net.nz>
7
 * @author     Francis Devine <francis@catalyst.net.nz>
8 9
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL version 3 or later
 * @copyright  For copyright information on Mahara, please see the README file distributed with this software.
10 11 12 13 14 15 16 17 18 19 20
 * @copyright  (C) portions from Moodle, (C) Martin Dougiamas http://dougiamas.com
 */

defined('INTERNAL') || die();
require_once(get_config('docroot') . 'auth/lib.php');

/**
 * Authenticates users with SAML 2.0
 */
class AuthSaml extends Auth {

21 22 23 24 25
    public static function get_metadata_path() {
        check_dir_exists(get_config('dataroot') . 'metadata/');
        return get_config('dataroot') . 'metadata/';
    }

26 27 28 29 30
    public static function prepare_metadata_path($idp) {
        $path = self::get_metadata_path() . preg_replace('/[\/:\.]/', '_', $idp) . '.xml';
        return $path;
    }

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
    /**
    * Loads and merges in a file with an attribute map.
    *
    * @param string $filepath  Path of attribute map file.
    * @param array $mapping Array where the attributes from the file should be added
    */
    private static function custom_loadmapfile($filepath, $mapping = array()) {
        if (!is_readable($filepath)) {
            throw new Exception(get_string('attributemapfilenotfound', 'auth.saml', $filepath));
        }
        $attributemap = NULL;
        include($filepath);
        if (!is_array($attributemap)) {
            throw new Exception(get_string('attributemapfilenotamap', 'auth.saml', $filepath));
        }

        $mapping = array_merge_recursive($mapping, $attributemap);
        return $mapping;
    }

/*
* Loads all mappings in the files into an array with 'class' => 'core:AttributeMap'
*
* @param filepaths array Paths to files that contain a mapping array
*/
    public static function get_attributemappings($filepaths= array()) {

          $configparameter = array(
              'class' => 'core:AttributeMap',
          );

          $attributemap = array();
          foreach ($filepaths as $key => $filepath) {
                //get the $attributemap array in the file
                $attributemap = self::custom_loadmapfile($filepath, $attributemap);
          }

          return array_merge($attributemap, $configparameter);
    }

71 72 73 74 75
    public static function get_certificate_path() {
        check_dir_exists(get_config('dataroot') . 'certificate/');
        return get_config('dataroot') . 'certificate/';
    }

76 77 78
    public function __construct($id = null) {
        $this->type = 'saml';
        $this->has_instance_config = true;
79

80 81 82 83 84
        $this->config['user_attribute'] = '';
        $this->config['weautocreateusers'] = 1;
        $this->config['firstnamefield' ] = '';
        $this->config['surnamefield'] = '';
        $this->config['emailfield'] = '';
85
        $this->config['studentidfield'] = '';
86 87 88 89
        $this->config['institutionattribute'] = '';
        $this->config['institutionregex'] = 0;
        $this->config['institutionvalue'] = '';
        $this->config['updateuserinfoonlogin'] = 1;
90
        $this->config['remoteuser'] = true;
91
        $this->config['loginlink'] = false;
92
        $this->config['institutionidp'] = '';
93
        $this->config['institutionidpentityid'] = '';
94
        $this->config['authloginmsg'] = '';
95
        $this->instanceid = $id;
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
        if (!empty($id)) {
            return $this->init($id);
        }
        return true;
    }

    public function init($id = null) {
        $this->ready = parent::init($id);

        // Check that required fields are set
        if ( empty($this->config['user_attribute']) ||
             empty($this->config['institutionattribute'])
              ) {
            $this->ready = false;
        }

        return $this->ready;
    }


    /**
     * We can autocreate users if the admin has said we can
     * in weautocreateusers
     */
    public function can_auto_create_users() {
122
        return (bool)$this->config['weautocreateusers'];
123 124 125 126 127 128 129 130 131
    }


    /**
     * Grab a delegate object for auth stuff
     */
    public function request_user_authorise($attributes) {
        global $USER, $SESSION;
        $this->must_be_ready();
132

133 134 135 136
        if (empty($attributes) or !array_key_exists($this->config['user_attribute'], $attributes)
                               or !array_key_exists($this->config['institutionattribute'], $attributes)) {
            throw new AccessDeniedException();
        }
137

138
        $remoteuser      = $attributes[$this->config['user_attribute']][0];
139 140 141
        $firstname       = isset($attributes[$this->config['firstnamefield']][0]) ? $attributes[$this->config['firstnamefield']][0] : null;
        $lastname        = isset($attributes[$this->config['surnamefield']][0]) ? $attributes[$this->config['surnamefield']][0] : null;
        $email           = isset($attributes[$this->config['emailfield']][0]) ? $attributes[$this->config['emailfield']][0] : null;
142
        $studentid       = isset($attributes[$this->config['studentidfield']][0]) ? $attributes[$this->config['studentidfield']][0] : null;
143
        $institutionname = $this->institution;
144

145 146 147 148 149
        $create = false;
        $update = false;

        // Retrieve a $user object. If that fails, create a blank one.
        try {
150
            $isremote = $this->config['remoteuser'] ? true : false;
151 152
            $user = new User;
            if (get_config('usersuniquebyusername')) {
153 154
                // When turned on, this setting means that it doesn't matter
                // which other application the user SSOs from, they will be
155 156
                // given the same account in Mahara.
                //
157 158 159 160 161
                // This setting is one that has security implications unless
                // only turned on by people who know what they're doing. In
                // particular, every system linked to Mahara should be making
                // sure that same username == same person.  This happens for
                // example if two Moodles are using the same LDAP server for
162 163
                // authentication.
                //
164 165 166
                // If this setting is on, it must NOT be possible to self
                // register on the site for ANY institution - otherwise users
                // could simply pick usernames of people's accounts they wished
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
                // to steal.
                if ($institutions = get_column('institution', 'name', 'registerallowed', '1')) {
                    log_warn("usersuniquebyusername is turned on but registration is allowed for an institution. "
                        . "No institution can have registration allowed for it, for security reasons.\n"
                        . "The following institutions have registration enabled:\n  " . join("\n  ", $institutions));
                    throw new AccessDeniedException();
                }

                if (!get_config('usersallowedmultipleinstitutions')) {
                    log_warn("usersuniquebyusername is turned on but usersallowedmultipleinstitutions is off. "
                        . "This makes no sense, as users will then change institution every time they log in from "
                        . "somewhere else. Please turn this setting on in Site Options");
                    throw new AccessDeniedException();
                }
            }
182 183 184 185 186 187 188 189
            else {
                if (!$isremote){
                    log_warn("usersuniquebyusername is turned off but remoteuser has not been set on for this institution: $institutionname. "
                        . "This is a security risk as users from different institutions with different IdPs can hijack "
                        . "each others accounts.  Fix this in the institution level auth/saml settings.");
                    throw new AccessDeniedException();
                }
            }
190 191 192 193
            if ($isremote && !empty($email) && $this->config['loginlink']) {
                $user->find_by_email_address($email);
            }
            else if ($isremote) {
194 195 196 197 198
                $user->find_by_instanceid_username($this->instanceid, $remoteuser, $isremote);
            }
            else {
                $user->find_by_username($remoteuser);
            }
199 200 201 202 203 204 205 206 207 208 209 210

            if ($user->get('suspendedcusr')) {
                die_info(get_string('accountsuspended', 'mahara', strftime(get_string('strftimedaydate'), $user->get('suspendedctime')), $user->get('suspendedreason')));
            }

            if ('1' == $this->config['updateuserinfoonlogin']) {
                $update = true;
            }
        } catch (AuthUnknownUserException $e) {
            if (!empty($this->config['weautocreateusers'])) {
                $institution = new Institution($this->institution);
                if ($institution->isFull()) {
211
                    $institution->send_admin_institution_is_full_message();
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
                    throw new XmlrpcClientException('SSO attempt from ' . $institution->displayname . ' failed - institution is full');
                }
                $user = new User;
                $create = true;
            }
            else {
                log_debug("User authorisation request from SAML failed - "
                    . "remote user '$remoteuser' is unknown to us and auto creation of users is turned off");
                return false;
            }
        }

        /*******************************************/

        if ($create) {

            $user->passwordchange     = 1;
            $user->active             = 1;
            $user->deleted            = 0;

            $user->expiry             = null;
            $user->expirymailsent     = 0;
            $user->lastlogin          = time();
235

236 237 238
            $user->firstname          = $firstname;
            $user->lastname           = $lastname;
            $user->email              = $email;
239
            $user->studentid          = $studentid;
240

241 242
            // must have these values
            if (empty($firstname) || empty($lastname) || empty($email)) {
243
                throw new AccessDeniedException(get_string('errormissinguserattributes1', 'auth.saml', get_config('sitename')));
244 245
            }

246 247 248
            $user->authinstance       = empty($this->config['parent']) ? $this->instanceid : $this->parent;

            db_begin();
249
            $user->username           = get_new_username($remoteuser, 40);
250 251 252 253 254 255 256 257 258 259 260 261 262

            $user->id = create_user($user, array(), $institutionname, $this, $remoteuser);

            /*
             * We need to convert the object to a stdclass with its own
             * custom method because it uses overloaders in its implementation
             * and its properties wouldn't be visible to a simple cast operation
             * like (array)$user
             */
            $userobj = $user->to_stdclass();
            $userarray = (array)$userobj;
            db_commit();

263
            // Now we have fired the create event, we need to re-get the data
264 265 266 267
            // for this user
            $user = new User;
            $user->find_by_id($userobj->id);

268 269 270 271 272
            if (get_config('usersuniquebyusername')) {
                // Add them to the institution they have SSOed in by
                $user->join_institution($institutionname);
            }

273
        } elseif ($update) {
274 275 276 277 278 279 280 281 282 283 284
            if (! empty($firstname)) {
                set_profile_field($user->id, 'firstname', $firstname);
                $user->firstname = $firstname;
            }
            if (! empty($lastname)) {
                set_profile_field($user->id, 'lastname', $lastname);
                $user->lastname = $lastname;
            }
            if (! empty($email)) {
                set_profile_field($user->id, 'email', $email);
                $user->email = $email;
285
            }
286 287 288 289 290
            if (! empty($studentid)) {
                set_profile_field($user->id, 'studentid', $studentid);
                $user->studentid = $studentid;
            }

291 292 293
            $user->lastlastlogin      = $user->lastlogin;
            $user->lastlogin          = time();
        }
294
        $user->commit();
295 296 297 298 299 300


        /*******************************************/

        // We know who our user is now. Bring em back to life.
        $result = $USER->reanimate($user->id, $this->instanceid);
301
        log_debug("remote user '$remoteuser' is now reanimated as '{$USER->username}' ");
302 303 304 305
        $SESSION->set('authinstance', $this->instanceid);

        return true;
    }
306

307 308 309
    // ensure that a user is logged out of mahara and the SAML 2.0 IdP
    public function logout() {
        global $CFG, $USER, $SESSION;
310

311 312
        // logout of mahara
        $USER->logout();
313

314 315
        // tidy up the session for retries
        $SESSION->set('messages', array());
316
        $SESSION->set('wantsurl', null);
317

318
        // redirect for logout of SAML 2.0 IdP
319
        redirect($CFG->wwwroot.'/auth/saml/index.php?logout=1');
320
    }
321

322 323 324
    public function after_auth_setup_page_hook() {
        return;
    }
325 326 327 328

    public function needs_remote_username() {
        return $this->config['remoteuser'] || parent::needs_remote_username();
    }
329 330 331 332 333 334 335 336
}

/**
 * Plugin configuration class
 */
class PluginAuthSaml extends PluginAuth {

    private static $default_config = array(
337 338 339 340 341 342 343 344 345 346 347 348 349 350
        'user_attribute'         => '',
        'weautocreateusers'      => 0,
        'firstnamefield'         => '',
        'surnamefield'           => '',
        'emailfield'             => '',
        'studentidfield'         => '',
        'updateuserinfoonlogin'  => 1,
        'institution'            => '',
        'institutionattribute'   => '',
        'institutionvalue'       => '',
        'institutionregex'       => 0,
        'remoteuser'             => 1,
        'loginlink'              => 0,
        'institutionidpentityid' => '',
351
        'active'                 => 1,
352 353
        'authloginmsg'           => '',
        'metarefresh_metadata_url'         => '',
354
    );
355

356 357 358 359 360 361 362 363 364 365 366 367 368 369 370
    public static function get_cron() {
        return array(
            (object)array(
                'callfunction' => 'auth_saml_refresh_cron',
                'minute' => '30',
                'hour' => '*',
            ),
        );
    }

    /*
     * This will trigger the simplesamlphp metadata module to do a refresh
     * in a similar way to as if we had configured a simplesamlphp web cron
     */
    public static function auth_saml_refresh_cron() {
371 372 373 374 375 376 377 378 379
        // we only want to run this if there are any saml instances containing the metarefresh_metadata_url
        if ($urls = get_records_sql_array("SELECT ai.id FROM {auth_instance} ai
                                           JOIN {auth_instance_config} aic ON aic.instance = ai.id
                                           WHERE ai.authname = 'saml'
                                           AND ai.active = 1
                                           AND aic.field = 'metarefresh_metadata_url'
                                           AND (aic.value IS NOT NULL and aic.value != '')", array())) {
            Metarefresh::metadata_refresh_hook();
        }
380 381
    }

382 383 384 385
    public static function can_be_disabled() {
        return true;
    }

386 387 388 389
    public static function is_active() {
        return get_field('auth_installed', 'active', 'name', 'saml');
    }

390 391 392 393
    public static function has_config() {
        return true;
    }

394 395
    public static function install_auth_default() {
        // Set library version to download
396
        set_config_plugin('auth', 'saml', 'version', '1.16.3');
397 398
    }

399 400 401
    private static function create_certificates($numberofdays = 3650) {
        global $CFG;
        // Get the details of the first site admin and use it for setting up the certificate
402
        $userid = get_record_sql('SELECT id FROM {usr} WHERE "admin" = 1 AND deleted = 0 ORDER BY id LIMIT 1', array());
403 404 405 406 407 408 409 410 411 412 413
        $id = $userid->id;
        $user = new User;
        $user->find_by_id($id);

        $country = get_profile_field($id, 'country');
        $town = get_profile_field($id, 'town');
        $city = get_profile_field($id, 'city');
        $industry = get_profile_field($id, 'industry');
        $occupation = get_profile_field($id, 'occupation');

        $dn = array(
414
            'commonName' => ($user->get('username') ? substr($user->get('username'), 0, 64) : 'Mahara'),
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
            'countryName' => ($country ? strtoupper($country) : 'NZ'),
            'localityName' => ($town ? $town : 'Wellington'),
            'emailAddress' => ($user->get('email') ? $user->get('email') : $CFG->noreplyaddress),
            'organizationName' => ($industry ? $industry : get_config('sitename')),
            'stateOrProvinceName' => ($city ? $city : 'Wellington'),
            'organizationalUnitName' => ($occupation ? $occupation : 'Mahara'),
        );

        $privkeypass = get_config('sitename');
        $privkey = openssl_pkey_new();
        $csr     = openssl_csr_new($dn, $privkey);
        $sscert  = openssl_csr_sign($csr, null, $privkey, $numberofdays);
        openssl_x509_export($sscert, $publickey);
        openssl_pkey_export($privkey, $privatekey, $privkeypass);

        // Write Private Key and Certificate files to disk.
        // If there was a generation error with either explode.
        if (empty($privatekey)) {
            throw new Exception(get_string('nullprivatecert', 'auth.saml'), 1);
        }
        if (empty($publickey)) {
            throw new Exception(get_string('nullpubliccert', 'auth.saml'), 1);
        }

        if ( !file_put_contents(AuthSaml::get_certificate_path() . 'server.pem', $privatekey) ) {
            throw new Exception(get_string('nullprivatecert', 'auth.saml'), 1);
        }
        if ( !file_put_contents(AuthSaml::get_certificate_path() . 'server.crt', $publickey) ) {
            throw new Exception(get_string('nullpubliccert', 'auth.saml'), 1);
        }
    }

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
    /*
     * Return an array of signature algorithms in a form suitable for feeding into a dropdown form
     */
    public static function get_valid_saml_signature_algorithms() {
        $return = array();
        $return['http://www.w3.org/2001/04/xmldsig-more#rsa-sha256'] = get_string('sha256', 'auth.saml');
        $return['http://www.w3.org/2001/04/xmldsig-more#rsa-sha384'] = get_string('sha384', 'auth.saml');
        $return['http://www.w3.org/2001/04/xmldsig-more#rsa-sha512'] = get_string('sha512', 'auth.saml');
        $return['http://www.w3.org/2000/09/xmldsig#rsa-sha1'] = get_string('sha1', 'auth.saml');

        return $return;
    }

    /*
     * Return a sensible default signature algorithm for simplesamlphp config
     */
    public static function get_default_saml_signature_algorithm() {
        //Sha1 is deprecated so we default to something more sensible
        return 'http://www.w3.org/2001/04/xmldsig-more#rsa-sha256';
    }

    /*
     * Check if a given value is a valid signature algorithm for configuration
     * in simplesamlphp
     */
    public static function is_valid_saml_signature_algorithm($value) {
        $valids = self::get_valid_saml_signature_algorithms();
        return array_key_exists($value, $valids);
    }

    /*
     * Get the configured signature algorithm, falling back to the default if
     * no valid value can be found or no value is set
     */
    public static function get_config_saml_signature_algorithm() {
        $signaturealgo = get_config_plugin('auth', 'saml', 'sigalgo');
        if (empty($signaturealgo) || !self::is_valid_saml_signature_algorithm($signaturealgo)) {
                $signaturealgo = self::get_default_saml_signature_algorithm();
        }

        return $signaturealgo;
    }

490 491
    public static function get_config_options() {

492 493 494 495 496
        $spentityid = get_config_plugin('auth', 'saml', 'spentityid');
        if (empty($spentityid)) {
            $spentityid = $_SERVER['HTTP_HOST'] . '/mahara';
        }

497 498 499
        $signaturealgo = self::get_config_saml_signature_algorithm();
        $possiblealgos = self::get_valid_saml_signature_algorithms();

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
        // first time - create it
        if (!file_exists(AuthSaml::get_certificate_path() . 'server.crt')) {
            error_log("auth/saml: Creating the certificate for the first time");
            self::create_certificates();
        }
        $cert = file_get_contents(AuthSaml::get_certificate_path() . 'server.crt');
        $pem = file_get_contents(AuthSaml::get_certificate_path() . 'server.pem');
        if (empty($cert) || empty($pem)) {
            // bad cert - get rid of it
            unlink(AuthSaml::get_certificate_path() . 'server.crt');
            unlink(AuthSaml::get_certificate_path() . 'server.pem');
        }
        else {
            $privatekey = openssl_pkey_get_private($pem);
            $publickey  = openssl_pkey_get_public($cert);
            $data = openssl_pkey_get_details($publickey);
            // Load data from the current certificate.
            $data = openssl_x509_parse($cert);
        }

        // Calculate date expirey interval.
        $date1 = date("Y-m-d\TH:i:s\Z", str_replace ('Z', '', $data['validFrom_time_t']));
        $date2 = date("Y-m-d\TH:i:s\Z", str_replace ('Z', '', $data['validTo_time_t']));
        $datetime1 = new DateTime($date1);
        $datetime2 = new DateTime($date2);
        $interval = $datetime1->diff($datetime2);
        $expirydays = $interval->format('%a');

528 529 530 531 532 533 534 535 536
        $elements = array(
            'authname' => array(
                'type'  => 'hidden',
                'value' => 'saml',
            ),
            'authglobalconfig' => array(
                'type'  => 'hidden',
                'value' => 'saml',
            ),
537
            'spentityid' => array(
538 539
                'type'  => 'text',
                'size' => 50,
540
                'title' => get_string('spentityid', 'auth.saml'),
541 542 543
                'rules' => array(
                    'required' => true,
                ),
544
                'defaultvalue' => $spentityid,
545 546
                'help'  => true,
            ),
547 548 549 550 551 552
            'metadata' => array(
                'type'  => 'html',
                'class' => 'htmldescription',
                'title' => get_string('spmetadata', 'auth.saml'),
                'value' => self::is_usable() ? get_string('metadatavewlink', 'auth.saml', get_config('wwwroot') . 'auth/saml/sp/metadata.php?output=xhtml') : get_string('ssphpnotconfigured', 'auth.saml'),
            ),
553 554 555 556 557 558 559
            'sigalgo' => array(
                'type' => 'select',
                'title' => get_string('sigalgo', 'auth.saml'),
                'options' => $possiblealgos,
                'defaultvalue' => $signaturealgo,
                'help' => true,
            ),
560 561
            'makereallysure' => array(
                'type'         => 'html',
562
                'value'        => "<script>jQuery(function() {     jQuery('#pluginconfig_save').on('click', function() {
563
                return confirm('" . get_string('reallyreallysure1', 'auth.saml') . "');
564
            });});</script>",
565
            ),
566 567
            'certificate' => array(
                                'type' => 'fieldset',
568
                                'legend' => get_string('certificate1', 'auth.saml'),
569 570 571
                                'elements' =>  array(
                                                'protos_help' =>  array(
                                                'type' => 'html',
572
                                                'value' => '<div><p>' . get_string('manage_certificate2', 'auth.saml') . '</p></div>',
573 574 575 576 577 578 579 580 581
                                                ),

                                                'pubkey' => array(
                                                    'type'         => 'html',
                                                    'value'        => '<h3 class="title">' . get_string('publickey','admin') . '</h3>' .
                                                      '<pre style="font-size: 0.7em; white-space: pre;">' . $cert . '</pre>'
                                                ),
                                                'sha1fingerprint' => array(
                                                    'type'         => 'html',
582
                                                    'value'        => '<div><p>' . get_string('sha1fingerprint', 'auth.webservice', auth_saml_openssl_x509_fingerprint($cert, "sha1")) . '</p></div>',
583 584 585
                                                ),
                                                'md5fingerprint' => array(
                                                    'type'         => 'html',
586
                                                    'value'        => '<div><p>' . get_string('md5fingerprint', 'auth.webservice', auth_saml_openssl_x509_fingerprint($cert, "md5")) . '</p></div>',
587 588 589 590 591 592 593 594 595 596 597
                                                ),
                                                'expires' => array(
                                                    'type'         => 'html',
                                                    'value'        => '<div><p>' . get_string('publickeyexpireson', 'auth.webservice',
                                                    format_date($data['validTo_time_t']) . " (" . $expirydays . " days)") . '</p></div>'
                                                ),
                                            ),
                                'collapsible' => false,
                                'collapsed'   => false,
                                'name' => 'activate_webservices_networking',
                            ),
598 599
        );

600 601
        // check extensions are loaded
        $libchecks = '';
602
        // Make sure the simplesamlphp files have been installed via 'make ssphp'
603
        if (!self::is_simplesamlphp_installed()) {
604 605
            $libchecks .= '<li>' . get_string('errorbadlib', 'auth.saml', get_config('docroot') .'auth/saml/extlib/simplesamlphp/vendor/autoload.php') . '</li>';
        }
606 607 608 609 610 611 612 613 614 615 616
        else {
            require(get_config('docroot') .'auth/saml/extlib/simplesamlphp/vendor/autoload.php');
            $config = SimpleSAML_Configuration::getInstance();

            //simplesaml version we install with 'make ssphp'
            $libversion = get_config_plugin('auth', 'saml', 'version');

            if (!empty($libversion) && $config->getVersion() != $libversion) {
                $libchecks .= '<li>' . get_string('errorupdatelib', 'auth.saml') . '</li>';
            }
        }
617 618 619
        // Make sure we can use a valid session handler with simplesamlphp as 'phpsession' doesn't work correctly in many situations
        if (!self::is_usable()) {
            $libchecks .= '<li>' . get_string_php_version('errornovalidsessionhandler', 'auth.saml') . '</li>';
620 621 622 623 624 625 626 627 628
        }
        if (!empty($libchecks)) {
            $libcheckstr = '<div class="alert alert-danger"><ul class="unstyled">' . $libchecks . '</ul></div>';
            $elements = array_merge(array('libchecks' => array(
                                                'type' => 'html',
                                                'value' => $libcheckstr,
                                     )), $elements);
        }

629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658
        // Show the current metadata installed on the site so we can delete them
        // We need to handle this outside the current pieform as we don't want to submit that and re-create a new certificate
        $disco = self::get_raw_disco_list();
        if (count($disco['list']) > 0) {
            $discoused = array();
            if ($discousedtmp  = get_records_sql_array("SELECT i.name, i.displayname, aic.value,
                                                         CASE WHEN i.name = 'mahara' THEN 1 ELSE 0 END AS site
                                                        FROM {auth_instance} ai
                                                        JOIN {auth_instance_config} aic ON aic.instance = ai.id
                                                        JOIN {institution} i ON i.name = ai.institution
                                                        WHERE ai.authname = ? and field = ?", array('saml', 'institutionidpentityid'))) {
                // turn $discoused into useful array structure
                foreach ($discousedtmp as $used) {
                    $discoused[$used->value][] = $used;
                }
            }

            list($cols, $html) = self::idptable($disco['list'], null, $discoused, true);
            $smarty = smarty_core();
            $smarty->assign('html', $html);
            $smarty->assign('cols', $cols);
            $out = $smarty->fetch('auth:saml:idptableconfig.tpl');
            $elements = array_merge($elements , array(
                                        'idptable' => array(
                                            'type' => 'html',
                                            'value' => $out,
                                        )
                                    ));
        }

659 660 661 662 663
        return array(
            'elements' => $elements,
        );
    }

664 665 666 667 668 669 670
    public static function validate_config_options(Pieform $form, $values) {
        if (empty($values['spentityid'])) {
            $form->set_error('spentityid', get_string('errorbadspentityid', 'auth.saml', $values['spentityid']));
        }
    }

    public static function save_config_options(Pieform $form, $values) {
671
        delete_records_select('auth_config', 'plugin = ? AND field NOT LIKE ?', array('saml', 'version'));
672
        $configs = array('spentityid', 'sigalgo');
673 674 675 676 677 678 679 680 681 682
        foreach ($configs as $config) {
            set_config_plugin('auth', 'saml', $config, $values[$config]);
        }

        // generate new certificates
        error_log("auth/saml: Creating new certificates");
        self::create_certificates();

    }

683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782
    public static function idptable($list, $preferred = array(), $institutions = array(), $showdelete = false) {
        $idps = array();
        $lang = current_language();
        $lang = explode('.', $lang);
        $lang = strtolower(array_shift($lang));
        $haslogos = $hasinstitutions = $hasdelete = false;
        foreach ($list as $entityid => $value) {
            $candelete = false;
            $desc = $name = $entityid;
            if (isset($value['description'][$lang])) {
                $desc = $value['description'][$lang];
            }
            if (isset($value['name'][$lang])) {
                $name = $value['name'][$lang];
            }
            $idplogo = array();
            if (isset($value['UIInfo']) && isset($value['UIInfo']['Logo'])) {
                $haslogos = true;
                // Fetch logo from provider if given
                $logos = $value['UIInfo']['Logo'];
                foreach ($logos as $logo) {
                    if (isset($logo['lang']) && $logo['lang'] == $lang) {
                        $idplogo = $logo;
                        break;
                    }
                }
                // None matching the lang wanted so use the first one
                if (empty($idplogo)) {
                    $idplogo = $logos[0];
                }
            }
            $insts = array();
            if (!empty($institutions) && !empty($institutions[$entityid])) {
                $hasinstitutions = true;
                $insts = $institutions[$entityid];
            }
            else if ($showdelete) {
                $hasdelete = true;
                $candelete = true;
            }

            $idps[]= array('idpentityid' => $entityid, 'name' => $name, 'description' => $desc, 'logo' => $idplogo, 'institutions' => $insts, 'delete' => $candelete);
        }

        usort($idps, function($a, $b) {
            return $a['name'] > $b['name'];
        });
        $idps = array(
                      'count'   => count($idps),
                      'limit'   => count($idps),
                      'offset'  => 1,
                      'data'    => $idps,
                      );

        $cols = array(
            'logo' => array(
                'name' => get_string('logo', 'auth.saml'),
                'template' => 'auth:saml:idplogo.tpl',
                'class' => 'short',
                'sort' => false
            ),
            'idpentityid' => array(
                'name' => get_string('idpentityid', 'auth.saml'),
                'template' => 'auth:saml:idpentityid.tpl',
                'class' => 'col-sm-3',
                'sort' => false
            ),
            'description' => array(
                'name' => get_string('idpprovider','auth.saml'),
                'sort' => false
            ),
            'institutions' => array(
                'name' => get_string('institutions', 'auth.saml'),
                'template' => 'auth:saml:idpinstitutions.tpl',
                'sort' => false
            ),
            'delete' => array(
                'template' => 'auth:saml:idpdelete.tpl',
                'sort' => false
            ),
        );
        if ($haslogos === false) {
            unset($cols['logo']);
        }
        if ($hasinstitutions === false) {
            unset($cols['institutions']);
        }
        if ($hasdelete === false) {
            unset($cols['delete']);
        }

        $smarty = smarty_core();
        $smarty->assign('results', $idps);
        $smarty->assign('cols', $cols);
        $smarty->assign('pagedescriptionhtml', get_string('selectidp', 'auth.saml'));
        $html = $smarty->fetch('auth:saml:idptable.tpl');

        return array($cols, $html);
    }

783 784 785 786 787
    public static function has_instance_config() {
        return true;
    }

    public static function is_usable() {
788 789 790
        if (!self::is_simplesamlphp_installed()) {
            return false;
        }
791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819
        $ishandler = false;

        switch (get_config('ssphpsessionhandler')) {
            case 'memcache':
                //make people use memcached, not memcache
                throw new ConfigSanityException(get_string('memcacheusememcached', 'error'));
                break;
            case 'memcached':
                if (self::is_memcache_configured()) {
                    $ishandler = true;
                    break;
                }
            case 'redis':
                if (self::is_redis_configured()) {
                    $ishandler = true;
                    break;
                }
            case 'sql':
                if (self::is_sql_configured()) {
                    $ishandler = true;
                    break;
                }
            default:
                // Check Redis
                $ishandler = self::is_redis_configured();
                // And check Memcache if no Redis
                $ishandler = $ishandler ? $ishandler : self::is_memcache_configured();
                // And check Sql if no Memcache
                $ishandler = $ishandler ? $ishandler : self::is_sql_configured();
820 821
        }

822
        return $ishandler;
823 824
    }

825 826 827 828 829 830 831 832 833
    public static function is_simplesamlphp_installed() {
        return file_exists(get_config('docroot') . 'auth/saml/extlib/simplesamlphp/vendor/autoload.php');
    }

    public static function init_simplesamlphp() {
        if (!self::is_simplesamlphp_installed()) {
            throw new AuthInstanceException(get_string('errorbadlib', 'auth.saml', get_config('docroot') . 'auth/saml/extlib/simplesamlphp/vendor/autoload.php'));
        }

834 835 836 837 838
        // Tell SSP that we are on 443 if we are terminating SSL elsewhere.
        if (get_config('sslproxy')) {
            $_SERVER['SERVER_PORT'] = '443';
        }

839 840 841 842 843 844 845 846
        require_once(get_config('docroot') . 'auth/saml/extlib/simplesamlphp/vendor/autoload.php');
        require_once(get_config('docroot') . 'auth/saml/extlib/_autoload.php');

        SimpleSAML_Configuration::init(get_config('docroot') . 'auth/saml/config');
    }
    public static function is_memcache_configured() {
        $is_configured = false;

847
        if (extension_loaded('memcached')) {
848
            foreach (self::get_memcache_servers() as $server) {
849
                $memcached = new Memcached;
850 851

                if (!empty($server['hostname']) && !empty($server['port'])) {
852 853 854 855 856
                    $memcached->addServer($server['hostname'], $server['port']);
                    // addServer doesn't make a connection to the server
                    // but if the server is added, but not running pid will be -1
                    $server_stats = $memcached->getStats();
                    if ($server_stats[$server['hostname'] . ":" . $server['port']]['pid'] > 0) {
857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887
                        $is_configured = true;
                        break;
                    }
                }
            }
        }
        return $is_configured;
    }

    public static function get_memcache_servers() {
        $memcache_servers = array();

        $servers = get_config('memcacheservers');

        if (empty($servers)) {
            $servers = 'localhost';
        }

        $servers = explode(',', $servers);

        foreach ($servers as $server) {
            $url = parse_url($server);
            $host = !empty($url['host']) ? $url['host'] : $url['path'];
            $port = !empty($url['port']) ? $url['port'] : 11211;

            $memcache_servers[] = array('hostname' => $host, 'port' => $port);
        }

        return $memcache_servers;
    }

888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924
    public static function is_redis_configured() {
        return (bool) PluginAuthSaml::get_redis_master();
    }

    public static function get_redis_master() {
        $master = null;
        if (extension_loaded('redis')) {
            foreach (self::get_redis_servers() as $server) {
                if (!empty($server['server']) && !empty($server['mastergroup']) && !empty($server['prefix'])) {
                    require_once(get_config('libroot') . 'redis/sentinel.php');
                    $sentinel = new sentinel($server['server']);
                    $master = $sentinel->get_master_addr($server['mastergroup']);
                }
            }
        }
        return $master;
    }

    public static function get_redis_config() {
        $servers = PluginAuthSaml::get_redis_servers();
        $master = PluginAuthSaml::get_redis_master();
        return array('host' => $master->ip,
                     'port' => (int)$master->port,
                     'prefix' => $servers[0]['prefix']
                    );
    }

    public static function get_redis_servers() {
        $redissentinelservers = get_config('redissentinelservers');
        $redismastergroup = get_config('redismastergroup');
        $redisprefix = get_config('redisprefix');
        $redis_servers[] = array('server' => $redissentinelservers,
                                 'mastergroup' => $redismastergroup,
                                 'prefix' => $redisprefix);
        return $redis_servers;
    }

925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943
    public static function is_sql_configured() {
        $config = PluginAuthSaml::get_sql_config();
        try {
            $connection = new PDO($config['dsn'], $config['username'], $config['password']);
            return true;
        }
        catch (PDOException $e) {
            return false;
        }
    }

    public static function get_sql_config() {
        return array('dsn' => get_config('ssphpsqldsn'),
                     'username' => get_config('ssphpsqlusername'),
                     'password' => get_config('ssphpsqlpassword'),
                     'prefix' => get_config('ssphpsqlprefix'),
                    );
    }

944 945 946 947 948 949 950 951 952 953 954 955 956
    public static function get_idps($xml) {
        $xml = new SimpleXMLElement($xml);
        $xml->registerXPathNamespace('md',   'urn:oasis:names:tc:SAML:2.0:metadata');
        $xml->registerXPathNamespace('mdui', 'urn:oasis:names:tc:SAML:metadata:ui');
        // Find all IDPSSODescriptor elements and then work back up to the entityID.
        $idps = $xml->xpath('//md:EntityDescriptor[//md:IDPSSODescriptor]');
        $entityid = null;
        if ($idps && isset($idps[0])) {
            $entityid = (string)$idps[0]->attributes('', true)->entityID[0];
        }
        return array($entityid, $idps);
    }

957 958 959 960 961 962
    public static function get_raw_disco_list() {
        PluginAuthSaml::init_simplesamlphp();
        $discoHandler = new PluginAuthSaml_IdPDisco(array('saml20-idp-remote', 'shib13-idp-remote'), 'saml');
        return $discoHandler->getTheIdPs();
    }

963 964 965 966
    public static function get_disco_list($lang = null, $entityidps = array()) {
        if (empty($lang)) {
            $lang = current_language();
        }
967 968

        $disco = self::get_raw_disco_list();
969 970 971 972 973 974 975 976 977 978 979 980
        if (count($disco['list']) > 0) {
            $lang = explode('.', $lang);
            $lang = strtolower(array_shift($lang));
            foreach($disco['list'] as $idp) {
                $idpname = (isset($idp['name'][$lang])) ? $idp['name'][$lang] : $idp['entityid'];
                $entityidps[$idp['entityid']] = $idpname;
            }
            return $entityidps;
        }
        return false;
    }

981
    public static function get_instance_config_options($institution, $instance = 0) {
982 983 984 985 986
        if (!class_exists('SimpleSAML_XHTML_IdPDisco')) {
            global $SESSION;
            $SESSION->add_error_msg(get_string('errorssphpsetup', 'auth.saml'));
            redirect(get_config('wwwroot') . 'admin/users/institutions.php?i=' . $institution);
        }
987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002

        if ($instance > 0) {
            $default = get_record('auth_instance', 'id', $instance);
            if ($default == false) {
                throw new SystemException('Could not find data for auth instance ' . $instance);
            }
            $current_config = get_records_menu('auth_instance_config', 'instance', $instance, '', 'field, value');

            if ($current_config == false) {
                $current_config = array();
            }
            foreach (self::$default_config as $key => $value) {
                if (array_key_exists($key, $current_config)) {
                    self::$default_config[$key] = $current_config[$key];
                }
            }
1003
            if (empty(self::$default_config['institutionvalue'])) {
1004 1005
                self::$default_config['institutionvalue'] = $institution;
            }
1006 1007 1008
            self::$default_config['active'] = $default->active;
        }
        else {
1009 1010
            $default = new stdClass();
            $default->instancename = '';
1011
            $default->active = 1;
1012 1013
        }

1014 1015 1016
        // lookup the institution metadata
        $entityid = "";
        self::$default_config['institutionidp'] = "";
1017 1018 1019 1020 1021 1022 1023
        if (!empty(self::$default_config['institutionidpentityid'])) {
            $idpfile = AuthSaml::prepare_metadata_path(self::$default_config['institutionidpentityid']);
            if (file_exists($idpfile)) {
                $rawxml = file_get_contents($idpfile);
                if (empty($rawxml)) {
                    // bad metadata - get rid of it
                    unlink($idpfile);
1024 1025
                }
                else {
1026 1027 1028 1029 1030 1031 1032 1033
                    list ($entityid, $idps) = self::get_idps($rawxml);
                    if ($entityid) {
                        self::$default_config['institutionidp'] = $rawxml;
                    }
                    else {
                        // bad metadata - get rid of it
                        unlink($idpfile);
                    }
1034 1035 1036 1037 1038 1039 1040 1041
                }
            }
        }

        $idp_title = get_string('institutionidp', 'auth.saml', $institution);
        if ($entityid) {
            $idp_title .= " (" . $entityid . ")";
        }
1042 1043 1044
        $entityidps = array();
        $entityidp_hiddenlabel = true;
        // Fetch the idp info via disco
1045 1046 1047
        $discolist = self::get_disco_list();
        if ($discolist) {
            $entityidps += $discolist;
1048 1049 1050 1051 1052 1053 1054 1055
            $entityidp_hiddenlabel = false;
        }
        asort($entityidps);
        // add the 'New' option to the top of the list
        $entityidps = array('new' => get_string('newidpentity', 'auth.saml')) + $entityidps;

        $idpselectjs = <<< EOF
<script type="application/javascript">
1056
jQuery(function($) {
1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075

    function update_idp_label(idp) {
        var idplabel = $('label[for="auth_config_institutionidp"]').html();
        // remove the idp entity from string
        if (idplabel.lastIndexOf('(') != -1) {
            idplabel = idplabel.substring(0, idplabel.lastIndexOf('('));
        }
        // add in new one
        if (idp) {
            idplabel = idplabel.trim() + ' (' + idp + ')';
        }
        $('label[for="auth_config_institutionidp"]').html(idplabel);
    }

    function update_idp_info(idp) {

        if (idp == 'new') {
            // clear the metadata box
            $('#auth_config_institutionidp').val('');
1076 1077
            // clear the entity url box
            $('#auth_config_metarefresh_metadata_url').val('');
1078 1079 1080
            update_idp_label(false);
        }
        else {
1081 1082
            // fetch the metadata info and update the textarea and url if configured
            sendjsonrequest(config.wwwroot + 'auth/saml/idpmetadata.json.php', {'idp': idp}, 'POST', function (data) {
1083 1084
                if (!data.error) {
                    $('#auth_config_institutionidp').val(data.data.metadata);
1085
                    $('#auth_config_metarefresh_metadata_url').val(data.data.metarefresh_metadata_url);
1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101
                }
            });
            update_idp_label(idp);
        }
    }

    // On change
    $('#auth_config_institutionidpentityid').on('change', function() {
        update_idp_info($(this).val());
    });
    // On load
    update_idp_info($('#auth_config_institutionidpentityid').val());
});
</script>
EOF;

1102 1103 1104 1105 1106
        $elements = array(
            'instance' => array(
                'type'  => 'hidden',
                'value' => $instance,
            ),
1107 1108 1109 1110
            'instancename' => array(
                'type'  => 'hidden',
                'value' => 'SAML',
            ),
1111 1112 1113 1114 1115 1116 1117 1118
            'institution' => array(
                'type'  => 'hidden',
                'value' => $institution,
            ),
            'authname' => array(
                'type'  => 'hidden',
                'value' => 'saml',
            ),
1119 1120 1121 1122 1123
            'active' => array(
                'type'  => 'switchbox',
                'title' => get_string('active', 'auth'),
                'defaultvalue' => (int) self::$default_config['active'],
            ),
1124 1125 1126 1127 1128 1129 1130
            'institutionidpentityid' => array(
                'type'  => 'select',
                'title' => get_string('institutionidpentity', 'auth.saml'),
                'options' => $entityidps,
                'defaultvalue' => ($entityid ? $entityid : 'new'),
                'hiddenlabel' => $entityidp_hiddenlabel,
            ),
1131 1132 1133 1134 1135 1136 1137 1138 1139 1140
            'metarefresh_metadata_url' => array(
                'type'  => 'text',
                'size' => 100,
                'title' => get_string('metarefresh_metadata_url', 'auth.saml'),
                'rules' => array(
                    'required' => false,
                ),
                'defaultvalue' => self::$default_config['metarefresh_metadata_url'],
                'help'  => true,
            ),
1141 1142 1143 1144 1145 1146 1147
            'institutionidp' => array(
                'type'  => 'textarea',
                'title' => $idp_title,
                'rows' => 10,
                'cols' => 80,
                'defaultvalue' => self::$default_config['institutionidp'],
                'help' => true,
1148
                'class' => 'under-label',
1149
            ),
1150 1151 1152 1153
            'idpselectjs' => array(
                'type'         => 'html',
                'value'        => $idpselectjs,
            ),
1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172
            'institutionattribute' => array(
                'type'  => 'text',
                'title' => get_string('institutionattribute', 'auth.saml', $institution),
                'rules' => array(
                    'required' => true,
                ),
                'defaultvalue' => self::$default_config['institutionattribute'],
                'help' => true,
            ),
            'institutionvalue' => array(
                'type'  => 'text',
                'title' => get_string('institutionvalue', 'auth.saml'),
                'rules' => array(
                'required' => true,
                ),
                'defaultvalue' => self::$default_config['institutionvalue'],
                'help' => true,
            ),
            'institutionregex' => array(
1173
                'type'         => 'switchbox',
1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186
                'title' => get_string('institutionregex', 'auth.saml'),
                'defaultvalue' => self::$default_config['institutionregex'],
                'help' => true,
            ),
            'user_attribute' => array(
                'type'  => 'text',
                'title' => get_string('userattribute', 'auth.saml'),
                'rules' => array(
                    'required' => true,
                ),
                'defaultvalue' => self::$default_config['user_attribute'],
                'help' => true,
            ),
1187
            'remoteuser' => array(
1188
                'type'         => 'switchbox',
1189 1190 1191 1192
                'title' => get_string('remoteuser', 'auth.saml'),
                'defaultvalue' => self::$default_config['remoteuser'],
                'help'  => true,
            ),
1193
            'loginlink' => array(
1194
                'type'         => 'switchbox',
1195 1196 1197 1198 1199
                'title' => get_string('loginlink', 'auth.saml'),
                'defaultvalue' => self::$default_config['loginlink'],
                'disabled' => (self::$default_config['remoteuser'] ? false : true),
                'help'  => true,
            ),
1200
            'updateuserinfoonlogin' => array(
1201
                'type'         => 'switchbox',
1202 1203 1204 1205 1206
                'title' => get_string('updateuserinfoonlogin', 'auth.saml'),
                'defaultvalue' => self::$default_config['updateuserinfoonlogin'],
                'help'  => true,
            ),
            'weautocreateusers' => array(
1207
                'type'         => 'switchbox',
1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229
                'title' => get_string('weautocreateusers', 'auth.saml'),
                'defaultvalue' => self::$default_config['weautocreateusers'],
                'help'  => true,
            ),
            'firstnamefield' => array(
                'type'  => 'text',
                'title' => get_string('samlfieldforfirstname', 'auth.saml'),
                'defaultvalue' => self::$default_config['firstnamefield'],
                'help'  => true,
            ),
            'surnamefield' => array(
                'type'  => 'text',
                'title' => get_string('samlfieldforsurname', 'auth.saml'),
                'defaultvalue' => self::$default_config['surnamefield'],
                'help'  => true,
            ),
            'emailfield' => array(
                'type'  => 'text',
                'title' => get_string('samlfieldforemail', 'auth.saml'),
                'defaultvalue' => self::$default_config['emailfield'],
                'help' => true,
            ),
1230 1231 1232 1233 1234 1235
            'studentidfield' => array(
                'type' => 'text',
                'title' => get_string('samlfieldforstudentid', 'auth.saml'),
                'defaultvalue' => self::$default_config['studentidfield'],
                'help' => true,
            ),
1236 1237 1238
            'authloginmsg' => array(
                'type'         => 'wysiwyg',
                'rows'         => 10,
1239 1240
                'cols'         => 50,
                'title'        => get_string('samlfieldauthloginmsg', 'auth.saml'),
1241 1242 1243
                'description'  => get_string('authloginmsgnoparent', 'auth'),
                'defaultvalue' => self::$default_config['authloginmsg'],
                'help'         => true,
1244
                'class'        => 'under-label-help',
1245
            ),
1246 1247 1248 1249
        );

        return array(
            'elements' => $elements,
1250
            'renderer' => 'div'
1251 1252 1253
        );
    }

1254
    public static function validate_instance_config_options($values, Pieform $form) {
1255

1256
        // only allow remoteuser to be unset if usersuniquebyusername is NOT set
1257
        if (!get_config('usersuniquebyusername') && !$values['remoteuser']) {
1258
            $form->set_error('remoteuser', get_string('errorremoteuser1', 'auth.saml'));
1259
        }
1260

1261 1262
        if (!empty($values['institutionidp'])) {
            try {
1263 1264
                list ($entityid, $idps) = self::get_idps($values['institutionidp']);
                if (!$entityid) {
1265 1266 1267 1268 1269 1270 1271
                    throw new Exception("Could not find entityId", 1);
                }
            }
            catch (Exception $e) {
                $form->set_error('institutionidp', get_string('errorbadmetadata', 'auth.saml'));
            }
        }
1272 1273 1274
        else {
            $form->set_error('institutionidpentityid', get_string('errormissingmetadata', 'auth.saml'));
        }
1275

1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286
        // If we're using Mahara usernames (usr.username) instead of remote usernames
        // (auth_remote_user.remoteusername), then autocreation cannot be enabled if any
        // institutions have registration enabled.
        //
        // This is because a user self-registering with another institution might pick
        // a username that matches the username from this SAML service, allowing them
        // to highjack someone else's account.
        //
        // (see the comments in the request_user_authorise function above).
        if ((!$values['remoteuser']) && ($values['weautocreateusers']) && ($institutions = get_column('institution', 'name', 'registerallowed', '1'))) {
            $form->set_error('weautocreateusers', get_string('errorregistrationenabledwithautocreate1', 'auth.saml'));
1287
        }
1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298

        // If enabled "We auto-create users" check that all required fields for that are set.
        if ($values['weautocreateusers']) {
            $required= array('firstnamefield', 'surnamefield', 'emailfield');
            foreach ($required as $required_field) {
                if (empty($values[$required_field])) {
                    $form->set_error($required_field, get_string('errorextrarequiredfield', 'auth.saml'));
                }
            }
        }

1299 1300 1301 1302 1303 1304 1305
        $dup = get_records_sql_array('SELECT COUNT(instance) AS instance FROM {auth_instance_config}
                                          WHERE ((field = \'institutionattribute\' AND value = ?) OR
                                                 (field = \'institutionvalue\' AND value = ?)) AND
                                                 instance IN (SELECT id FROM {auth_instance} WHERE authname = \'saml\' AND id != ?)
                                          GROUP BY instance
                                          ORDER BY instance',
                                      array($values['institutionattribute'], $values['institutionvalue'], $values['instance']));
1306 1307 1308 1309 1310 1311 1312
        if (is_array($dup)) {
            foreach ($dup as $instance) {
                if ($instance->instance >= 2) {
                    // we already have an authinstance with these same values
                    $form->set_error('institutionattribute', get_string('errorbadinstitutioncombo', 'auth.saml'));
                    break;
                }
1313 1314
            }
        }
1315
    }
1316

1317
    public static function save_instance_config_options($values, Pieform $form) {
1318
        global $SESSION;
1319

1320
        $authinstance = new stdClass();
1321

1322 1323 1324 1325
        if ($values['instance'] > 0) {
            $values['create'] = false;
            $current = get_records_assoc('auth_instance_config', 'instance', $values['instance'], '', 'field, value');
            $authinstance->id = $values['instance'];
1326 1327
        }
        else {
1328 1329
            $values['create'] = true;
            $lastinstance = get_records_array('auth_instance', 'institution', $values['institution'], 'priority DESC', '*', '0', '1');
1330

1331 1332
            if ($lastinstance == false) {
                $authinstance->priority = 0;
1333 1334
            }
            else {
1335
                $authinstance->priority = $lastinstance[0]->priority + 1;
1336
            }
1337
        }
1338

1339 1340
        $authinstance->institution  = $values['institution'];
        $authinstance->authname     = $values['authname'];
1341
        $authinstance->active       = (int) $values['active'];
1342
        $authinstance->instancename = $values['authname'];
1343

1344 1345 1346 1347 1348 1349
        if ($values['create']) {
            $values['instance'] = insert_record('auth_instance', $authinstance, 'id', true);
        }
        else {
            update_record('auth_instance', $authinstance, array('id' => $values['instance']));
        }
1350

1351 1352 1353
        if (empty($current)) {
            $current = array();
        }
1354

1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386
        // grab the entityId from the metadata
        list ($entityid, $idps) = self::get_idps($values['institutionidp']);

        $changedxml = false;
        if ($values['institutionidpentityid'] != 'new') {
            $existingidpfile = AuthSaml::prepare_metadata_path($values['institutionidpentityid']);
            if (file_exists($existingidpfile)) {
                $rawxml = file_get_contents($existingidpfile);
                if ($rawxml != $values['institutionidp']) {
                    $changedxml = true;
                    // find out which institutions are using it
                    $duplicates = get_records_sql_array("
                        SELECT COUNT(aic.instance) AS instances
                        FROM {auth_instance_config} aic
                        JOIN {auth_instance} ai ON (ai.authname = 'saml' AND ai.id = aic.instance)
                        WHERE aic.field = 'institutionidpentityid' AND aic.value = ? AND aic.instance != ?",
                        array($values['institutionidpentityid'], $values['instance']));
                    if ($duplicates[0]->instances > 0) {
                        $SESSION->add_ok_msg(get_string('idpentityupdatedduplicates', 'auth.saml', $duplicates[0]->instances));
                    }
                    else {
                        $SESSION->add_ok_msg(get_string('idpentityupdated', 'auth.saml'));
                    }
                }
                else {
                    $SESSION->add_ok_msg(get_string('idpentityadded', 'auth.saml'));
                }
            }
            else {
                // existing idpfile not found so just save it
                $changedxml = true;
            }
1387 1388
        }
        else {
1389 1390 1391
           $values['institutionidpentityid'] = $entityid;
           $changedxml = true;
           $SESSION->add_ok_msg(get_string('idpentityadded', 'auth.saml'));
1392
        }
1393 1394 1395 1396 1397 1398 1399 1400
        self::$default_config = array(
            'user_attribute' => $values['user_attribute'],
            'weautocreateusers' => $values['weautocreateusers'],
            'loginlink' => $values['loginlink'],
            'remoteuser' => $values['remoteuser'],
            'firstnamefield' => $values['firstnamefield'],
            'surnamefield' => $values['surnamefield'],
            'emailfield' => $values['emailfield'],
1401
            'studentidfield' => $values['studentidfield'],
1402 1403 1404 1405
            'updateuserinfoonlogin' => $values['updateuserinfoonlogin'],
            'institutionattribute' => $values['institutionattribute'],
            'institutionvalue' => $values['institutionvalue'],
            'institutionregex' => $values['institutionregex'],
1406
            'institutionidpentityid' => $entityid,
1407
            'authloginmsg' => $values['authloginmsg'],
1408
            'metarefresh_metadata_url' => $values['metarefresh_metadata_url'],
1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421
        );

        foreach(self::$default_config as $field => $value) {
            $record = new stdClass();
            $record->instance = $values['instance'];
            $record->field    = $field;
            $record->value    = $value;

            if ($values['create'] || !array_key_exists($field, $current)) {
                insert_record('auth_instance_config', $record);
            }
            else {
                update_record('auth_instance_config', $record, array('instance' => $values['instance'], 'field' => $field));
1422 1423
            }
        }
1424

1425
        // save the institution config
1426 1427 1428
        if ($changedxml) {
            $idpfile = AuthSaml::prepare_metadata_path($values['institutionidpentityid']);
            file_put_contents($idpfile, $values['institutionidp']);
1429
        }
1430

1431 1432
        return $values;
    }
1433 1434 1435 1436 1437

    /**
     * Add "SSO Login" link below the normal login form.
     */
    public static function login_form_elements() {
1438
        $url = get_config('wwwroot') . 'auth/saml/index.php';
1439
        if (param_exists('login')) {
1440 1441 1442
            // We're on the transient login page. Redirect back to original page once we're done.
            $url .= '?wantsurl=' . urlencode(get_full_script_path());
        }
1443 1444
        $elements = array(
            'loginsaml' => array(
1445
                'value' => '<div class="login-externallink"><a class="btn btn-primary btn-xs" href="' . $url . '">' . get_string('login', 'auth.saml') . '</a></div>'
1446 1447 1448 1449
            )
        );
        return $elements;
    }
1450 1451 1452 1453

    public static function need_basic_login_form() {
        return false;
    }
1454
}
1455

1456 1457 1458 1459 1460 1461 1462 1463 1464
/**
 * Work around for missing function in 5.5 - is in 5.6
 */
function auth_saml_openssl_x509_fingerprint($cert, $hash) {
   $cert = preg_replace('#-.*-|\r|\n#', '', $cert);
   $bin = base64_decode($cert);
   return hash($hash, $bin);
}

1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499
if (file_exists(get_config('docroot') . 'auth/saml/extlib/simplesamlphp/lib/SimpleSAML/XHTML/IdPDisco.php')) {
    require_once(get_config('docroot') . 'auth/saml/extlib/simplesamlphp/lib/SimpleSAML/XHTML/IdPDisco.php');

    class PluginAuthSaml_IdPDisco extends SimpleSAML_XHTML_IdPDisco
    {

        /**
         * Initializes this discovery service.
         *
         * The constructor does the parsing of the request. If this is an invalid request, it will throw an exception.
         *
         * @param array  $metadataSets Array with metadata sets we find remote entities in.
         * @param string $instance The name of this instance of the discovery service.
         *
         * @throws Exception If the request is invalid.
         */
        public function __construct(array $metadataSets, $instance) {
            assert('is_string($instance)');

            // initialize standard classes
            $this->config = SimpleSAML_Configuration::getInstance();
            $this->metadata = SimpleSAML_Metadata_MetaDataStorageHandler::getMetadataHandler();
            $this->instance = $instance;
            $this->metadataSets = $metadataSets;
            $this->isPassive = false;
        }

        public function getTheIdPs() {
            $idpList = $this->getIdPList();
            $idpList = $this->filterList($idpList);
            $preferredIdP = $this->getRecommendedIdP();
            return array('list' => $idpList, 'preferred' => $preferredIdP);
        }
    }
}
1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572


/*
 * Provides any mahara specific wrappers for the metarefresh plugin from simplesamlphp that is used to refresh IDP metadata
 */
class Metarefresh {
    /*
     * Path that the metarefresh module should write it's metadata file to
     *
     * It is also used to store the metarefresh state file
     */
    public static function get_metadata_path() {
        check_dir_exists(get_config('dataroot') . 'metadata/refresh/');
        return get_config('dataroot') . 'metadata/refresh/';
    }

    /*
     * Return all configured metadataurls for idps if any found
     */
    public static function get_metadata_urls() {
        $finalarr = array();
        $sites = get_records_menu('auth_instance_config', 'field', 'institutionidpentityid', '', 'instance, value');
        $urls = get_records_array('auth_instance_config', 'field', 'metarefresh_metadata_url', '', 'field, value, instance');
        if ( ( !$sites || count($sites) <= 0 ) || ( !$urls || count($urls) <= 0 ) ) {
            log_warn("Could not get any valid urls for metadata refresh url list", false, false);
            return array();//could not get any valid urls to fetch metadata from
        }
        foreach($urls as $url) {
            if ( isset($url->value) && !empty($url->value) ) {
                if ( isset($sites[$url->instance]) ) {
                    $finalarr[$sites[$url->instance]] = $url->value;
                }
            }
        }
        return $finalarr;
    }

    /*
     * Given an IDP entity id, find the source url for it
     */
    public static function get_metadata_url($idp) {
        $sources = self::get_metadata_urls();
        if (isset($sources[$idp])) {
            return $sources[$idp];
        }
        return '';
    }



    /**
    * Hook to try a metarefresh using the metarefresh module in simplesaml from mahara
    *
    * Most of this code was based on the  cron_hook in the metarefresh module
    *
    * With only minimal mahara specific tweaks around config and data paths
    *
    */
    function metadata_refresh_hook() {
        try {
            //Include autoloader and setup config dir correctly
            PluginAuthSaml::init_simplesamlphp();

            $config = SimpleSAML_Configuration::getInstance();
            $mconfig = SimpleSAML_Configuration::getOptionalConfig('config-metarefresh.php');

            $sets = $mconfig->getConfigList('sets', array());

            //Store our metarefresh state file in the sitedata for the site
            $stateFile = self::get_metadata_path() . 'metarefresh-state.php';

            foreach ($sets AS $setkey => $set) {

1573
                SimpleSAML\Logger::info('Mahara [metarefresh]: Executing set [' . $setkey . ']');
1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639

                $expireAfter = $set->getInteger('expireAfter', NULL);
                if ($expireAfter !== NULL) {
                    $expire = time() + $expireAfter;
                }
                else {
                    $expire = NULL;
                }

                $outputDir = $set->getString('outputDir');
                $outputDir = $config->resolvePath($outputDir);
                $outputFormat = $set->getValueValidate('outputFormat', array('flatfile', 'serialize'), 'flatfile');

                $oldMetadataSrc = SimpleSAML_Metadata_MetaDataStorageSource::getSource(array(
                    'type' => $outputFormat,
                    'directory' => $outputDir,
                ));

                $metaloader = new sspmod_metarefresh_MetaLoader($expire, $stateFile, $oldMetadataSrc);

                # Get global blacklist, whitelist and caching info
                $blacklist = $mconfig->getArray('blacklist', array());
                $whitelist = $mconfig->getArray('whitelist', array());
                $conditionalGET = $mconfig->getBoolean('conditionalGET', FALSE);

                // get global type filters
                $available_types = array(
                    'saml20-idp-remote',
                    'saml20-sp-remote',
                    'shib13-idp-remote',
                    'shib13-sp-remote',
                    'attributeauthority-remote'
                );
                $set_types = $set->getArrayize('types', $available_types);

                foreach($set->getArray('sources') AS $source) {

                    // filter metadata by type of entity
                    if (isset($source['types'])) {
                        $metaloader->setTypes($source['types']);
                    }
                    else {
                        $metaloader->setTypes($set_types);
                    }

                    # Merge global and src specific blacklists
                    if (isset($source['blacklist'])) {
                        $source['blacklist'] = array_unique(array_merge($source['blacklist'], $blacklist));
                    }
                    else {
                        $source['blacklist'] = $blacklist;
                    }

                    # Merge global and src specific whitelists
                    if (isset($source['whitelist'])) {
                        $source['whitelist'] = array_unique(array_merge($source['whitelist'], $whitelist));
                    }
                    else {
                        $source['whitelist'] = $whitelist;
                    }

                    # Let src specific conditionalGET override global one
                    if (!isset($source['conditionalGET'])) {
                        $source['conditionalGET'] = $conditionalGET;
                    }

1640
                    SimpleSAML\Logger::debug('cron [metarefresh]: In set [' . $setkey . '] loading source ['  . $source['src'] . ']');
1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664
                    $metaloader->loadSource($source);
                }

                // Write state information back to disk
                $metaloader->writeState();

                switch ($outputFormat) {
                    case 'flatfile':
                        $metaloader->writeMetadataFiles($outputDir);
                        break;
                    case 'serialize':
                        $metaloader->writeMetadataSerialize($outputDir);
                        break;
                }

                if ($set->hasValue('arp')) {
                    $arpconfig = SimpleSAML_Configuration::loadFromArray($set->getValue('arp'));
                    $metaloader->writeARPfile($arpconfig);
                }
            }
            return true;//we were able to update successfully

        }
        catch (Exception $e) {
1665
            SimpleSAML\Logger::info('Mahara [metarefresh]: Error during metadata refresh ' . $e->getMessage());
1666 1667 1668 1669
            return false;//fetch failed
        }
    }
}