From 16e591a84a98a15ee7bd583a4885f5ac48854f28 Mon Sep 17 00:00:00 2001
From: Tim van Dijen <tvdijen@gmail.com>
Date: Sat, 6 Jan 2018 23:39:03 +0100
Subject: [PATCH] PSR-2

---
 modules/saml/lib/IdP/SAML1.php     | 244 ++++++++++----------
 modules/saml/lib/IdP/SQLNameID.php | 343 +++++++++++++++--------------
 2 files changed, 295 insertions(+), 292 deletions(-)

diff --git a/modules/saml/lib/IdP/SAML1.php b/modules/saml/lib/IdP/SAML1.php
index cd8affad9..68fb13ed8 100644
--- a/modules/saml/lib/IdP/SAML1.php
+++ b/modules/saml/lib/IdP/SAML1.php
@@ -6,130 +6,130 @@ use SimpleSAML\Bindings\Shib13\HTTPPost;
  *
  * @package SimpleSAMLphp
  */
-class sspmod_saml_IdP_SAML1 {
-
-	/**
-	 * Send a response to the SP.
-	 *
-	 * @param array $state  The authentication state.
-	 */
-	public static function sendResponse(array $state) {
-		assert(isset($state['Attributes']));
-		assert(isset($state['SPMetadata']));
-		assert(isset($state['saml:shire']));
-		assert(array_key_exists('saml:target', $state)); // Can be NULL
-
-		$spMetadata = $state["SPMetadata"];
-		$spEntityId = $spMetadata['entityid'];
-		$spMetadata = SimpleSAML_Configuration::loadFromArray($spMetadata,
-			'$metadata[' . var_export($spEntityId, TRUE) . ']');
-
-		SimpleSAML\Logger::info('Sending SAML 1.1 Response to ' . var_export($spEntityId, TRUE));
-
-		$attributes = $state['Attributes'];
-		$shire = $state['saml:shire'];
-		$target = $state['saml:target'];
-
-		$idp = SimpleSAML_IdP::getByState($state);
-
-		$idpMetadata = $idp->getConfig();
-
-		$config = SimpleSAML_Configuration::getInstance();
-		$metadata = SimpleSAML_Metadata_MetaDataStorageHandler::getMetadataHandler();
-
-		$statsData = array(
-			'spEntityID' => $spEntityId,
-			'idpEntityID' => $idpMetadata->getString('entityid'),
-			'protocol' => 'saml1',
-		);
-		if (isset($state['saml:AuthnRequestReceivedAt'])) {
-			$statsData['logintime'] = microtime(TRUE) - $state['saml:AuthnRequestReceivedAt'];
-		}
-		SimpleSAML_Stats::log('saml:idp:Response', $statsData);
-
-		// Generate and send response.
-		$ar = new \SimpleSAML\XML\Shib13\AuthnResponse();
-		$authnResponseXML = $ar->generate($idpMetadata, $spMetadata, $shire, $attributes);
-
-		$httppost = new HTTPPost($config, $metadata);
-		$httppost->sendResponse($authnResponseXML, $idpMetadata, $spMetadata, $target, $shire);
+class sspmod_saml_IdP_SAML1
+{
+    /**
+     * Send a response to the SP.
+     *
+     * @param array $state  The authentication state.
+     */
+    public static function sendResponse(array $state)
+    {
+        assert(isset($state['Attributes']));
+        assert(isset($state['SPMetadata']));
+        assert(isset($state['saml:shire']));
+        assert(array_key_exists('saml:target', $state)); // Can be NULL
+
+        $spMetadata = $state["SPMetadata"];
+        $spEntityId = $spMetadata['entityid'];
+        $spMetadata = SimpleSAML_Configuration::loadFromArray($spMetadata,
+            '$metadata[' . var_export($spEntityId, true) . ']');
+
+        SimpleSAML\Logger::info('Sending SAML 1.1 Response to ' . var_export($spEntityId, true));
+
+        $attributes = $state['Attributes'];
+        $shire = $state['saml:shire'];
+        $target = $state['saml:target'];
+
+        $idp = SimpleSAML_IdP::getByState($state);
+
+        $idpMetadata = $idp->getConfig();
+
+        $config = SimpleSAML_Configuration::getInstance();
+        $metadata = SimpleSAML_Metadata_MetaDataStorageHandler::getMetadataHandler();
+
+        $statsData = array(
+            'spEntityID' => $spEntityId,
+            'idpEntityID' => $idpMetadata->getString('entityid'),
+            'protocol' => 'saml1',
+        );
+        if (isset($state['saml:AuthnRequestReceivedAt'])) {
+            $statsData['logintime'] = microtime(true) - $state['saml:AuthnRequestReceivedAt'];
+        }
+        SimpleSAML_Stats::log('saml:idp:Response', $statsData);
+
+        // Generate and send response.
+        $ar = new \SimpleSAML\XML\Shib13\AuthnResponse();
+        $authnResponseXML = $ar->generate($idpMetadata, $spMetadata, $shire, $attributes);
+
+        $httppost = new HTTPPost($config, $metadata);
+        $httppost->sendResponse($authnResponseXML, $idpMetadata, $spMetadata, $target, $shire);
+    }
+
+
+    /**
+     * Receive an authentication request.
+     *
+     * @param SimpleSAML_IdP $idp  The IdP we are receiving it for.
+     */
+    public static function receiveAuthnRequest(SimpleSAML_IdP $idp)
+    {
+        if (isset($_REQUEST['cookieTime'])) {
+            $cookieTime = (int)$_REQUEST['cookieTime'];
+            if ($cookieTime + 5 > time()) {
+                /*
+                 * Less than five seconds has passed since we were
+                 * here the last time. Cookies are probably disabled.
+                 */
+                \SimpleSAML\Utils\HTTP::checkSessionCookie(\SimpleSAML\Utils\HTTP::getSelfURL());
+            }
+        }
+
+        if (!isset($_REQUEST['providerId'])) {
+            throw new SimpleSAML_Error_BadRequest('Missing providerId parameter.');
+        }
+        $spEntityId = (string)$_REQUEST['providerId'];
+
+        if (!isset($_REQUEST['shire'])) {
+            throw new SimpleSAML_Error_BadRequest('Missing shire parameter.');
+        }
+        $shire = (string)$_REQUEST['shire'];
+
+        if (isset($_REQUEST['target'])) {
+            $target = $_REQUEST['target'];
+        } else {
+            $target = null;
+        }
+
+        SimpleSAML\Logger::info('Shib1.3 - IdP.SSOService: Got incoming Shib authnRequest from ' . var_export($spEntityId, true) . '.');
+
+        $metadata = SimpleSAML_Metadata_MetaDataStorageHandler::getMetadataHandler();
+        $spMetadata = $metadata->getMetaDataConfig($spEntityId, 'shib13-sp-remote');
+
+        $found = false;
+        foreach ($spMetadata->getEndpoints('AssertionConsumerService') as $ep) {
+            if ($ep['Binding'] !== 'urn:oasis:names:tc:SAML:1.0:profiles:browser-post') {
+                continue;
+            }
+            if ($ep['Location'] !== $shire) {
+                continue;
+            }
+            $found = true;
+            break;
+        }
+        if (!$found) {
+            throw new Exception('Invalid AssertionConsumerService for SP ' .
+                var_export($spEntityId, true) . ': ' . var_export($shire, true));
 	}
 
+        SimpleSAML_Stats::log('saml:idp:AuthnRequest', array(
+            'spEntityID' => $spEntityId,
+            'protocol' => 'saml1',
+        ));
 
-	/**
-	 * Receive an authentication request.
-	 *
-	 * @param SimpleSAML_IdP $idp  The IdP we are receiving it for.
-	 */
-	public static function receiveAuthnRequest(SimpleSAML_IdP $idp) {
-
-		if (isset($_REQUEST['cookieTime'])) {
-			$cookieTime = (int)$_REQUEST['cookieTime'];
-			if ($cookieTime + 5 > time()) {
-				/*
-				 * Less than five seconds has passed since we were
-				 * here the last time. Cookies are probably disabled.
-				 */
-				\SimpleSAML\Utils\HTTP::checkSessionCookie(\SimpleSAML\Utils\HTTP::getSelfURL());
-			}
-		}
-
-		if (!isset($_REQUEST['providerId'])) {
-			throw new SimpleSAML_Error_BadRequest('Missing providerId parameter.');
-		}
-		$spEntityId = (string)$_REQUEST['providerId'];
-
-		if (!isset($_REQUEST['shire'])) {
-			throw new SimpleSAML_Error_BadRequest('Missing shire parameter.');
-		}
-		$shire = (string)$_REQUEST['shire'];
-
-		if (isset($_REQUEST['target'])) {
-			$target = $_REQUEST['target'];
-		} else {
-			$target = NULL;
-		}
-
-		SimpleSAML\Logger::info('Shib1.3 - IdP.SSOService: Got incoming Shib authnRequest from ' . var_export($spEntityId, TRUE) . '.');
-
-		$metadata = SimpleSAML_Metadata_MetaDataStorageHandler::getMetadataHandler();
-		$spMetadata = $metadata->getMetaDataConfig($spEntityId, 'shib13-sp-remote');
-
-		$found = FALSE;
-		foreach ($spMetadata->getEndpoints('AssertionConsumerService') as $ep) {
-			if ($ep['Binding'] !== 'urn:oasis:names:tc:SAML:1.0:profiles:browser-post') {
-				continue;
-			}
-			if ($ep['Location'] !== $shire) {
-				continue;
-			}
-			$found = TRUE;
-			break;
-		}
-		if (!$found) {
-			throw new Exception('Invalid AssertionConsumerService for SP ' .
-				var_export($spEntityId, TRUE) . ': ' . var_export($shire, TRUE));
-		}
-
-		SimpleSAML_Stats::log('saml:idp:AuthnRequest', array(
-			'spEntityID' => $spEntityId,
-			'protocol' => 'saml1',
-		));
-
-		$sessionLostURL = \SimpleSAML\Utils\HTTP::addURLParameters(
+        $sessionLostURL = \SimpleSAML\Utils\HTTP::addURLParameters(
             \SimpleSAML\Utils\HTTP::getSelfURL(),
-			array('cookieTime' => time()));
-
-		$state = array(
-			'Responder' => array('sspmod_saml_IdP_SAML1', 'sendResponse'),
-			'SPMetadata' => $spMetadata->toArray(),
-			SimpleSAML_Auth_State::RESTART => $sessionLostURL,
-			'saml:shire' => $shire,
-			'saml:target' => $target,
-			'saml:AuthnRequestReceivedAt' => microtime(TRUE),
-		);
-
-		$idp->handleAuthenticationRequest($state);
-	}
-
+            array('cookieTime' => time()));
+
+        $state = array(
+            'Responder' => array('sspmod_saml_IdP_SAML1', 'sendResponse'),
+            'SPMetadata' => $spMetadata->toArray(),
+            SimpleSAML_Auth_State::RESTART => $sessionLostURL,
+            'saml:shire' => $shire,
+            'saml:target' => $target,
+            'saml:AuthnRequestReceivedAt' => microtime(true),
+        );
+
+        $idp->handleAuthenticationRequest($state);
+    }
 }
diff --git a/modules/saml/lib/IdP/SQLNameID.php b/modules/saml/lib/IdP/SQLNameID.php
index ce5145fd7..8111f5e23 100644
--- a/modules/saml/lib/IdP/SQLNameID.php
+++ b/modules/saml/lib/IdP/SQLNameID.php
@@ -5,174 +5,177 @@
  *
  * @package SimpleSAMLphp
  */
-class sspmod_saml_IdP_SQLNameID  {
-
-	/**
-	 * Create NameID table in SQL, if it is missing.
-	 *
-	 * @param \SimpleSAML\Store\SQL $store  The datastore.
-	 */
-	private static function createTable(\SimpleSAML\Store\SQL $store) {
-
-		if ($store->getTableVersion('saml_PersistentNameID') === 1) {
-			return;
-		}
-
-		$query = 'CREATE TABLE ' . $store->prefix . '_saml_PersistentNameID (
-			_idp VARCHAR(256) NOT NULL,
-			_sp VARCHAR(256) NOT NULL,
-			_user VARCHAR(256) NOT NULL,
-			_value VARCHAR(40) NOT NULL,
-			UNIQUE (_idp, _sp, _user)
-		)';
-		$store->pdo->exec($query);
-
-		$query = 'CREATE INDEX ' . $store->prefix . '_saml_PersistentNameID_idp_sp ON '  . $store->prefix . '_saml_PersistentNameID (_idp, _sp)';
-		$store->pdo->exec($query);
-
-		$store->setTableVersion('saml_PersistentNameID', 1);
-	}
-
-
-	/**
-	 * Retrieve the SQL datastore.
-	 *
-	 * Will also ensure that the NameID table is present.
-	 *
-	 * @return \SimpleSAML\Store\SQL  SQL datastore.
-	 */
-	private static function getStore() {
-
-		$store = \SimpleSAML\Store::getInstance();
-		if (!($store instanceof \SimpleSAML\Store\SQL)) {
-			throw new SimpleSAML_Error_Exception('SQL NameID store requires SimpleSAMLphp to be configured with a SQL datastore.');
-		}
-
-		self::createTable($store);
-
-		return $store;
-	}
-
-
-	/**
-	 * Add a NameID into the database.
-	 *
-	 * @param \SimpleSAML\Store\SQL $store  The data store.
-	 * @param string $idpEntityId  The IdP entityID.
-	 * @param string $spEntityId  The SP entityID.
-	 * @param string $user  The user's unique identificator (e.g. username).
-	 * @param string $value  The NameID value.
-	 */
-	public static function add($idpEntityId, $spEntityId, $user, $value) {
-		assert(is_string($idpEntityId));
-		assert(is_string($spEntityId));
-		assert(is_string($user));
-		assert(is_string($value));
-
-		$store = self::getStore();
-
-		$params = array(
-			'_idp' => $idpEntityId,
-			'_sp' => $spEntityId,
-			'_user' => $user,
-			'_value' => $value,
-		);
-
-		$query = 'INSERT INTO ' . $store->prefix . '_saml_PersistentNameID (_idp, _sp, _user, _value) VALUES(:_idp, :_sp, :_user, :_value)';
-		$query = $store->pdo->prepare($query);
-		$query->execute($params);
-	}
-
-
-	/**
-	 * Retrieve a NameID into from database.
-	 *
-	 * @param string $idpEntityId  The IdP entityID.
-	 * @param string $spEntityId  The SP entityID.
-	 * @param string $user  The user's unique identificator (e.g. username).
-	 * @return string|NULL $value  The NameID value, or NULL of no NameID value was found.
-	 */
-	public static function get($idpEntityId, $spEntityId, $user) {
-		assert(is_string($idpEntityId));
-		assert(is_string($spEntityId));
-		assert(is_string($user));
-
-		$store = self::getStore();
-
-		$params = array(
-			'_idp' => $idpEntityId,
-			'_sp' => $spEntityId,
-			'_user' => $user,
-		);
-
-		$query = 'SELECT _value FROM ' . $store->prefix . '_saml_PersistentNameID WHERE _idp = :_idp AND _sp = :_sp AND _user = :_user';
-		$query = $store->pdo->prepare($query);
-		$query->execute($params);
-
-		$row = $query->fetch(PDO::FETCH_ASSOC);
-		if ($row === FALSE) {
-			// No NameID found
-			return NULL;
-		}
-
-		return $row['_value'];
-	}
-
-
-	/**
-	 * Delete a NameID from the database.
-	 *
-	 * @param string $idpEntityId  The IdP entityID.
-	 * @param string $spEntityId  The SP entityID.
-	 * @param string $user  The user's unique identificator (e.g. username).
-	 */
-	public static function delete($idpEntityId, $spEntityId, $user) {
-		assert(is_string($idpEntityId));
-		assert(is_string($spEntityId));
-		assert(is_string($user));
-
-		$store = self::getStore();
-
-		$params = array(
-			'_idp' => $idpEntityId,
-			'_sp' => $spEntityId,
-			'_user' => $user,
-		);
-
-		$query = 'DELETE FROM ' . $store->prefix . '_saml_PersistentNameID WHERE _idp = :_idp AND _sp = :_sp AND _user = :_user';
-		$query = $store->pdo->prepare($query);
-		$query->execute($params);
-	}
-
-
-	/**
-	 * Retrieve all federated identities for an IdP-SP pair.
-	 *
-	 * @param string $idpEntityId  The IdP entityID.
-	 * @param string $spEntityId  The SP entityID.
-	 * @return array  Array of userid => NameID.
-	 */
-	public static function getIdentities($idpEntityId, $spEntityId) {
-		assert(is_string($idpEntityId));
-		assert(is_string($spEntityId));
-
-		$store = self::getStore();
-
-		$params = array(
-			'_idp' => $idpEntityId,
-			'_sp' => $spEntityId,
-		);
-
-		$query = 'SELECT _user, _value FROM ' . $store->prefix . '_saml_PersistentNameID WHERE _idp = :_idp AND _sp = :_sp';
-		$query = $store->pdo->prepare($query);
-		$query->execute($params);
-
-		$res = array();
-		while ( ($row = $query->fetch(PDO::FETCH_ASSOC)) !== FALSE) {
-			$res[$row['_user']] = $row['_value'];
-		}
-
-		return $res;
-	}
-
+class sspmod_saml_IdP_SQLNameID
+{
+    /**
+     * Create NameID table in SQL, if it is missing.
+     *
+     * @param \SimpleSAML\Store\SQL $store  The datastore.
+     */
+    private static function createTable(\SimpleSAML\Store\SQL $store)
+    {
+        if ($store->getTableVersion('saml_PersistentNameID') === 1) {
+            return;
+        }
+
+        $query = 'CREATE TABLE ' . $store->prefix . '_saml_PersistentNameID (
+            _idp VARCHAR(256) NOT NULL,
+            _sp VARCHAR(256) NOT NULL,
+            _user VARCHAR(256) NOT NULL,
+            _value VARCHAR(40) NOT NULL,
+            UNIQUE (_idp, _sp, _user)
+        )';
+        $store->pdo->exec($query);
+
+        $query = 'CREATE INDEX ' . $store->prefix . '_saml_PersistentNameID_idp_sp ON '  . $store->prefix . '_saml_PersistentNameID (_idp, _sp)';
+        $store->pdo->exec($query);
+
+        $store->setTableVersion('saml_PersistentNameID', 1);
+    }
+
+
+    /**
+     * Retrieve the SQL datastore.
+     *
+     * Will also ensure that the NameID table is present.
+     *
+     * @return \SimpleSAML\Store\SQL  SQL datastore.
+     */
+    private static function getStore()
+    {
+        $store = \SimpleSAML\Store::getInstance();
+        if (!($store instanceof \SimpleSAML\Store\SQL)) {
+            throw new SimpleSAML_Error_Exception('SQL NameID store requires SimpleSAMLphp to be configured with a SQL datastore.');
+        }
+
+        self::createTable($store);
+
+        return $store;
+    }
+
+
+    /**
+     * Add a NameID into the database.
+     *
+     * @param \SimpleSAML\Store\SQL $store  The data store.
+     * @param string $idpEntityId  The IdP entityID.
+     * @param string $spEntityId  The SP entityID.
+     * @param string $user  The user's unique identificator (e.g. username).
+     * @param string $value  The NameID value.
+     */
+    public static function add($idpEntityId, $spEntityId, $user, $value)
+    {
+        assert(is_string($idpEntityId));
+        assert(is_string($spEntityId));
+        assert(is_string($user));
+        assert(is_string($value));
+
+        $store = self::getStore();
+
+        $params = array(
+            '_idp' => $idpEntityId,
+            '_sp' => $spEntityId,
+            '_user' => $user,
+            '_value' => $value,
+        );
+
+        $query = 'INSERT INTO ' . $store->prefix . '_saml_PersistentNameID (_idp, _sp, _user, _value) VALUES(:_idp, :_sp, :_user, :_value)';
+        $query = $store->pdo->prepare($query);
+        $query->execute($params);
+    }
+
+
+    /**
+     * Retrieve a NameID into from database.
+     *
+     * @param string $idpEntityId  The IdP entityID.
+     * @param string $spEntityId  The SP entityID.
+     * @param string $user  The user's unique identificator (e.g. username).
+     * @return string|NULL $value  The NameID value, or NULL of no NameID value was found.
+     */
+    public static function get($idpEntityId, $spEntityId, $user)
+    {
+        assert(is_string($idpEntityId));
+        assert(is_string($spEntityId));
+        assert(is_string($user));
+
+        $store = self::getStore();
+
+        $params = array(
+            '_idp' => $idpEntityId,
+            '_sp' => $spEntityId,
+            '_user' => $user,
+        );
+
+        $query = 'SELECT _value FROM ' . $store->prefix . '_saml_PersistentNameID WHERE _idp = :_idp AND _sp = :_sp AND _user = :_user';
+        $query = $store->pdo->prepare($query);
+        $query->execute($params);
+
+        $row = $query->fetch(PDO::FETCH_ASSOC);
+        if ($row === false) {
+            // No NameID found
+            return null;
+        }
+
+        return $row['_value'];
+    }
+
+
+    /**
+     * Delete a NameID from the database.
+     *
+     * @param string $idpEntityId  The IdP entityID.
+     * @param string $spEntityId  The SP entityID.
+     * @param string $user  The user's unique identificator (e.g. username).
+     */
+    public static function delete($idpEntityId, $spEntityId, $user)
+    {
+        assert(is_string($idpEntityId));
+        assert(is_string($spEntityId));
+        assert(is_string($user));
+
+        $store = self::getStore();
+
+        $params = array(
+            '_idp' => $idpEntityId,
+            '_sp' => $spEntityId,
+            '_user' => $user,
+        );
+
+        $query = 'DELETE FROM ' . $store->prefix . '_saml_PersistentNameID WHERE _idp = :_idp AND _sp = :_sp AND _user = :_user';
+        $query = $store->pdo->prepare($query);
+        $query->execute($params);
+    }
+
+
+    /**
+     * Retrieve all federated identities for an IdP-SP pair.
+     *
+     * @param string $idpEntityId  The IdP entityID.
+     * @param string $spEntityId  The SP entityID.
+     * @return array  Array of userid => NameID.
+     */
+    public static function getIdentities($idpEntityId, $spEntityId)
+    {
+        assert(is_string($idpEntityId));
+        assert(is_string($spEntityId));
+
+        $store = self::getStore();
+
+        $params = array(
+            '_idp' => $idpEntityId,
+            '_sp' => $spEntityId,
+        );
+
+        $query = 'SELECT _user, _value FROM ' . $store->prefix . '_saml_PersistentNameID WHERE _idp = :_idp AND _sp = :_sp';
+        $query = $store->pdo->prepare($query);
+        $query->execute($params);
+
+        $res = array();
+        while (($row = $query->fetch(PDO::FETCH_ASSOC)) !== false) {
+            $res[$row['_user']] = $row['_value'];
+        }
+
+        return $res;
+    }
 }
-- 
GitLab