setCasServerCACert() public static method

Set the certificate of the CAS server CA and if the CN should be properly verified.
public static setCasServerCACert ( string $cert, boolean $validate_cn = true ) : void
$cert string CA certificate file name
$validate_cn boolean Validate CN in certificate (default true)
return void
Ejemplo n.º 1
0
function check_cas_result($config)
{
    require_once dirname(__DIR__) . '/vendor/autoload.php';
    try {
        $cas_version = $config->cas_version ? $config->cas_version : CAS_VERSION_2_0;
        // phpCAS::setDebug();
        phpCAS::client($cas_version, $config->cashostname, (int) $config->casport, $config->casbaseuri, false);
        // don't automatically clear tickets from the url, we're taking care of that
        phpCAS::setNoClearTicketsFromUrl();
        // if a certificate is provided, use it, otherwise don't
        if ($config->cas_server_ca_cert_path != "") {
            // here we sould set the server certificate for production
            // '/etc/pki/tls/certs/DigiCertCA.crt'
            phpCAS::setCasServerCACert($config->cas_server_ca_cert_path);
        } else {
            // if you want to skip ssl verification
            if ($config->cas_server_no_validation) {
                phpCAS::setNoCasServerValidation();
            }
        }
        // check authentication; returns true/false
        if (phpCAS::checkAuthentication()) {
            // grab username
            $NetUsername = phpCAS::getUser();
            return $NetUsername;
        } else {
            return false;
        }
    } catch (Exception $e) {
        error_log("CAS ERROR: " . $e->getMessage());
        register_error($e->getMessage());
        return false;
    }
}
Ejemplo n.º 2
0
 public function __construct()
 {
     // These are default values for the first login and should be changed via GUI
     $CAS_HOSTNAME = 'your.domain.org';
     $CAS_PORT = '443';
     $CAS_PATH = '/cas';
     $this->autocreate = OCP\Config::getAppValue('user_cas', 'cas_autocreate', true);
     $this->updateUserData = OCP\Config::getAppValue('user_cas', 'cas_update_user_data', true);
     $this->defaultGroup = OCP\Config::getAppValue('user_cas', 'cas_default_group', '');
     $this->protectedGroups = explode(',', str_replace(' ', '', OCP\Config::getAppValue('user_cas', 'cas_protected_groups', '')));
     $this->mailMapping = OCP\Config::getAppValue('user_cas', 'cas_email_mapping', '');
     $this->displayNameMapping = OCP\Config::getAppValue('user_cas', 'cas_displayName_mapping', '');
     $this->groupMapping = OCP\Config::getAppValue('user_cas', 'cas_group_mapping', '');
     $casVersion = OCP\Config::getAppValue('user_cas', 'cas_server_version', '2.0');
     $casHostname = OCP\Config::getAppValue('user_cas', 'cas_server_hostname', $CAS_HOSTNAME);
     $casPort = OCP\Config::getAppValue('user_cas', 'cas_server_port', $CAS_PORT);
     $casPath = OCP\Config::getAppValue('user_cas', 'cas_server_path', $CAS_PATH);
     $casCertPath = OCP\Config::getAppValue('user_cas', 'cas_cert_path', '');
     global $initialized_cas;
     if (!$initialized_cas) {
         phpCAS::client($casVersion, $casHostname, (int) $casPort, $casPath, false);
         if (!empty($casCertPath)) {
             phpCAS::setCasServerCACert($casCertPath);
         } else {
             phpCAS::setNoCasServerValidation();
         }
         $initialized_cas = true;
     }
 }
Ejemplo n.º 3
0
 /**
  * Initialize the class, this must be called before anything else
  * @param $config
  * @param bool $changeSessionID Allow phpCAS to change the session_id (Single Sign Out/handleLogoutRequests is based on that change)
  * @param $debugLog Set to a path to enable debug log
  */
 public static function init($config, $changeSessionID = true, $debugLog = null)
 {
     if ($debugLog != null) {
         phpCAS::setDebug($debugLog);
     }
     phpCAS::client(CAS_VERSION_2_0, $config['site'], $config['port'], "cas", $changeSessionID);
     self::$config = $config;
     $private_key = null;
     if (isset($config['private_key'])) {
         $key = static::resolve_filename($config['private_key']);
         $private_key = openssl_get_privatekey("file:///{$key}");
         if ($private_key === false) {
             throw new NXAuthError("Failed to open private key {$key}");
         }
     }
     if (isset($config['ca_cert']) && $config['ca_cert'] != null) {
         self::$ca_cert = static::resolve_filename($config['ca_cert']);
         phpCAS::setCasServerCACert(self::$ca_cert);
     } else {
         phpCAS::setNoCasServerValidation();
         // Disable curl ssl verification
         phpCAS::setExtraCurlOption(CURLOPT_SSL_VERIFYHOST, 0);
         phpCAS::setExtraCurlOption(CURLOPT_SSL_VERIFYPEER, 0);
     }
     NXAPI::init(array('private_key' => $private_key, 'key_id' => $config['key_id'], 'url' => "https://" . $config['site'], 'ca_cert' => self::$ca_cert));
 }
Ejemplo n.º 4
0
 public static function initialized_php_cas()
 {
     if (!self::$_initialized_php_cas) {
         $casVersion = OCP\Config::getAppValue('user_cas', 'cas_server_version', '2.0');
         $casHostname = OCP\Config::getAppValue('user_cas', 'cas_server_hostname', $_SERVER['SERVER_NAME']);
         $casPort = OCP\Config::getAppValue('user_cas', 'cas_server_port', 443);
         $casPath = OCP\Config::getAppValue('user_cas', 'cas_server_path', '/cas');
         $casDebugFile = OCP\Config::getAppValue('user_cas', 'cas_debug_file', '');
         $casCertPath = OCP\Config::getAppValue('user_cas', 'cas_cert_path', '');
         $php_cas_path = OCP\Config::getAppValue('user_cas', 'cas_php_cas_path', 'CAS.php');
         if (!class_exists('phpCAS')) {
             if (empty($php_cas_path)) {
                 $php_cas_path = 'CAS.php';
             }
             OC_Log::write('cas', "Try to load phpCAS library ({$php_cas_path})", OC_Log::DEBUG);
             include_once $php_cas_path;
             if (!class_exists('phpCAS')) {
                 OC_Log::write('cas', 'Fail to load phpCAS library !', OC_Log::ERROR);
                 return false;
             }
         }
         if ($casDebugFile !== '') {
             phpCAS::setDebug($casDebugFile);
         }
         phpCAS::client($casVersion, $casHostname, (int) $casPort, $casPath, false);
         if (!empty($casCertPath)) {
             phpCAS::setCasServerCACert($casCertPath);
         } else {
             phpCAS::setNoCasServerValidation();
         }
         self::$_initialized_php_cas = true;
     }
     return self::$_initialized_php_cas;
 }
 private function init_cas_client()
 {
     if (class_exists('phpCAS')) {
         return true;
     }
     require getConfig('casldap_phpcas_path');
     $cas_debug_file = getConfig('cas_debug_file_path');
     if (!empty($cas_debug_file)) {
         phpCAS::setDebug($cas_debug_file);
     }
     $cas_host = getConfig('cas_host');
     $cas_port = getConfig('cas_port') or 443;
     $cas_context = getConfig('cas_context');
     switch (getConfig('cas_version')) {
         case 1:
             $cas_version = CAS_VERSION_1_0;
             break;
         case 2:
             $cas_version = CAS_VERSION_2_0;
             break;
         case 3:
             $cas_version = CAS_VERSION_3_0;
             break;
         default:
             $cas_version = CAS_VERSION_2_0;
             break;
     }
     phpCAS::client($cas_version, $cas_host, intval($cas_port), $cas_context);
     $cas_server_ca_cert_path = getConfig('cas_server_ca_cert_path');
     if ($cas_server_ca_cert_path) {
         phpCAS::setCasServerCACert($cas_server_ca_cert_path);
     } else {
         phpCAS::setNoCasServerValidation();
     }
 }
 public function __construct(ComponentCollection $collection, $settings)
 {
     $this->settings['host'] = 'cas.ucdavis.edu';
     $this->settings['context'] = '/cas';
     $this->settings['port'] = 443;
     $this->settings['ca_cert_path'] = '/usr/share/ca-certificates/mozilla/AddTrust_External_Root.crt';
     phpCAS::client(CAS_VERSION_2_0, $this->settings['host'], $this->settings['port'], $this->settings['context']);
     phpCAS::setCasServerCACert($this->settings['ca_cert_path']);
     parent::__construct($collection, $settings);
 }
Ejemplo n.º 7
0
function initPhpCAS($host, $port, $context, $CA_certificate_file)
{
    phpCAS::client(SAML_VERSION_1_1, $host, intval($port), $context, false);
    if ($CA_certificate_file) {
        phpCAS::setCasServerCACert($CA_certificate_file);
    } else {
        phpCAS::setNoCasServerValidation();
    }
    //phpCAS::setLang(PHPCAS_LANG_FRENCH);
}
Ejemplo n.º 8
0
 /**
  * Stores the configuration. Calls the parent configuration first,
  * then does additional operations.
  *
  * @param object Properties $configuration
  * @return object
  * @access public
  * @since 3/24/05
  */
 function assignConfiguration(Properties $configuration)
 {
     parent::assignConfiguration($configuration);
     $format = $configuration->getProperty('DISPLAY_NAME_FORMAT');
     ArgumentValidator::validate($format, RegexValidatorRule::getRule('/\\[\\[([^]]+)\\]\\]/'));
     $this->displayNameFormat = $format;
     if ($debug = $configuration->getProperty('CAS_DEBUG_PATH')) {
         ArgumentValidator::validate($debug, StringValidatorRule::getRule());
         phpCAS::setDebug($debug);
     }
     $host = $configuration->getProperty('CAS_HOST');
     ArgumentValidator::validate($host, RegexValidatorRule::getRule('/^[a-z0-9]+\\.[a-z0-9]+.[a-z]+$/'));
     $port = $configuration->getProperty('CAS_PORT');
     ArgumentValidator::validate($port, RegexValidatorRule::getRule('/^[0-9]+$/'));
     $path = $configuration->getProperty('CAS_PATH');
     ArgumentValidator::validate($path, RegexValidatorRule::getRule('/^\\/.*$/'));
     phpCAS::client(CAS_VERSION_2_0, $host, intval($port), $path, false);
     if ($cert = $configuration->getProperty('CAS_CERT')) {
         phpCAS::setCasServerCACert($cert);
     } else {
         phpCAS::setNoCasServerValidation();
     }
     // Allow group lookup via a CASDirectory:
     // https://mediawiki.middlebury.edu/wiki/LIS/CAS_Directory
     $dirUrl = $configuration->getProperty('CASDIRECTORY_BASE_URL');
     ArgumentValidator::validate($dirUrl, StringValidatorRule::getRule());
     $this->directoryUrl = $dirUrl;
     // set the callback URL for the PGT to be sent to. This must be an https url
     // whose certificate is trusted by CAS.
     // 		$callbackUrl = $configuration->getProperty('CALLBACK_URL');
     // 		ArgumentValidator::validate($callbackUrl, RegexValidatorRule::getRule('/^https:\/\/.*$/'));
     // 		phpCAS::setFixedCallbackURL($callbackUrl);
     $adminAccess = $configuration->getProperty('CASDIRECTORY_ADMIN_ACCESS');
     ArgumentValidator::validate($adminAccess, StringValidatorRule::getRule());
     $this->adminAccess = $adminAccess;
     $classRoot = $configuration->getProperty('CASDIRECTORY_CLASS_ROOT');
     if ($classRoot) {
         ArgumentValidator::validate($classRoot, StringValidatorRule::getRule());
         $this->classRoot = $classRoot;
     } else {
         $this->classRoot = null;
     }
     $groupIdRegex = $configuration->getProperty('CASDIRECTORY_GROUP_ID_REGEX');
     if ($groupIdRegex) {
         ArgumentValidator::validate($groupIdRegex, StringValidatorRule::getRule());
         $this->groupIdRegex = $groupIdRegex;
     } else {
         $this->groupIdRegex = null;
     }
     // Root Groups to expose
     ArgumentValidator::validate($configuration->getProperty('ROOT_GROUPS'), ArrayValidatorRuleWithRule::getRule(StringValidatorRule::getRule()));
     $this->rootGroups = array_unique($configuration->getProperty('ROOT_GROUPS'));
 }
Ejemplo n.º 9
0
 private function setCASSettings()
 {
     if ($this->options->IsCasDebugOn()) {
         phpCAS::setDebug($this->options->DebugFile());
     }
     phpCAS::client($this->options->CasVersion(), $this->options->HostName(), $this->options->Port(), $this->options->ServerUri(), $this->options->ChangeSessionId());
     if ($this->options->CasHandlesLogouts()) {
         phpCAS::handleLogoutRequests(true, $this->options->LogoutServers());
     }
     if ($this->options->HasCertificate()) {
         phpCAS::setCasServerCACert($this->options->Certificate());
     }
     phpCAS::setNoCasServerValidation();
 }
Ejemplo n.º 10
0
 function __construct()
 {
     if (!self::$initialized) {
         global $cas_cfg;
         phpCAS::client(CAS_VERSION_2_0, $cas_cfg['host'], $cas_cfg['port'], $cas_cfg['context']);
         // Perform SSL validation only if server_ca_cert path is provided.
         if (isset($cas_cfg['server_ca_cert'])) {
             phpCAS::setCasServerCACert($cas_cfg['server_ca_cert']);
         } else {
             phpCAS::setNoCasServerValidation();
         }
         self::$initialized = true;
     }
 }
Ejemplo n.º 11
0
 function __construct($collection, $settings)
 {
     $this->_Collection = $collection;
     if (Configure::read('CAS.debug_log_enabled')) {
         phpCAS::setDebug(TMP . 'phpCas.log.txt');
     }
     phpCAS::client(CAS_VERSION_2_0, Configure::read('CAS.hostname'), Configure::read('CAS.port'), Configure::read('CAS.uri'));
     $certServer = Configure::read('CAS.cert_path');
     if (empty($certServer)) {
         phpCAS::setNoCasServerValidation();
     } else {
         phpCAS::setCasServerCACert($certServer);
     }
 }
Ejemplo n.º 12
0
 function __construct()
 {
     if (!self::$initialized) {
         global $cas_cfg;
         phpCAS::client(CAS_VERSION_2_0, $cas_cfg['host'], $cas_cfg['port'], $cas_cfg['context']);
         // Perform SSL validation only if server_ca_cert path is provided.
         if (isset($cas_cfg['server_ca_cert'])) {
             phpCAS::setCasServerCACert($cas_cfg['server_ca_cert']);
         } else {
             phpCAS::setNoCasServerValidation();
         }
         setcookie('org.springframework.web.servlet.i18n.CookieLocaleResolver.LOCALE', explode('_', setlocale(LC_ALL, '0'))[0], 0, '/');
         self::$initialized = true;
     }
 }
Ejemplo n.º 13
0
 /**
  * Initializes the authority objects based on an associative array of arguments
  * @param array $args an associate array of arguments. The argument list is dependent on the authority
  *
  * General - Required keys:
  *   TITLE => The human readable title of the AuthorityImage
  *   INDEX => The tag used to identify this authority @see AuthenticationAuthority::getAuthenticationAuthority
  *
  * General - Optional keys:
  *   LOGGEDIN_IMAGE_URL => a url to an image/badge that is placed next to the user name when logged in
  *
  * CAS - Required keys:
  *   CAS_PROTOCOL => The protocol to use. Should be equivalent to one of the phpCAS constants, e.g. "2.0":
  *                   CAS_VERSION_1_0 => '1.0', CAS_VERSION_2_0 => '2.0', SAML_VERSION_1_1 => 'S1'
  *   CAS_HOST => The host name of the CAS server, e.g. "cas.example.edu"
  *   CAS_PORT => The port the CAS server is listening on, e.g. "443"
  *   CAS_PATH => The path of the CAS application, e.g. "/cas/"
  *   CAS_CA_CERT => The filesystem path to a CA certificate that will be used to validate the authenticity
  *                  of the CAS server, e.g. "/etc/tls/pki/certs/my_ca_cert.crt". If empty, no certificate
  *                  validation will be performed (not recommended for production).
  *
  * CAS - Optional keys:
  *   ATTRA_EMAIL => Attribute name for the user's email adress, e.g. "email". This only applies if your 
  *                  CAS server returns attributes in a SAML-1.1 or CAS-2.0 response.
  *   ATTRA_FIRST_NAME => Attribute name for the user's first name, e.g. "givename". This only applies if your 
  *                       CAS server returns attributes in a SAML-1.1 or CAS-2.0 response.
  *   ATTRA_LAST_NAME => Attribute name for the user's last name, e.g. "surname". This only applies if your 
  *                      CAS server returns attributes in a SAML-1.1 or CAS-2.0 response.
  *   ATTRA_FULL_NAME => Attribute name for the user's full name, e.g. "displayname". This only applies if your 
  *                      CAS server returns attributes in a SAML-1.1 or CAS-2.0 response.
  *   ATTRA_MEMBER_OF => Attribute name for the user's groups, e.g. "memberof". This only applies if your 
  *                      CAS server returns attributes in a SAML-1.1 or CAS-2.0 response.
  *
  * NOTE: Any subclass MUST call parent::init($args) to ensure proper operation
  *
  */
 public function init($args)
 {
     parent::init($args);
     // include the PHPCAS library
     if (empty($args['CAS_PHPCAS_PATH'])) {
         require_once 'CAS.php';
     } else {
         require_once $args['CAS_PHPCAS_PATH'] . '/CAS.php';
     }
     if (empty($args['CAS_PROTOCOL'])) {
         throw new KurogoConfigurationException('CAS_PROTOCOL value not set for ' . $this->AuthorityTitle);
     }
     if (empty($args['CAS_HOST'])) {
         throw new KurogoConfigurationException('CAS_HOST value not set for ' . $this->AuthorityTitle);
     }
     if (empty($args['CAS_PORT'])) {
         throw new KurogoConfigurationException('CAS_PORT value not set for ' . $this->AuthorityTitle);
     }
     if (empty($args['CAS_PATH'])) {
         throw new KurogoConfigurationException('CAS_PATH value not set for ' . $this->AuthorityTitle);
     }
     phpCAS::client($args['CAS_PROTOCOL'], $args['CAS_HOST'], intval($args['CAS_PORT']), $args['CAS_PATH'], false);
     if (empty($args['CAS_CA_CERT'])) {
         phpCAS::setNoCasServerValidation();
     } else {
         phpCAS::setCasServerCACert($args['CAS_CA_CERT']);
     }
     // Record any attribute mapping configured.
     if (!empty($args['ATTRA_EMAIL'])) {
         CASUser::mapAttribute('Email', $args['ATTRA_EMAIL']);
     }
     if (!empty($args['ATTRA_FIRST_NAME'])) {
         CASUser::mapAttribute('FirstName', $args['ATTRA_FIRST_NAME']);
     }
     if (!empty($args['ATTRA_LAST_NAME'])) {
         CASUser::mapAttribute('LastName', $args['ATTRA_LAST_NAME']);
     }
     if (!empty($args['ATTRA_FULL_NAME'])) {
         CASUser::mapAttribute('FullName', $args['ATTRA_FULL_NAME']);
     }
     // Store an attribute for group membership if configured.
     if (!empty($args['ATTRA_MEMBER_OF'])) {
         CASUser::mapAttribute('MemberOf', $args['ATTRA_MEMBER_OF']);
     }
 }
Ejemplo n.º 14
0
 public function triggerAuth($service_url = null)
 {
     self::buildClient($this->config->get('cas-hostname'), $this->config->get('cas-port'), $this->config->get('cas-context'));
     // Force set the CAS service URL to the osTicket login page.
     if ($service_url) {
         phpCAS::setFixedServiceURL($service_url);
     }
     // Verify the CAS server's certificate, if configured.
     if ($this->config->get('cas-ca-cert-path')) {
         phpCAS::setCasServerCACert($this->config->get('cas-ca-cert-path'));
     } else {
         phpCAS::setNoCasServerValidation();
     }
     // Trigger authentication and set the user fields when validated.
     if (!phpCAS::isAuthenticated()) {
         phpCAS::forceAuthentication();
     } else {
         $this->setUser();
         $this->setEmail();
         $this->setName();
     }
 }
Ejemplo n.º 15
0
    public function __construct()
    {
        if (!function_exists('curl_init')) {
            show_error('<strong>ERROR:</strong> You need to install the PHP module
				<strong><a href="http://php.net/curl">curl</a></strong> to be able
				to use CAS authentication.');
        }
        $CI =& get_instance();
        $this->CI = $CI;
        $CI->config->load('cas');
        $this->phpcas_path = $CI->config->item('phpcas_path');
        $this->cas_server_url = $CI->config->item('cas_server_url');
        if (empty($this->phpcas_path) or filter_var($this->cas_server_url, FILTER_VALIDATE_URL) === FALSE) {
            $this->_cas_show_config_error();
        }
        $cas_lib_file = $this->phpcas_path . '/CAS.php';
        if (!file_exists($cas_lib_file)) {
            show_error("<strong>ERROR:</strong> Could not find a file <em>CAS.php</em> in directory\n\t\t\t\t<strong>{$this->phpcas_path}</strong><br /><br />\n\t\t\t\tPlease, check your config file <strong>config/cas.php</strong> and make sure the\n\t\t\t\tconfiguration <em>phpcas_path</em> is a valid phpCAS installation.");
        }
        require_once $cas_lib_file;
        if ($CI->config->item('cas_debug')) {
            phpCAS::setDebug();
        }
        // init CAS client
        $defaults = array('path' => '', 'port' => 443);
        $cas_url = array_merge($defaults, parse_url($this->cas_server_url));
        phpCAS::client(CAS_VERSION_2_0, $cas_url['host'], $cas_url['port'], $cas_url['path'], false);
        // configures SSL behavior
        if ($CI->config->item('cas_disable_server_validation')) {
            phpCAS::setNoCasServerValidation();
        } else {
            $ca_cert_file = $CI->config->item('cas_server_ca_cert');
            if (empty($ca_cert_file)) {
                $this->_cas_show_config_error();
            }
            phpCAS::setCasServerCACert($ca_cert_file);
        }
    }
Ejemplo n.º 16
0
 /**
  * Connect to the CAS (clientcas connection or proxycas connection)
  *
  */
 function connectCAS()
 {
     global $CFG;
     static $connected = false;
     if (!$connected) {
         // Make sure phpCAS doesn't try to start a new PHP session when connecting to the CAS server.
         if ($this->config->proxycas) {
             phpCAS::proxy($this->config->casversion, $this->config->hostname, (int) $this->config->port, $this->config->baseuri, false);
         } else {
             phpCAS::client($this->config->casversion, $this->config->hostname, (int) $this->config->port, $this->config->baseuri, false);
         }
         $connected = true;
     }
     // If Moodle is configured to use a proxy, phpCAS needs some curl options set.
     if (!empty($CFG->proxyhost) && !is_proxybypass($this->config->hostname)) {
         phpCAS::setExtraCurlOption(CURLOPT_PROXY, $CFG->proxyhost);
         if (!empty($CFG->proxyport)) {
             phpCAS::setExtraCurlOption(CURLOPT_PROXYPORT, $CFG->proxyport);
         }
         if (!empty($CFG->proxytype)) {
             // Only set CURLOPT_PROXYTYPE if it's something other than the curl-default http
             if ($CFG->proxytype == 'SOCKS5') {
                 phpCAS::setExtraCurlOption(CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
             }
         }
         if (!empty($CFG->proxyuser) and !empty($CFG->proxypassword)) {
             phpCAS::setExtraCurlOption(CURLOPT_PROXYUSERPWD, $CFG->proxyuser . ':' . $CFG->proxypassword);
             if (defined('CURLOPT_PROXYAUTH')) {
                 // any proxy authentication if PHP 5.1
                 phpCAS::setExtraCurlOption(CURLOPT_PROXYAUTH, CURLAUTH_BASIC | CURLAUTH_NTLM);
             }
         }
     }
     if ($this->config->certificate_check && $this->config->certificate_path) {
         phpCAS::setCasServerCACert($this->config->certificate_path);
     } else {
         // Don't try to validate the server SSL credentials
         phpCAS::setNoCasServerValidation();
     }
 }
Ejemplo n.º 17
0
function cas_authenticate($auth, $new = false, $cas_host = null, $cas_port = null, $cas_context = null, $cas_cachain = null)
{
    global $langConnectWith, $langNotSSL;
    // SESSION does not exist if user has not been authenticated
    $ret = array();
    if (!$new) {
        $cas = get_auth_settings($auth);
        if ($cas) {
            $cas_host = $cas['cas_host'];
            $cas_port = $cas['cas_port'];
            $cas_context = $cas['cas_context'];
            $cas_cachain = $cas['cas_cachain'];
            $casusermailattr = $cas['casusermailattr'];
            $casuserfirstattr = $cas['casuserfirstattr'];
            $casuserlastattr = $cas['casuserlastattr'];
            $cas_altauth = $cas['cas_altauth'];
        }
    }
    if ($new or $cas) {
        $cas_url = 'https://' . $cas_host;
        $cas_port = intval($cas_port);
        if ($cas_port != '443') {
            $cas_url = $cas_url . ':' . $cas_port;
        }
        $cas_url = $cas_url . $cas_context;
        // The "real" hosts that send SAML logout messages
        // Assumes the cas server is load balanced across multiple hosts
        $cas_real_hosts = array($cas_host);
        // Uncomment to enable debugging
        // phpCAS::setDebug();
        // Initialize phpCAS - keep session in application
        $ret['message'] = "{$langConnectWith} {$cas_url}";
        phpCAS::client(SAML_VERSION_1_1, $cas_host, $cas_port, $cas_context, FALSE);
        // Set the CA certificate that is the issuer of the cert on the CAS server
        if (isset($cas_cachain) && !empty($cas_cachain) && is_readable($cas_cachain)) {
            phpCAS::setCasServerCACert($cas_cachain);
        } else {
            phpCAS::setNoCasServerValidation();
            $ret['error'] = "{$langNotSSL}";
        }
        // Single Sign Out
        //phpCAS::handleLogoutRequests(true, $cas_real_hosts);
        // Force CAS authentication on any page that includes this file
        phpCAS::forceAuthentication();
        //$ret['attrs'] = get_cas_attrs(phpCAS::getAttributes(), $cas);
        if (phpCAS::checkAuthentication()) {
            $ret['attrs'] = phpCAS::getAttributes();
        }
        return $ret;
    } else {
        return null;
    }
}
Ejemplo n.º 18
0
 /**
  * Validate this user's credentials against CAS.
  * @param  array $auth_settings Plugin settings
  * @return [mixed] Array containing 'email' and 'authenticated_by'
  *                       strings for the successfully authenticated
  *                       user, or WP_Error() object on failure.
  */
 private function custom_authenticate_cas($auth_settings)
 {
     // Move on if CAS hasn't been requested here.
     if (empty($_GET['external']) || $_GET['external'] !== 'cas') {
         return new WP_Error('cas_not_available', 'CAS is not enabled.');
     }
     // Set the CAS client configuration
     phpCAS::client(SAML_VERSION_1_1, $auth_settings['cas_host'], intval($auth_settings['cas_port']), $auth_settings['cas_path']);
     // Update server certificate bundle if it doesn't exist or is older
     // than 3 months, then use it to ensure CAS server is legitimate.
     $cacert_path = plugin_dir_path(__FILE__) . 'inc/cacert.pem';
     $time_90_days = 90 * 24 * 60 * 60;
     // days * hours * minutes * seconds
     $time_90_days_ago = time() - $time_90_days;
     if (!file_exists($cacert_path) || filemtime($cacert_path) < $time_90_days_ago) {
         $cacert_contents = file_get_contents('http://curl.haxx.se/ca/cacert.pem');
         if ($cacert_contents !== false) {
             file_put_contents($cacert_path, $cacert_contents);
         } else {
             return new WP_Error('cannot_update_cacert', 'Unable to update outdated server certificates from http://curl.haxx.se/ca/cacert.pem.');
         }
     }
     phpCAS::setCasServerCACert($cacert_path);
     // Authenticate against CAS
     if (!phpCAS::isAuthenticated()) {
         phpCAS::forceAuthentication();
         die;
     }
     // Get the TLD from the CAS host for use in matching email addresses
     // For example: example.edu is the TLD for authn.example.edu, so user
     // 'bob' will have the following email address: bob@example.edu.
     $tld = preg_match('/[^.]*\\.[^.]*$/', $auth_settings['cas_host'], $matches) === 1 ? $matches[0] : '';
     // Get username that successfully authenticated against the external service (CAS).
     $externally_authenticated_email = strtolower(phpCAS::getUser()) . '@' . $tld;
     // We'll track how this user was authenticated in user meta.
     $authenticated_by = 'cas';
     return array('email' => $externally_authenticated_email, 'authenticated_by' => $authenticated_by);
 }
 */
// Load the settings from the central config file
require_once 'config.php';
// Load the CAS lib
require_once $phpcas_path . '/CAS.php';
// Enable debugging
phpCAS::setDebug();
// Enable verbose error messages. Disable in production!
phpCAS::setVerbose(false);
// Harden session cookie to prevent some attacks on the cookie (e.g. XSS)
session_set_cookie_params($client_lifetime, $client_path, $client_domain, $client_secure, $client_httpOnly);
// Initialize phpCAS
phpCAS::client(SAML_VERSION_1_1, $cas_host, $cas_port, $cas_context);
// For production use set the CA certificate that is the issuer of the cert
// on the CAS server and uncomment the line below
phpCAS::setCasServerCACert($cas_server_ca_cert_path);
// For quick testing you can disable SSL validation of the CAS server.
// THIS SETTING IS NOT RECOMMENDED FOR PRODUCTION.
// VALIDATING THE CAS SERVER IS CRUCIAL TO THE SECURITY OF THE CAS PROTOCOL!
// phpCAS::setNoCasServerValidation();
// Handle SAML logout requests that emanate from the CAS host exclusively.
// Failure to restrict SAML logout requests to authorized hosts could
// allow denial of service attacks where at the least the server is
// tied up parsing bogus XML messages.
phpCAS::handleLogoutRequests(true, $cas_real_hosts);
// Force CAS authentication on any page that includes this file
phpCAS::forceAuthentication();
// Some small code triggered by the logout button
if (isset($_REQUEST['logout'])) {
    phpCAS::logout();
}
Ejemplo n.º 20
0
/**
    Etablis le status de visiteur si non connecté
     **/
if (!isset($_SESSION['rang'])) {
    $_SESSION['rang'] = 0;
}
/**
		Récupération des informations sur la page actuelle
	**/
if ($currentPageData = getCurrentPageData()) {
    if ($currentPageData['fullRight'][$_SESSION['rang']] == 0) {
        // On invite l'utilisateur à se connecter au CAS
        phpCAS::client(CAS_VERSION_2_0, CAS_SERVER_URI, (int) constant('CAS_SERVER_PORT'), '');
        phpCAS::setServerServiceValidateURL(CAS_SERVER_VALIDATEURI);
        if (is_file(CAS_SERVER_CERTIFICATPATH)) {
            phpCAS::setCasServerCACert(CAS_SERVER_CERTIFICATPATH);
        } else {
            phpCAS::setNoCasServerValidation();
        }
        phpCAS::forceAuthentication();
        if (phpCAS::getUser()) {
            //Si l'utilisateur s'est connecté
            // Récupération des données serveur
            $test = phpCAS::checkAuthentication();
            // Récupération des données utilisateur
            $sql = 'SELECT * FROM user WHERE nbEtudiant = :nbEtu LIMIT 1';
            $res = $db->prepare($sql);
            $res->execute(array('nbEtu' => phpCAS::getUser()));
            if ($res_f = $res->fetch()) {
                $_SESSION['id'] = $res_f['id'];
                $_SESSION['nom'] = $res_f['nom'];
Ejemplo n.º 21
0
 function tryToLogUser(&$httpVars, $isLast = false)
 {
     if (isset($_SESSION["CURRENT_MINISITE"])) {
         return false;
     }
     $this->loadConfig();
     if (isset($_SESSION['AUTHENTICATE_BY_CAS'])) {
         $flag = $_SESSION['AUTHENTICATE_BY_CAS'];
     } else {
         $flag = 0;
     }
     $pgtIou = !empty($httpVars['pgtIou']);
     $logged = isset($_SESSION['LOGGED_IN_BY_CAS']);
     $enre = !empty($httpVars['put_action_enable_redirect']);
     $ticket = !empty($httpVars['ticket']);
     $pgt = !empty($_SESSION['phpCAS']['pgt']);
     $clientModeTicketPendding = isset($_SESSION['AUTHENTICATE_BY_CAS_CLIENT_MOD_TICKET_PENDDING']);
     if ($this->cas_modify_login_page) {
         if ($flag == 0 && $enre && !$logged && !$pgtIou) {
             $_SESSION['AUTHENTICATE_BY_CAS'] = 1;
         } elseif ($flag == 1 && !$enre && !$logged && !$pgtIou && !$ticket && !$pgt) {
             $_SESSION['AUTHENTICATE_BY_CAS'] = 0;
         } elseif ($flag == 1 && $enre && !$logged && !$pgtIou) {
             $_SESSION['AUTHENTICATE_BY_CAS'] = 1;
         } elseif ($pgtIou || $pgt) {
             $_SESSION['AUTHENTICATE_BY_CAS'] = 1;
         } elseif ($ticket) {
             $_SESSION['AUTHENTICATE_BY_CAS'] = 1;
             $_SESSION['AUTHENTICATE_BY_CAS_CLIENT_MOD_TICKET_PENDDING'] = 1;
         } elseif ($logged && $pgtIou) {
             $_SESSION['AUTHENTICATE_BY_CAS'] = 2;
         } else {
             $_SESSION['AUTHENTICATE_BY_CAS'] = 0;
         }
         if ($_SESSION['AUTHENTICATE_BY_CAS'] < 1) {
             if ($clientModeTicketPendding) {
                 unset($_SESSION['AUTHENTICATE_BY_CAS_CLIENT_MOD_TICKET_PENDDING']);
             } else {
                 return false;
             }
         }
     }
     /**
      * Depend on phpCAS mode configuration
      */
     switch ($this->cas_mode) {
         case PHPCAS_MODE_CLIENT:
             if ($this->checkConfigurationForClientMode()) {
                 AJXP_Logger::info(__FUNCTION__, "Start phpCAS mode Client: ", "sucessfully");
                 phpCAS::client(CAS_VERSION_2_0, $this->cas_server, $this->cas_port, $this->cas_uri, false);
                 if (!empty($this->cas_certificate_path)) {
                     phpCAS::setCasServerCACert($this->cas_certificate_path);
                 } else {
                     phpCAS::setNoCasServerValidation();
                 }
                 /**
                  * Debug
                  */
                 if ($this->cas_debug_mode) {
                     // logfile name by date:
                     $today = getdate();
                     $file_path = AJXP_DATA_PATH . '/logs/phpcas_' . $today['year'] . '-' . $today['month'] . '-' . $today['mday'] . '.txt';
                     empty($this->cas_debug_file) ? $file_path : ($file_path = $this->cas_debug_file);
                     phpCAS::setDebug($file_path);
                 }
                 phpCAS::forceAuthentication();
             } else {
                 AJXP_Logger::error(__FUNCTION__, "Could not start phpCAS mode CLIENT, please verify the configuration", "");
                 return false;
             }
             break;
         case PHPCAS_MODE_PROXY:
             /**
              * If in login page, user click on login via CAS, the page will be reload with manuallyredirectocas is set.
              * Or force redirect to cas login page even the force redirect is set in configuration of this module
              *
              */
             if ($this->checkConfigurationForProxyMode()) {
                 AJXP_Logger::info(__FUNCTION__, "Start phpCAS mode Proxy: ", "sucessfully");
                 /**
                  * init phpCAS in mode proxy
                  */
                 phpCAS::proxy(CAS_VERSION_2_0, $this->cas_server, $this->cas_port, $this->cas_uri, false);
                 if (!empty($this->cas_certificate_path)) {
                     phpCAS::setCasServerCACert($this->cas_certificate_path);
                 } else {
                     phpCAS::setNoCasServerValidation();
                 }
                 /**
                  * Debug
                  */
                 if ($this->cas_debug_mode) {
                     // logfile name by date:
                     $today = getdate();
                     $file_path = AJXP_DATA_PATH . '/logs/phpcas_' . $today['year'] . '-' . $today['month'] . '-' . $today['mday'] . '.txt';
                     empty($this->cas_debug_file) ? $file_path : ($file_path = $this->cas_debug_file);
                     phpCAS::setDebug($file_path);
                 }
                 if (!empty($this->cas_setFixedCallbackURL)) {
                     phpCAS::setFixedCallbackURL($this->cas_setFixedCallbackURL);
                 }
                 //
                 /**
                  * PTG storage
                  */
                 $this->setPTGStorage();
                 phpCAS::forceAuthentication();
                 /**
                  * Get proxy ticket (PT) for SAMBA to authentication at CAS via pam_cas
                  * In fact, we can use any other service. Of course, it should be enabled in CAS
                  *
                  */
                 $err_code = null;
                 $serviceURL = $this->cas_proxied_service;
                 AJXP_Logger::debug(__FUNCTION__, "Try to get proxy ticket for service: ", $serviceURL);
                 $res = phpCAS::serviceSMB($serviceURL, $err_code);
                 if (!empty($res)) {
                     $_SESSION['PROXYTICKET'] = $res;
                     AJXP_Logger::info(__FUNCTION__, "Get Proxy ticket successfully ", "");
                 } else {
                     AJXP_Logger::info(__FUNCTION__, "Could not get Proxy ticket. ", "");
                 }
                 break;
             } else {
                 AJXP_Logger::error(__FUNCTION__, "Could not start phpCAS mode PROXY, please verify the configuration", "");
                 return false;
             }
         default:
             return false;
             break;
     }
     AJXP_Logger::debug(__FUNCTION__, "Call phpCAS::getUser() after forceAuthentication ", "");
     $cas_user = phpCAS::getUser();
     if (!AuthService::userExists($cas_user) && $this->is_AutoCreateUser) {
         AuthService::createUser($cas_user, openssl_random_pseudo_bytes(20));
     }
     if (AuthService::userExists($cas_user)) {
         $res = AuthService::logUser($cas_user, "", true);
         if ($res > 0) {
             AJXP_Safe::storeCredentials($cas_user, $_SESSION['PROXYTICKET']);
             $_SESSION['LOGGED_IN_BY_CAS'] = true;
             if (!empty($this->cas_additional_role)) {
                 $userObj = ConfService::getConfStorageImpl()->createUserObject($cas_user);
                 $roles = $userObj->getRoles();
                 $cas_RoleID = $this->cas_additional_role;
                 $userObj->addRole(AuthService::getRole($cas_RoleID, true));
                 AuthService::updateUser($userObj);
             }
             return true;
         }
     }
     return false;
 }
Ejemplo n.º 22
0
 /**
  * Connect to the CAS (clientcas connection or proxycas connection)
  *
  */
 function connectCAS()
 {
     global $PHPCAS_CLIENT;
     if (!is_object($PHPCAS_CLIENT)) {
         // Make sure phpCAS doesn't try to start a new PHP session when connecting to the CAS server.
         if ($this->config->proxycas) {
             phpCAS::proxy($this->config->casversion, $this->config->hostname, (int) $this->config->port, $this->config->baseuri, false);
         } else {
             phpCAS::client($this->config->casversion, $this->config->hostname, (int) $this->config->port, $this->config->baseuri, false);
         }
     }
     if ($this->config->certificate_check && $this->config->certificate_path) {
         phpCAS::setCasServerCACert($this->config->certificate_path);
     } else {
         // Don't try to validate the server SSL credentials
         phpCAS::setNoCasServerValidation();
     }
 }
Ejemplo n.º 23
0
 /**
  * Constructor
  *
  * Carry out sanity checks to ensure the object is
  * able to operate. Set capabilities.
  *
  * @author     Fabian Bircher <*****@*****.**>
  */
 public function __construct()
 {
     parent::__construct();
     global $config_cascade;
     global $conf;
     // allow the preloading to configure other user files
     if (isset($config_cascade['plaincasauth.users']) && isset($config_cascade['plaincasauth.users']['default'])) {
         $this->casuserfile = $config_cascade['plaincasauth.users']['default'];
     } else {
         $this->casuserfile = DOKU_CONF . 'users.auth.plaincas.php';
     }
     $this->localuserfile = $config_cascade['plainauth.users']['default'];
     // check the state of the file with the users and attempt to create it.
     if (!@is_readable($this->casuserfile)) {
         if (!fopen($this->casuserfile, 'w')) {
             msg("plainCAS: The CAS users file could not be opened.", -1);
             $this->success = false;
         } elseif (!@is_readable($this->casuserfile)) {
             $this->success = false;
         } else {
             $this->success = true;
         }
         // die( "bitch!" );
     }
     if ($this->success) {
         // the users are not managable through the wiki
         $this->cando['addUser'] = false;
         $this->cando['delUser'] = true;
         $this->cando['modLogin'] = false;
         //keep this false as CAS name is constant
         $this->cando['modPass'] = false;
         $this->cando['modName'] = false;
         $this->cando['modMail'] = false;
         $this->cando['modGroups'] = false;
         $this->cando['getUsers'] = true;
         $this->cando['getUserCount'] = true;
         $this->cando['external'] = preg_match("#(bot)|(slurp)|(netvibes)#i", $_SERVER['HTTP_USER_AGENT']) ? false : true;
         //Disable CAS redirection for bots/crawlers/readers
         $this->cando['login'] = true;
         $this->cando['logout'] = true;
         $this->cando['logoff'] = true;
         // The default options which need to be set in the settins file.
         $defaults = array('logFile' => NULL, 'cert' => NULL, 'cacert' => NULL, 'debug' => false, 'settings_file' => DOKU_CONF . 'plaincas.settings.php', 'defaultgroup' => $conf['defaultgroup'], 'superuser' => $conf['superuser']);
         $this->_options = (array) $conf['plugin']['authplaincas'] + $defaults;
         // Options are set in the configuration and have a proper default value there.
         $this->_options['server'] = $this->getConf('server');
         $this->_options['rootcas'] = $this->getConf('rootcas');
         $this->_options['port'] = $this->getConf('port');
         $this->_options['samlValidate'] = $this->getConf('samlValidate');
         $this->_options['autologin'] = $this->getConf('autologinout');
         // $this->getConf('autologin');
         $this->_options['caslogout'] = $this->getConf('autologinout');
         // $this->getConf('caslogout');
         $this->_options['handlelogoutrequest'] = $this->getConf('handlelogoutrequest');
         $this->_options['handlelogoutrequestTrustedHosts'] = $this->getConf('handlelogoutrequestTrustedHosts');
         $this->_options['minimalgroups'] = $this->getConf('minimalgroups');
         $this->_options['localusers'] = $this->getConf('localusers');
         // $this->_options['defaultgroup'] = $this->getConf('defaultgroup');
         // $this->_options['superuser'] = $this->getConf('superuser');
         // no local users at the moment
         $this->_options['localusers'] = false;
         if ($this->_options['localusers'] && !@is_readable($this->localuserfile)) {
             msg("plainCAS: The local users file is not readable.", -1);
             $this->success = false;
         }
         if ($this->_getOption("logFile")) {
             phpCAS::setDebug($this->_getOption("logFile"));
         }
         //If $conf['auth']['cas']['logFile'] exist we start phpCAS in debug mode
         $server_version = CAS_VERSION_2_0;
         if ($this->_getOption("samlValidate")) {
             $server_version = SAML_VERSION_1_1;
         }
         phpCAS::client($server_version, $this->_getOption('server'), (int) $this->_getOption('port'), $this->_getOption('rootcas'), true);
         //Note the last argument true, to allow phpCAS to change the session_id so he will be able to destroy the session after a CAS logout request - Enable Single Sign Out
         // curl extension is needed
         if (!function_exists('curl_init')) {
             if ($this->_getOption('debug')) {
                 msg("CAS err: CURL extension not found.", -1, __LINE__, __FILE__);
             }
             $this->success = false;
             return;
         }
         // automatically log the user when there is a cas session opened
         if ($this->_getOption('autologin')) {
             phpCAS::setCacheTimesForAuthRecheck(1);
         } else {
             phpCAS::setCacheTimesForAuthRecheck(-1);
         }
         if ($this->_getOption('cert')) {
             phpCAS::setCasServerCert($this->_getOption('cert'));
         } elseif ($this->_getOption('cacert')) {
             phpCAS::setCasServerCACert($this->_getOption('cacert'));
         } else {
             phpCAS::setNoCasServerValidation();
         }
         if ($this->_getOption('handlelogoutrequest')) {
             phpCAS::handleLogoutRequests(true, $this->_getOption('handlelogoutrequestTrustedHosts'));
         } else {
             phpCAS::handleLogoutRequests(false);
         }
         if (@is_readable($this->_getOption('settings_file'))) {
             include_once $this->_getOption('settings_file');
         } else {
             include_once DOKU_PLUGIN . 'authplaincas/plaincas.settings.php';
         }
     }
     //
 }
Ejemplo n.º 24
0
 */
return function (Slim\App $app) {
    $container = $app->getContainer();
    $events = $container['events'];
    $events('on', 'app.autoload', function ($autoloader) {
        $autoloader->addPsr4('SchSSO\\', __DIR__ . '/src/');
    });
    $events('on', 'app.services', function ($container) {
        $container['init_cas'] = $container->protect(function () use($container) {
            $settings = $container['settings']['sso']['phpcas'];
            phpCAS::client($settings['serverVersion'], $settings['serverHostname'], $settings['serverPort'], $settings['serverUri'], $settings['changeSessionId']);
            if ($casServerCaCert = $settings['casServerCaCert']) {
                if ($settings['casServerCnValidate']) {
                    phpCAS::setCasServerCACert($casServerCaCert, true);
                } else {
                    phpCAS::setCasServerCACert($casServerCaCert, false);
                }
            }
            if ($settings['noCasServerValidation']) {
                phpCAS::setNoCasServerValidation();
            }
            phpCAS::handleLogoutRequests();
        });
        $container['is_allowed'] = $container->protect(function ($attributes) use($container) {
            $allowed = isset($container['settings']['sso']['allowed']) ? $container['settings']['sso']['allowed'] : [];
            foreach ($allowed as $index => $ruleset) {
                $isAllowed[$index] = true;
                foreach ($ruleset as $attribute => $rule) {
                    if (!isset($attributes[$attribute])) {
                        $isAllowed[$index] = false;
                        break;
Ejemplo n.º 25
0
    // C'est idiot car cette valeur n'est pas fiable, n'importe qui peut présenter n'importe quel User-Agent !
    // En attendant qu'ils appliquent un remède plus intelligent, et au cas où un autre prestataire aurait la même mauvaise idée, on envoie un User-Agent bidon (défini dans le loader)...
    phpCAS::setExtraCurlOption(CURLOPT_USERAGENT, CURL_AGENT);
    // Appliquer un proxy si défini par le webmestre ; voir cURL::get_contents() pour les commentaires.
    if (defined('SERVEUR_PROXY_USED') && SERVEUR_PROXY_USED) {
        phpCAS::setExtraCurlOption(CURLOPT_PROXY, SERVEUR_PROXY_NAME);
        phpCAS::setExtraCurlOption(CURLOPT_PROXYPORT, (int) SERVEUR_PROXY_PORT);
        phpCAS::setExtraCurlOption(CURLOPT_PROXYTYPE, constant(SERVEUR_PROXY_TYPE));
        if (SERVEUR_PROXY_AUTH_USED) {
            phpCAS::setExtraCurlOption(CURLOPT_PROXYAUTH, constant(SERVEUR_PROXY_AUTH_METHOD));
            phpCAS::setExtraCurlOption(CURLOPT_PROXYUSERPWD, SERVEUR_PROXY_AUTH_USER . ':' . SERVEUR_PROXY_AUTH_PASS);
        }
    }
    // On indique qu'il faut vérifier la validité du certificat SSL, sauf exception paramétrée, mais alors dans ce cas ça ne sert à rien d'utiliser une connexion sécurisée.
    if (strpos(PHPCAS_NO_CERTIF_LISTING, ',' . $connexion_nom . ',') === FALSE) {
        phpCAS::setCasServerCACert(CHEMIN_FICHIER_CA_CERTS_FILE);
    } else {
        phpCAS::setNoCasServerValidation();
    }
    // Gestion du single sign-out
    phpCAS::handleLogoutRequests(FALSE);
    // Déconnexion de CAS
    phpCAS::logout();
    exit;
}
// ////////////////////////////////////////////////////////////////////////////////////////////////////
// Déconnexion avec Shibboleth
// ////////////////////////////////////////////////////////////////////////////////////////////////////
if ($connexion_mode == 'shibboleth') {
    /*
    Pour le moment, on a acté avec le Catice qu'une déconnexion depuis une application entrainera seulement une déconnexion de cette application.
Ejemplo n.º 26
0
 /**
  * Plugin initialization, action & filters register, etc
  */
 function init($run_cas = true)
 {
     global $error;
     if ($run_cas) {
         /**
          * phpCAS initialization
          */
         include_once $this->phpcas_path;
         if ($this->settings['server_hostname'] == '' || intval($this->settings['server_port']) == 0) {
             $this->cas_configured = false;
         }
         if ($this->cas_configured) {
             //If everything is alright, let's initialize the phpCAS client
             phpCAS::client($this->settings['cas_version'], $this->settings['server_hostname'], intval($this->settings['server_port']), $this->settings['server_path'], false);
             // function added in phpCAS v. 0.6.0
             // checking for static method existance is frustrating in php4
             $phpCas = new phpCas();
             if (method_exists($phpCas, 'setCasServerCACert') && $this->settings['cert_path']) {
                 phpCAS::setCasServerCACert($this->settings['cert_path']);
             } elseif (method_exists($phpCas, 'setNoCasServerValidation')) {
                 phpCAS::setNoCasServerValidation();
             }
             unset($phpCas);
             if (defined('CAS_MAESTRO_DEBUG_ON') && CAS_MAESTRO_DEBUG_ON == true) {
                 phpCAS::setDebug(CAS_MAESTRO_PLUGIN_PATH . 'debug.log');
             }
             /**
              * Filters and actions registration
              */
             add_filter('authenticate', array(&$this, 'validate_login'), 30, 3);
             add_filter('login_url', array(&$this, 'bypass_reauth'));
             add_action('lost_password', array(&$this, 'disable_function'));
             add_action('retrieve_password', array(&$this, 'disable_function'));
             add_action('password_reset', array(&$this, 'disable_function'));
             add_filter('show_password_fields', array(&$this, 'show_password_fields'));
         } else {
             $error = __("wpCAS is not configured. Please, login, go to the settings and configure with your credentials.", "CAS_Maestro");
             //add_filter( 'login_head', array(&$this, 'display_login_notconfigured'));
         }
     }
     add_action('wp_logout', array(&$this, 'process_logout'));
     //Register the language initialization
     add_action('init', array(&$this, 'lang_init'));
     add_action('admin_init', array(&$this, 'add_meta_boxes'));
     add_action('profile_update', array(&$this, 'onSaveProfile'), 10, 2);
     add_action('admin_notices', array(&$this, 'notify_email_update'));
     add_action('admin_menu', array(&$this, 'register_menus'), 50);
     add_action('admin_enqueue_scripts', array(&$this, 'register_javascript'));
     //Filter to rewrite the login form action to bypass cas
     if ($this->bypass_cas) {
         add_filter('site_url', array(&$this, 'bypass_cas_login_form'), 20, 3);
         add_filter('authenticate', array(&$this, 'validate_noncas_login'), 30, 3);
     }
 }
Ejemplo n.º 27
0
 * ownCloud - user_cas
 *
 * @author Sixto Martin <*****@*****.**>
 * @copyright Sixto Martin Garcia. 2012
 * @copyright Leonis. 2014 <*****@*****.**>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
 * License as published by the Free Software Foundation; either
 * version 3 of the License, or any later version.
 *
 * This library 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 AFFERO GENERAL PUBLIC LICENSE for more details.
 *
 * You should have received a copy of the GNU Affero General Public
 * License along with this library.  If not, see <http://www.gnu.org/licenses/>.
 *
 */
global $initialized_cas;
if (!$initialized_cas) {
    phpCAS::client($casVersion, $casHostname, (int) $casPort, $casPath, false);
    if (!empty($casCertPath)) {
        phpCAS::setCasServerCACert($casCertPath);
    } else {
        phpCAS::setNoCasServerValidation();
    }
    $initialized_cas = true;
}
phpCAS::forceAuthentication();
Ejemplo n.º 28
0
    /**
     * Initialize CAS client
     * 
     */
    private function cas_init() {
        if (!$this->cas_inited) {
            // retrieve configurations
            $cfg = rcmail::get_instance()->config->all();

            // include phpCAS
			require_once('/usr/share/php/CAS/CAS.php');
			phpCAS::setDebug('/var/log/lcs/casdebug.log');
            
            // initialize CAS client
            if ($cfg['cas_proxy']) {
                phpCAS::proxy(CAS_VERSION_2_0, $cfg['cas_hostname'], $cfg['cas_port'], $cfg['cas_uri'], false);

                // set URL for PGT callback
                phpCAS::setFixedCallbackURL($this->generate_url(array('action' => 'pgtcallback')));
                
                // set PGT storage
                #phpCAS::setPGTStorageFile('xml', $cfg['cas_pgt_dir']);
				phpCAS::setPGTStorageFile($cfg['cas_pgt_dir']);
            }
            else {
                phpCAS::client(CAS_VERSION_2_0, $cfg['cas_hostname'], $cfg['cas_port'], $cfg['cas_uri'], false);
            }

            // set service URL for authorization with CAS server
            phpCAS::setFixedServiceURL($this->generate_url(array('action' => 'login', 'task' => 'mail')));

            // set SSL validation for the CAS server
            if ($cfg['cas_validation'] == 'self') {
                phpCAS::setCasServerCert($cfg['cas_cert']);
            }
            else if ($cfg['cas_validation'] == 'ca') {
                phpCAS::setCasServerCACert($cfg['cas_cert']);
            }
            else {
                phpCAS::setNoCasServerValidation();
            }

            // set login and logout URLs of the CAS server
            phpCAS::setServerLoginURL($cfg['cas_login_url']);
            phpCAS::setServerLogoutURL($cfg['cas_logout_url']);

            $this->cas_inited = true;
        }
    }
Ejemplo n.º 29
0
 static function casLoginProcess()
 {
     global $config, $message, $ui;
     self::init();
     /* Reset error messages */
     $message = '';
     //~ phpCAS::setDebug();
     // Initialize phpCAS
     phpCAS::client(CAS_VERSION_2_0, $config->get_cfg_value('casHost', 'localhost'), (int) $config->get_cfg_value('casPort', 443), $config->get_cfg_value('casContext', ''));
     // Set the CA certificate that is the issuer of the cert
     phpCAS::setCasServerCACert($config->get_cfg_value('casServerCaCertPath'));
     //~ phpCAS::setNoCasServerValidation();
     // force CAS authentication
     phpCAS::forceAuthentication();
     self::$username = phpCAS::getUser();
     $ldap = $config->get_ldap_link();
     $ldap->cd($config->current['BASE']);
     $verify_attr = explode(',', $config->get_cfg_value('loginAttribute', 'uid'));
     $filter = '';
     foreach ($verify_attr as $attr) {
         $filter .= '(' . $attr . '=' . self::$username . ')';
     }
     $ldap->search('(&(|' . $filter . ')(objectClass=inetOrgPerson))');
     $attrs = $ldap->fetch();
     if ($ldap->count() < 1) {
         msg_dialog::display(_('Error'), sprintf(_('CAS user "%s" could not be found in the LDAP'), self::$username), FATAL_ERROR_DIALOG);
         exit;
     } elseif ($ldap->count() > 1) {
         msg_dialog::display(_('Error'), sprintf(_('CAS user "%s" match several users in the LDAP'), self::$username), FATAL_ERROR_DIALOG);
         exit;
     }
     $ui = new userinfo($config, $attrs['dn']);
     $ui->loadACL();
     $success = self::runSteps(array('loginAndCheckExpired', 'runSchemaCheck', 'checkForLockingBranch'));
     if ($success) {
         /* Everything went well, redirect to main.php */
         self::redirect();
     }
 }
Ejemplo n.º 30
0
 /**
  * Establishes phpCAS Configuration and Enables the phpCAS Client
  *
  * @return object     Returns phpCAS Object
  */
 protected function setupCAS()
 {
     $casauth = new \phpCAS();
     // Check to see if phpCAS has already been setup. If it has, than skip as
     // client can only be called once.
     if (!$this->phpCASSetup) {
         $cas = $this->getConfig()->CAS;
         if (isset($cas->log) && !empty($cas->log) && isset($cas->debug) && $cas->debug) {
             $casauth->setDebug($cas->log);
         }
         $casauth->client(SAML_VERSION_1_1, $cas->server, (int) $cas->port, $cas->context, false);
         if (isset($cas->CACert) && !empty($cas->CACert)) {
             $casauth->setCasServerCACert($cas->CACert);
         } else {
             $casauth->setNoCasServerValidation();
         }
         $this->phpCASSetup = true;
     }
     return $casauth;
 }