protected function _loadEntityMetadata($entityId)
 {
     $janusConfig = SimpleSAML_Configuration::getConfig('module_janus.php');
     $entityController = new sspmod_janus_EntityController($janusConfig);
     $entityController->setEntity($entityId);
     $entityController->loadEntity();
     $this->_entityMetadata = $entityController->getMetaArray();
 }
 protected function _loadEntity($entityId)
 {
     $janusConfig = SimpleSAML_Configuration::getConfig('module_janus.php');
     $entityController = new sspmod_janus_EntityController($janusConfig);
     $entityController->setEntity($entityId);
     $entityController->loadEntity();
     $this->_entityController = $entityController;
     return $entityController ? true : false;
 }
 /**
  * Delete the ARP identified by the aid.
  *
  * @return PDOStatement|false The statement or false on error.
  */
 public function delete()
 {
     if (empty($this->_aid)) {
         SimpleSAML_Logger::error('JANUS:ARP:delete - aid needs to be set.');
         return false;
     }
     $deleteStatement = $this->execute('UPDATE ' . self::$prefix . 'arp SET
         `deleted` = ?
         WHERE `aid` = ?;', array(date('c'), $this->_aid));
     if ($deleteStatement === false) {
         return false;
     }
     // Get all entities with the just removed ARP
     $st = $this->execute('SELECT eid
         FROM ' . self::$prefix . 'entity
         WHERE `arp` = ?;', array($this->_aid));
     if (!$st) {
         return $deleteStatement;
     }
     $janus_config = SimpleSAML_Configuration::getConfig('module_janus.php');
     $controller = new sspmod_janus_EntityController($janus_config);
     // Remove the ARP from all entities
     $entity_rows = $st->fetchAll();
     foreach ($entity_rows as $entity_row) {
         $controller->setEntity($entity_row['eid']);
         $controller->loadEntity();
         $controller->setArp('0');
         $controller->saveEntity();
     }
     return $deleteStatement;
 }
 protected function _loadEntityCertificate($entityId)
 {
     $janusConfig = SimpleSAML_Configuration::getConfig('module_janus.php');
     $entityController = new sspmod_janus_EntityController($janusConfig);
     $entityController->setEntity($entityId);
     $entityController->loadEntity();
     try {
         $certificate = $entityController->getCertificate();
     } catch (Exception $e) {
         $this->_response->Errors[] = "Certificate data invalid!";
         return false;
     }
     if (!$certificate) {
         $this->_response->Warnings[] = "No certificate data for this entity";
         return false;
     }
     $this->_certificate = $certificate;
     return true;
 }
 protected function _validate($metadataConfig)
 {
     $entityMetadata = $this->_loadImplodedEntityMetadata($this->_entityController->getMetaArray());
     foreach ($metadataConfig as $k => $v) {
         // Required field
         $errors = array();
         $warnings = array();
         // Missing required field
         if (!array_key_exists($k, $entityMetadata) && $this->_isRequired($v)) {
             $errors[] = self::$_MISSING_REQUIRED_FIELD;
             $this->_setValidations($k, $errors, $warnings);
         } else {
             if (array_key_exists($k, $entityMetadata)) {
                 $this->_validateDefaultValue($entityMetadata, $k, $v, $errors, $warnings);
                 $this->_validateCustomValidates($entityMetadata, $k, $v, $errors, $warnings);
                 $this->_setValidations($k, $errors, $warnings);
             }
         }
         // Do nothing is key is not present and field is not required
     }
 }
Esempio n. 6
0
 /**
  * If a metadata document for a Service Provider specified 'RequestedAttribute' elements, then we
  * add that as an ARP.
  *
  * @param array $parsedMetadata SAMLParser output
  * @return array SAMLParser output without 'attributes'.
  */
 private function _applyRequestedAttributesAsArp(array $parsedMetadata)
 {
     if (!isset($parsedMetadata['attributes'])) {
         return $parsedMetadata;
     }
     $arpAttributes = $this->getAllowedArpAttributes();
     $requestedAttributes = $this->denormalizeAttributes($parsedMetadata['attributes']);
     $arp = array();
     foreach ($requestedAttributes as $requestedAttribute) {
         // Skip attributes not allowed in an ARP.
         if (!in_array($requestedAttribute, $arpAttributes)) {
             continue;
         }
         $arp[$requestedAttribute] = array('*');
     }
     $this->_entityController->setArpAttributes($arp);
     unset($parsedMetadata['attributes']);
     return $parsedMetadata;
 }
 $query = '/md:EntityDescriptor';
 $entity = $xpath->query($query);
 $entityid = $entity->item(0)->getAttribute('entityID');
 $query = '/md:EntityDescriptor/md:SPSSODescriptor';
 $sp = $xpath->query($query);
 if ($sp->length > 0) {
     $type = 'saml20-sp';
 }
 $query = '/md:EntityDescriptor/md:IDPSSODescriptor';
 $idp = $xpath->query($query);
 if ($idp->length > 0) {
     $type = 'saml20-idp';
 }
 $msg = $mcontrol->createNewEntity($entityid, $type);
 if (is_int($msg)) {
     $econtroller = new sspmod_janus_EntityController($janus_config);
     $econtroller->setEntity((string) $msg);
     $econtroller->loadEntity();
     $pm->subscribe($user->getUid(), 'ENTITYUPDATE-' . $msg);
     $directlink = SimpleSAML_Module::getModuleURL('janus/editentity.php', array('eid' => $msg));
     $pm->post('New entity created', 'Permalink: <a href="' . $directlink . '">' . $directlink . '</a><br /><br />A new entity has been created.<br />Entityid: ' . $_POST['entityid'] . '<br />Entity type: ' . $_POST['entitytype'], 'ENTITYCREATE', $user->getUid());
     $msg = 'text_entity_created';
     if ($type == 'saml20-sp') {
         $msg = $econtroller->importMetadata20SP($_POST['metadata_xml'], $update);
     } else {
         if ($type == 'saml20-idp') {
             $msg = $econtroller->importMetadata20IdP($_POST['metadata_xml'], $update);
         } else {
             $msg = 'error_metadata_not_import';
         }
     }
                    }
                }
            }
            echo '-------------------------------------';
        }
        $econtroller->saveEntity();
        echo $key . ' imported<br />';
    }
}
echo '<h1>SAML20 SP</h1>';
include 'saml20-sp-remote.php';
foreach ($metadata as $key => $val) {
    $msg = $mcontrol->createNewEntity($key, 'saml20-sp');
    echo "Id: " . $msg . '<br />';
    if (is_int($msg)) {
        $econtroller = new sspmod_janus_EntityController($janus_config);
        $econtroller->setEntity((string) $msg);
        $econtroller->loadEntity();
        foreach ($val as $k => $v) {
            if ($k == 'attributes') {
                $arp = new sspmod_janus_ARP();
                $arp->setName($key);
                $arp->setAttributes($v);
                $arp->save();
                $econtroller->setArp($arp->getAid());
            }
            if ($k == 'name') {
                $k = 'entity:name';
            }
            if ($k == 'description') {
                $k = 'entity:description';
$session = SimpleSAML_Session::getInstance();
$janusConfig = SimpleSAML_Configuration::getConfig('module_janus.php');
$authSource = $janusConfig->getValue('auth', 'login-admin');
// Validate user
if (!$session->isValid($authSource)) {
    SimpleSAML_Utilities::redirect(SimpleSAML_Module::getModuleURL('janus/index.php', array('selectedtab' => "'federation'")));
}
$entities = array();
$util = new sspmod_janus_AdminUtil();
$userController = new sspmod_janus_UserController($janusConfig);
$entities = array_merge($userController->searchEntitiesByType('saml20-idp'), $userController->searchEntitiesByType('saml20-sp'));
foreach ($entities as $entity) {
    /**
     * @var sspmod_janus_Entity $entity
     */
    $entityId = $entity->getEid();
    $entityController = new sspmod_janus_EntityController($janusConfig);
    $entityController->setEntity($entityId);
    $entityController->loadEntity();
    $controllerEntity = $entityController->getEntity();
    $entityType = $controllerEntity->getType();
    if (!isset($entities[$entityType])) {
        $entities[$entityType] = array();
    }
    $entities_info[$entityType][] = array('Id' => $controllerEntity->getEntityid(), 'Name' => $controllerEntity->getPrettyname(), 'WorkflowStatus' => $controllerEntity->getWorkflow(), 'MetadataUrl' => $controllerEntity->getMetadataURL(), 'Eid' => $controllerEntity->getEid());
}
ksort($entities_info);
$template = new SimpleSAML_XHTML_Template(SimpleSAML_Configuration::getInstance(), 'janus:show-entities-validation.php', 'janus:show-entities-validation');
$template->data['header'] = "Service Registry JANUS entities validation";
$template->data['entities'] = $entities_info;
$template->show();
$metaentries = array('saml20-idp' => array(), 'saml20-sp' => array(), 'shib13-idp' => array(), 'shib13-sp' => array());
$now = time();
$util = new sspmod_janus_AdminUtil();
if (SimpleSAML_Module::isModuleEnabled('x509')) {
    $strict_cert_validation = $janus_config->getBoolean('cert.strict.validation', true);
    $cert_allowed_warnings = $janus_config->getArray('cert.allowed.warnings', array());
    $cert_time_limit = $janus_config->getInteger('notify.cert.expiring.before', 30);
}
$notify_meta_expiring_before = $janus_config->getInteger('notify.meta.expiring.before', 5);
$meta_time_limit = $now + $notify_meta_expiring_before * 86400;
$workflowstates = $janus_config->getValue('workflowstates');
foreach ($util->getEntities() as $entity) {
    $entry = array();
    $eid = $entity['eid'];
    // Get Entity controller
    $mcontroller = new sspmod_janus_EntityController($janus_config);
    $mcontroller->setEntity($eid);
    $mcontroller->loadEntity();
    // Grab some basic fields
    $metadata = $mcontroller->getMetadata();
    $entity_id = $mcontroller->getEntity()->getEntityid();
    $entity_type = $mcontroller->getEntity()->getType();
    $prettyname = $mcontroller->getEntity()->getPrettyname();
    $entity_workflow = $mcontroller->getEntity()->getWorkflow();
    $metaArray = $mcontroller->getMetaArray();
    $entry['entityid'] = $entity_id;
    $entry['entitytype'] = $entity_type;
    $entry['prettyname'] = $prettyname;
    $entry['workflow'] = $entity_workflow;
    // Check if the entity has all the required fields
    $metadata_alowed = $janus_config->getArray('metadatafields.' . $entity_type, array());
 public function runForCronTag($cronTag)
 {
     if (!$this->_isExecuteRequired($cronTag)) {
         return array("Not doing metadata_refresh");
     }
     $cronLogger = new sspmod_janus_Cron_Logger();
     try {
         $janusConfig = SimpleSAML_Configuration::getConfig('module_janus.php');
         $util = new sspmod_janus_AdminUtil();
         $entities = $util->getEntities();
         foreach ($entities as $partialEntity) {
             $entityController = new sspmod_janus_EntityController($janusConfig);
             $eid = $partialEntity['eid'];
             if (!$entityController->setEntity($eid)) {
                 $cronLogger->with($eid)->error("Failed import of entity. Wrong eid '{$eid}'.");
                 continue;
             }
             $entityController->loadEntity();
             $entity = $entityController->getEntity();
             $entityId = $entity->getEntityId();
             $metadataUrl = $entity->getMetadataURL();
             $metadataCachingInfo = $entityController->getMetadataCaching();
             if (empty($metadataUrl)) {
                 $cronLogger->with($entityId)->warn("No metadata url.");
                 continue;
             }
             $nextRun = time();
             switch ($cronTag) {
                 case 'hourly':
                     $nextRun += 3600;
                     break;
                 case 'daily':
                     $nextRun += 24 * 60 * 60;
                     break;
                 case 'frequent':
                     $nextRun += 0;
                     // How often is frequent?
                     break;
                 default:
                     throw new Exception("Unknown cron tag '{$cronTag}'");
             }
             if ($metadataCachingInfo['validUntil'] > $nextRun && $metadataCachingInfo['cacheUntil'] > $nextRun) {
                 $cronLogger->with($entityId)->notice("Should not update, cache still valid.");
                 continue;
             }
             $xml = @file_get_contents($metadataUrl);
             if (!$xml) {
                 $cronLogger->with($entityId)->error("Failed import of entity. Bad URL '{$metadataUrl}'? ");
                 continue;
             }
             $document = new DOMDocument();
             if (!@$document->loadXML($xml)) {
                 $cronLogger->with($entityId)->error("Failed import of entity. Invalid XML at '{$metadataUrl}'?");
                 continue;
             }
             $query = new DOMXPath($document);
             $nsFound = false;
             foreach ($query->query('namespace::*') as $node) {
                 if ($node->nodeValue === "urn:oasis:names:tc:SAML:2.0:metadata") {
                     $nsFound = true;
                     break;
                 }
             }
             if (!$nsFound) {
                 $cronLogger->with($entityId)->error("Failed import of entity. Metadata at '{$metadataUrl}' does not contain SAML2 Metadata namespace?");
                 continue;
             }
             $query->registerNamespace('md', "urn:oasis:names:tc:SAML:2.0:metadata");
             $entityDescriptorDomElement = $query->query("//md:EntityDescriptor[@entityID=\"{$entityId}\"]");
             if ($entityDescriptorDomElement->length === 0) {
                 $cronLogger->with($entityId)->error("Failed import of entity. Metadata at '{$metadataUrl}' does not contain an EntityDescriptor with entityId '{$entityId}'?");
                 continue;
             }
             $updated = false;
             if ($entity->getType() == 'saml20-sp') {
                 $statusCode = $entityController->importMetadata20SP($xml, $updated);
                 if ($statusCode !== 'status_metadata_parsed_ok') {
                     $cronLogger->with($entityId)->error("Entity not updated");
                 }
             } else {
                 if ($entity->getType() == 'saml20-idp') {
                     $statusCode = $entityController->importMetadata20IdP($xml, $updated);
                     if ($statusCode !== 'status_metadata_parsed_ok') {
                         $cronLogger->with($entityId)->error("Entity not updated");
                     }
                 } else {
                     $cronLogger->with($entityId)->error("Failed import of entity. Wrong type");
                 }
             }
             if ($updated) {
                 $this->_mailUpdatedMetaData($entity, $xml);
                 $cronLogger->with($entityId)->notice("Entity updated");
                 $metadataCachingInfo = $this->_getMetaDataCachingInfo($xml, $entityId);
                 $entityController->setMetadataCaching($metadataCachingInfo['validUntil'], $metadataCachingInfo['cacheUntil']);
             } else {
                 $cronLogger->with($entityId)->notice("Entity not updated, no changes required");
                 // Update metadata caching info (validUntil )
                 $metadataCachingInfo = $this->_getMetaDataCachingInfo($xml, $entityId);
                 $entityController->setMetadataCaching($metadataCachingInfo['validUntil'], $metadataCachingInfo['cacheUntil']);
             }
         }
     } catch (Exception $e) {
         $cronLogger->error($e->getMessage());
     }
     if ($cronLogger->hasErrors()) {
         $this->_mailTechnicalContact($cronTag, $cronLogger);
     }
     return $cronLogger->getSummaryLines();
 }
 protected static function _checkIdPMetadataIsConnectionAllowed(array $data, $revisionId = NULL)
 {
     $idpcontroller = new sspmod_janus_EntityController(SimpleSAML_Configuration::getConfig('module_janus.php'));
     $idpcontroller->setEntity($data['idpentityid'], $revisionId);
     if ($idpcontroller->getAllowedAll() != "yes") {
         $idpblocked = $idpcontroller->getBlockedEntities();
         if (count($idpblocked) && !array_key_exists($data['spentityid'], $idpblocked)) {
             return true;
         }
         $idpallowed = $idpcontroller->getAllowedEntities();
         if (count($idpallowed) && array_key_exists($data['spentityid'], $idpallowed)) {
             return true;
         }
         return false;
     }
     return true;
 }
    $userid = $attributes[$useridattr][0];
} else {
    $session->setData('string', 'refURL', SimpleSAML_Utilities::selfURL());
    SimpleSAML_Utilities::redirect(SimpleSAML_Module::getModuleURL('janus/index.php'));
}
function check_uri($uri)
{
    if (preg_match('/^[a-z][a-z0-9+-\\.]*:.+$/i', $uri) == 1) {
        return TRUE;
    }
    return FALSE;
}
// Get metadata to present remote entitites
$metadata = SimpleSAML_Metadata_MetaDataStorageHandler::getMetadataHandler();
// Get Entity controller
$mcontroller = new sspmod_janus_EntityController($janus_config);
// Get the user
$user = new sspmod_janus_User($janus_config->getValue('store'));
$user->setUserid($userid);
$user->load(sspmod_janus_User::USERID_LOAD);
// Get Admin util which we use to retrieve entities
$autil = new sspmod_janus_AdminUtil();
// Function to fix up PHP's messing up POST input containing dots, etc.
function getRealPOST()
{
    $vars = array();
    $input = file_get_contents("php://input");
    if (!empty($input)) {
        $pairs = explode("&", $input);
        foreach ($pairs as $pair) {
            $nv = explode("=", $pair);
 private static function getMetadata($eid, $revision, $type = null, array $option = null)
 {
     assert('ctype_digit($eid)');
     assert('ctype_digit($revision)');
     $janus_config = SimpleSAML_Configuration::getConfig('module_janus.php');
     $econtroller = new sspmod_janus_EntityController($janus_config);
     if (!($entity = $econtroller->setEntity($eid, $revision))) {
         self::$_error = array('Entity could not be loaded - Eid: ' . $eid . ' Revisionid: ' . $revisionid);
         return false;
     }
     $metadata_raw = $econtroller->getMetadata();
     // Get metadata fields
     $nm_mb = new sspmod_janus_MetadatafieldBuilder($janus_config->getArray('metadatafields.' . $entity->getType()));
     $metadatafields_required = $nm_mb->getMetadatafields();
     // Get required metadata fields
     $required = array();
     foreach ($metadatafields_required as $mf) {
         if (isset($mf->required) && $mf->required === true) {
             $required[] = $mf->name;
         }
     }
     // Get metadata to me tested
     $metadata = array();
     foreach ($metadata_raw as $k => $v) {
         // Metadata field not defined
         if (!isset($metadatafields_required[$v->getKey()])) {
             continue;
         }
         // Value not set for metadata
         if (is_string($v->getValue()) && $v->getValue() == '') {
             continue;
         }
         // Compute is the default values is allowed
         $default_allow = false;
         if (isset($metadatafield_required[$v->getKey()]->default_allow) && is_bool($metadata_required[$v->getKey()]->default_allow)) {
             $default_allow = $metadata_required[$v->getKey()]->default_allow;
         }
         /*
          * Do not include metadata if value is set to default and default
          * is not allowed.
          */
         if (!$default_allow && (isset($metadata_required[$v->getKey()]->default) && $v->getValue() == $metadata_required[$v->getKey()]->default)) {
             continue;
         }
         $metadata[] = $v->getKey();
     }
     // Compute missing metadata that is required
     $missing_required = array_diff($required, $metadata);
     $entityid = $entity->getEntityid();
     if (empty($missing_required)) {
         try {
             $metaArray = $econtroller->getMetaArray();
             $metaArray['eid'] = $eid;
             $blocked_entities = $econtroller->getBlockedEntities();
             $allowed_entities = $econtroller->getAllowedEntities();
             $disable_consent = $econtroller->getDisableConsent();
             $metaflat = '// Revision: ' . $entity->getRevisionid() . "\n";
             $metaflat .= var_export($entityid, TRUE) . ' => ' . var_export($metaArray, TRUE) . ',';
             // Add authproc filter to block blocked entities
             if (!empty($blocked_entities) || !empty($allowed_entities)) {
                 $metaflat = substr($metaflat, 0, -2);
                 if (!empty($blocked_entities)) {
                     $metaflat .= "  'blocked' => array(\n";
                     foreach ($blocked_entities as $bentity => $value) {
                         $metaflat .= "    '" . $bentity . "',\n";
                     }
                     $metaflat .= "  ),\n";
                 }
                 if (!empty($allowed_entities)) {
                     $metaflat .= "  'allowed' => array(\n";
                     foreach ($allowed_entities as $aentity => $value) {
                         $metaflat .= "      '" . $aentity . "',\n";
                     }
                     $metaflat .= "  ),\n";
                 }
                 $metaflat .= '),';
             }
             // Add disable consent
             if (!empty($disable_consent)) {
                 $metaflat = substr($metaflat, 0, -2);
                 $metaflat .= "  'consent.disable' => array(\n";
                 foreach ($disable_consent as $key => $value) {
                     $metaflat .= "    '" . $key . "',\n";
                 }
                 $metaflat .= "  ),\n";
                 $metaflat .= '),';
             }
             $maxCache = isset($option['maxCache']) ? $option['maxCache'] : null;
             $maxDuration = isset($option['maxDuration']) ? $option['maxDuration'] : null;
             try {
                 $metaBuilder = new SimpleSAML_Metadata_SAMLBuilder($entityid, $maxCache, $maxDuration);
                 $metaBuilder->addMetadata($metaArray['metadata-set'], $metaArray);
             } catch (Exception $e) {
                 SimpleSAML_Logger::error('JANUS - Entity_id:' . $entityid . ' - Error generating XML metadata - ' . var_export($e, true));
                 self::$_error = array('Error generating XML metadata - ' . $e->getMessage());
                 return false;
             }
             // Add organization info
             if (!empty($metaArray['OrganizationName']) && !empty($metaArray['OrganizationDisplayName']) && !empty($metaArray['OrganizationURL'])) {
                 $metaBuilder->addOrganizationInfo(array('OrganizationName' => $metaArray['OrganizationName'], 'OrganizationDisplayName' => $metaArray['OrganizationDisplayName'], 'OrganizationURL' => $metaArray['OrganizationURL']));
             }
             // Add contact info
             if (!empty($metaArray['contact'])) {
                 $metaBuilder->addContact('technical', $metaArray['contact']);
             }
             switch ($type) {
                 case self::XML:
                     return $metaBuilder->getEntityDescriptor();
                 case self::XMLREADABLE:
                     return $metaBuilder->getEntityDescriptorText();
                 case self::PHPARRAY:
                     return $metaArray;
                 case self::FLATFILE:
                 default:
                     return $metaflat;
             }
         } catch (Exception $exception) {
             $session = SimpleSAML_Session::getInstance();
             SimpleSAML_Utilities::fatalError($session->getTrackID(), 'JANUS - Metadatageneration', $exception);
         }
     } else {
         SimpleSAML_Logger::error('JANUS - Missing required metadata fields. Entity_id:' . $entityid);
         self::$_error = $missing_required;
         return false;
     }
 }
// Added persistent, transient and unspecified to all entities as valid NameIDFormats
/**
 * DbPatch makes the following variables available to PHP patches:
 *
 * @var $this       DbPatch_Command_Patch_PHP
 * @var $writer     DbPatch_Core_Writer
 * @var $db         Zend_Db_Adapter_Abstract
 * @var $phpFile    string
 */
define('SAML2_NAME_ID_FORMAT_UNSPECIFIED', 'urn:oasis:names:tc:SAML:2.0:nameid-format:unspecified');
define('SAML2_NAME_ID_FORMAT_TRANSIENT', 'urn:oasis:names:tc:SAML:2.0:nameid-format:transient');
define('SAML2_NAME_ID_FORMAT_PERSISTENT', 'urn:oasis:names:tc:SAML:2.0:nameid-format:persistent');
$_SERVER['REMOTE_ADDR'] = '127.0.0.1';
$janusConfig = SimpleSAML_Configuration::getConfig('module_janus.php');
$userController = new sspmod_janus_UserController($janusConfig, sspmod_janus_DiContainer::getInstance()->getSecurityContext());
$userController->setUser('engine');
$entities = $userController->getEntities();
/** @var sspmod_janus_Entity $entity */
foreach ($entities as $entity) {
    if ($entity->getType() != 'saml20-sp') {
        continue;
    }
    $entity->setRevisionnote('patch-0015.php: Added persistent, transient and unspecified to all entities as valid NameIDFormats');
    $entityController = new sspmod_janus_EntityController($janusConfig);
    $entityController->setEntity($entity);
    $entityController->addMetadata('NameIDFormats:0', SAML2_NAME_ID_FORMAT_PERSISTENT);
    $entityController->addMetadata('NameIDFormats:1', SAML2_NAME_ID_FORMAT_TRANSIENT);
    $entityController->addMetadata('NameIDFormats:2', SAML2_NAME_ID_FORMAT_UNSPECIFIED);
    $entityController->saveEntity();
}
<?php

require_once '/opt/www/serviceregistry/www/_include.php';
#	$session = SimpleSAML_Session::getInstance();
$config = SimpleSAML_Configuration::getInstance();
$janus_config = SimpleSAML_Configuration::getConfig('module_janus.php');
$econtroller = new sspmod_janus_EntityController($janus_config);
$econtroller->setEntity('http://example.openconext.local');
$econtroller->addMetaData('SingleSignOnService', 'http://example.openconext.local');
#	$econtroller->saveEntity();
 /**
  * Create new entity with parsed entityid
  *
  * Create a new entity and give the user access to the entity.
  *
  * @param string $entityid Entity id for the new entity
  * @param string $type     Entity type
  *
  * @return sspmod_janus_Entity|bool Returns the entity or false on error.
  * @since Method available since Release 1.0.0
  */
 public function createNewEntity($entityid, $type)
 {
     assert('is_string($entityid)');
     assert('is_string($type)');
     if ($this->isEntityIdInUse($entityid, $errorMessage)) {
         return $errorMessage;
     }
     if ($this->hasEntityIdBeenUsed($entityid, $errorMessage)) {
         return $errorMessage;
     }
     $startstate = $this->_config->getString('workflowstate.default');
     // Get the default ARP
     $default_arp = '0';
     $st = $this->execute("SELECT aid FROM " . self::$prefix . "arp WHERE is_default = TRUE AND deleted = ''");
     if ($st) {
         $rows = $st->fetchAll();
         if (count($rows) === 1) {
             $default_arp = $rows[0]['aid'];
         }
     }
     // Instantiate a new entity
     $entity = new sspmod_janus_Entity($this->_config, true);
     $entity->setEntityid($entityid);
     $entity->setWorkflow($startstate);
     $entity->setType($type);
     $entity->setArp($default_arp);
     $entity->setUser($this->_user->getUid());
     $entity->setRevisionnote('Entity created.');
     $entity->save();
     $st = $this->execute('INSERT INTO ' . self::$prefix . 'hasEntity 
         (`uid`, `eid`, `created`, `ip`) 
         VALUES 
         (?, ?, ?, ?);', array($this->_user->getUid(), $entity->getEid(), date('c'), $_SERVER['REMOTE_ADDR']));
     if ($st === false) {
         return 'error_db';
     }
     $ec = new sspmod_janus_EntityController($this->_config);
     $ec->setEntity($entity);
     $update = false;
     // Get metadatafields for new type
     $nm_mb = new sspmod_janus_MetadatafieldBuilder($this->_config->getArray('metadatafields.' . $type));
     $metadatafields = $nm_mb->getMetadatafields();
     // Add all required fileds
     foreach ($metadatafields as $mf) {
         if (isset($mf->required) && $mf->required === true) {
             $ec->addMetadata($mf->name, $mf->default);
             $update = true;
         }
     }
     if ($update === true) {
         $ec->saveEntity();
     }
     // Reset list of entities
     $this->_entities = null;
     $this->_loadEntities();
     return $entity->getEid();
 }
Esempio n. 18
0
 /**
  * @param $entityId
  * @return \sspmod_janus_EntityController
  */
 protected function getEntityControllerForEntityId($entityId)
 {
     if (!isset($this->entityControllers[$entityId])) {
         $controller = new \sspmod_janus_EntityController($this->configuration);
         $controller->setEntity($entityId);
         $this->entityControllers[$entityId] = $controller;
     }
     return $this->entityControllers[$entityId];
 }
$useridattr = $janus_config->getValue('useridattr', 'eduPersonPrincipalName');
$et = new SimpleSAML_XHTML_Template($config, 'janus:editentity.php', 'janus:editentity');
// Validate user
if ($session->isValid($authsource)) {
    $attributes = $session->getAttributes();
    // Check if userid exists
    if (!isset($attributes[$useridattr])) {
        throw new Exception('User ID is missing');
    }
    $userid = $attributes[$useridattr][0];
} else {
    echo $et->t('error_no_access');
    exit;
}
// Get Entity controller
$mcontroller = new sspmod_janus_EntityController($janus_config);
// Get the user
$user = new sspmod_janus_User($janus_config->getValue('store'));
$user->setUserid($userid);
$user->load(sspmod_janus_User::USERID_LOAD);
// Get the correct entity
$eid = $_GET['eid'];
if (!($entity = $mcontroller->setEntity($eid))) {
    throw new SimpleSAML_Error_Exception('Error in setEntity');
}
$workflowstates = $janus_config->getValue('workflowstates');
// load entity
$mcontroller->loadEntity();
// Check if user is allowed to se entity
$allowedUsers = $mcontroller->getUsers();
$uiguard = new sspmod_janus_UIguard($janus_config->getValue('access'));
 public function runForCronTag($cronTag)
 {
     if (!$this->_isExecuteRequired($cronTag)) {
         return array();
     }
     $cronLogger = new sspmod_janus_Cron_Logger();
     try {
         $janusConfig = SimpleSAML_Configuration::getConfig('module_janus.php');
         $srConfig = SimpleSAML_Configuration::getConfig('module_janus.php');
         $rootCertificatesFile = $srConfig->getString('ca_bundle_file');
         $util = new sspmod_janus_AdminUtil();
         $entities = $util->getEntities();
         foreach ($entities as $partialEntity) {
             try {
                 $entityController = new sspmod_janus_EntityController($janusConfig);
                 $eid = $partialEntity['eid'];
                 if (!$entityController->setEntity($eid)) {
                     $cronLogger->with($eid)->error("Failed import of entity. Wrong eid '{$eid}'.");
                     continue;
                 }
                 $entityController->loadEntity();
                 $entityId = $entityController->getEntity()->getEntityid();
                 $entityType = $entityController->getEntity()->getType();
                 try {
                     try {
                         $certificate = $entityController->getCertificate();
                         // @workaround
                         // Since getCertificate() returns false when certificate does not exist following check is required to skip validation
                         if (empty($certificate)) {
                             throw new Exception('No certificate found');
                         }
                     } catch (Exception $e) {
                         if ($entityType === 'saml20-sp') {
                             $cronLogger->with($entityId)->notice("SP does not have a certificate");
                         } else {
                             if ($entityType === 'saml20-idp') {
                                 $cronLogger->with($entityId)->warn("Unable to create certificate object, certData missing?");
                             }
                         }
                         continue;
                     }
                     $validator = new sspmod_janus_OpenSsl_Certificate_Validator($certificate);
                     $validator->setIgnoreSelfSigned(true);
                     $validator->validate();
                     $validatorWarnings = $validator->getWarnings();
                     $validatorErrors = $validator->getErrors();
                     foreach ($validatorWarnings as $warning) {
                         $cronLogger->with($entityId)->warn($warning);
                     }
                     foreach ($validatorErrors as $error) {
                         $cronLogger->with($entityId)->error($error);
                     }
                     sspmod_janus_OpenSsl_Certificate_Chain_Factory::loadRootCertificatesFromFile($rootCertificatesFile);
                     $chain = sspmod_janus_OpenSsl_Certificate_Chain_Factory::createFromCertificateIssuerUrl($certificate);
                     $validator = new sspmod_janus_OpenSsl_Certificate_Chain_Validator($chain);
                     $validator->setIgnoreSelfSigned(true);
                     $validator->setTrustedRootCertificateAuthorityFile($rootCertificatesFile);
                     $validator->validate();
                     $validatorWarnings = $validator->getWarnings();
                     $validatorErrors = $validator->getErrors();
                     foreach ($validatorWarnings as $warning) {
                         $cronLogger->with($entityId)->warn($warning);
                     }
                     foreach ($validatorErrors as $error) {
                         $cronLogger->with($entityId)->error($error);
                     }
                 } catch (Exception $e) {
                     $cronLogger->with($entityId)->error($e->getMessage());
                 }
             } catch (Exception $e) {
                 $cronLogger->error($e->getMessage() . $e->getTraceAsString());
             }
         }
     } catch (Exception $e) {
         $cronLogger->error($e->getMessage() . $e->getTraceAsString());
     }
     if ($cronLogger->hasErrors()) {
         $this->_mailTechnicalContact($cronTag, $cronLogger);
     }
     return $cronLogger->getSummaryLines();
 }