generateRandomBytes() public static method

Deprecation: This method will be removed in SSP 2.0. Please use openssl_random_pseudo_bytes() instead.
public static generateRandomBytes ( $length )
 /**
  * Construct
  *
  * @param array $authSourceconfig Configuration array for the selected authsource
  * @param array $writeConfig Configuration array for the selected catalogue backend
  * @param array $attributes The user attributes to be saved
  */
 public function __construct($authSourceConfig, $writeConfig, $attributes, $hashAlgo)
 {
     $asc = SimpleSAML_Configuration::loadFromArray($authSourceConfig);
     try {
         $this->dbh = new PDO($asc->getString('dsn'), $asc->getString('username'), $asc->getString('password'));
     } catch (PDOException $e) {
         throw new Exception($e->getMessage());
     }
     $driver = explode(':', $asc->getString('dsn'), 2);
     $driver = strtolower($driver[0]);
     /* Driver specific initialization. */
     switch ($driver) {
         case 'mysql':
             /* Use UTF-8. */
             $this->dbh->exec("SET NAMES utf8");
             $this->dbh->exec("SET CHARACTER SET utf8;");
             break;
         case 'pgsql':
             /* Use UTF-8. */
             $this->dbh->exec("SET NAMES 'UTF8'");
             break;
     }
     $this->dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
     $this->attributes = $attributes;
     $this->hashAlgo = $hashAlgo;
     $this->salt = bin2hex(SimpleSAML_Utilities::generateRandomBytes(64, FALSE));
     $wc = SimpleSAML_Configuration::loadFromArray($writeConfig);
     $this->userIdAttr = $wc->getString('user.id.param');
 }
Beispiel #2
0
 protected function __construct()
 {
     /* Call the parent constructor in case it should become
      * necessary in the future.
      */
     parent::__construct();
     /* Initialize the php session handling.
      *
      * If session_id() returns a blank string, then we need
      * to call session start. Otherwise the session is already
      * started, and we should avoid calling session_start().
      */
     if (session_id() === '') {
         $config = SimpleSAML_Configuration::getInstance();
         $cookiepath = $config->getBoolean('session.phpsession.limitedpath', FALSE) ? '/' . $config->getBaseURL() : '/';
         session_set_cookie_params(0, $cookiepath, NULL, SimpleSAML_Utilities::isHTTPS());
         $cookiename = $config->getString('session.phpsession.cookiename', NULL);
         if (!empty($cookiename)) {
             session_name($cookiename);
         }
         $savepath = $config->getString('session.phpsession.savepath', NULL);
         if (!empty($savepath)) {
             session_save_path($savepath);
         }
         if (!array_key_exists(session_name(), $_COOKIE)) {
             /* Session cookie unset - session id not set. Generate new (secure) session id. */
             session_id(SimpleSAML_Utilities::stringToHex(SimpleSAML_Utilities::generateRandomBytes(16)));
         }
         session_start();
     }
 }
Beispiel #3
0
 /**
  * Create the redirect URL for a message.
  *
  * @param  SAML2_Message $message The message.
  * @return string        The URL the user should be redirected to in order to send a message.
  * @throws Exception
  */
 public function getRedirectURL(SAML2_Message $message)
 {
     $store = SimpleSAML_Store::getInstance();
     if ($store === FALSE) {
         throw new Exception('Unable to send artifact without a datastore configured.');
     }
     $generatedId = pack('H*', (string) SimpleSAML_Utilities::stringToHex(SimpleSAML_Utilities::generateRandomBytes(20)));
     $artifact = base64_encode("" . sha1($message->getIssuer(), TRUE) . $generatedId);
     $artifactData = $message->toUnsignedXML();
     $artifactDataString = $artifactData->ownerDocument->saveXML($artifactData);
     $store->set('artifact', $artifact, $artifactDataString, time() + 15 * 60);
     $params = array('SAMLart' => $artifact);
     $relayState = $message->getRelayState();
     if ($relayState !== NULL) {
         $params['RelayState'] = $relayState;
     }
     return SimpleSAML_Utilities::addURLparameter($message->getDestination(), $params);
 }
 /**
  * Create and set new session id.
  *
  * @return string  The new session id.
  */
 public function newSessionId()
 {
     $session_cookie_params = session_get_cookie_params();
     if ($session_cookie_params['secure'] && !SimpleSAML_Utilities::isHTTPS()) {
         throw new SimpleSAML_Error_Exception('Session start with secure cookie not allowed on http.');
     }
     if (headers_sent()) {
         throw new SimpleSAML_Error_Exception('Cannot create new session - headers already sent.');
     }
     /* Generate new (secure) session id. */
     $sessionId = SimpleSAML_Utilities::stringToHex(SimpleSAML_Utilities::generateRandomBytes(16));
     SimpleSAML_Session::createSession($sessionId);
     if (session_id() !== '') {
         /* Session already started, close it. */
         session_write_close();
     }
     session_id($sessionId);
     session_start();
     return session_id();
 }
 /**
  * Retrieve the session id of saved in the session cookie.
  *
  * @return string  The session id saved in the cookie.
  */
 public function getCookieSessionId()
 {
     if (session_id() === '') {
         $session_cookie_params = session_get_cookie_params();
         if ($session_cookie_params['secure'] && !SimpleSAML_Utilities::isHTTPS()) {
             throw new SimpleSAML_Error_Exception('Session start with secure cookie not allowed on http.');
         }
         if (!self::hasSessionCookie()) {
             if (headers_sent()) {
                 throw new SimpleSAML_Error_Exception('Cannot create new session - headers already sent.');
             }
             /* Session cookie unset - session id not set. Generate new (secure) session id. */
             $sessionId = SimpleSAML_Utilities::stringToHex(SimpleSAML_Utilities::generateRandomBytes(16));
             SimpleSAML_Session::createSession($sessionId);
             session_id($sessionId);
         }
         session_start();
     }
     return session_id();
 }
Beispiel #6
0
    function send()
    {
        if ($this->to == NULL) {
            throw new Exception('EMail field [to] is required and not set.');
        }
        if ($this->subject == NULL) {
            throw new Exception('EMail field [subject] is required and not set.');
        }
        if ($this->body == NULL) {
            throw new Exception('EMail field [body] is required and not set.');
        }
        $random_hash = SimpleSAML_Utilities::stringToHex(SimpleSAML_Utilities::generateRandomBytes(16));
        if (isset($this->from)) {
            $this->headers[] = 'From: ' . $this->from;
        }
        if (isset($this->replyto)) {
            $this->headers[] = 'Reply-To: ' . $this->replyto;
        }
        $this->headers[] = 'Content-Type: multipart/alternative; boundary="simplesamlphp-' . $random_hash . '"';
        $message = '
--simplesamlphp-' . $random_hash . '
Content-Type: text/plain; charset="utf-8" 
Content-Transfer-Encoding: 8bit

' . strip_tags(html_entity_decode($this->body)) . '

--simplesamlphp-' . $random_hash . '
Content-Type: text/html; charset="utf-8" 
Content-Transfer-Encoding: 8bit

' . $this->getHTML($this->body) . '

--simplesamlphp-' . $random_hash . '--
';
        $headers = implode("\n", $this->headers);
        $mail_sent = @mail($this->to, $this->subject, $message, $headers);
        SimpleSAML_Logger::debug('Email: Sending e-mail to [' . $this->to . '] : ' . ($mail_sent ? 'OK' : 'Failed'));
        if (!$mail_sent) {
            throw new Exception('Error when sending e-mail');
        }
    }
 /**
  * Get the NameID value.
  *
  * @return string|NULL  The NameID value.
  */
 protected function getValue(array &$state)
 {
     if (!isset($state['saml:NameIDFormat']) || $state['saml:NameIDFormat'] !== $this->format) {
         SimpleSAML_Logger::debug('SQLPersistentNameID: Request did not specify persistent NameID format -  not generating persistent NameID.');
         return NULL;
     }
     if (!isset($state['Destination']['entityid'])) {
         SimpleSAML_Logger::warning('SQLPersistentNameID: No SP entity ID - not generating persistent NameID.');
         return NULL;
     }
     $spEntityId = $state['Destination']['entityid'];
     if (!isset($state['Source']['entityid'])) {
         SimpleSAML_Logger::warning('SQLPersistentNameID: No IdP entity ID - not generating persistent NameID.');
         return NULL;
     }
     $idpEntityId = $state['Source']['entityid'];
     if (!isset($state['Attributes'][$this->attribute]) || count($state['Attributes'][$this->attribute]) === 0) {
         SimpleSAML_Logger::warning('SQLPersistentNameID: Missing attribute ' . var_export($this->attribute, TRUE) . ' on user - not generating persistent NameID.');
         return NULL;
     }
     if (count($state['Attributes'][$this->attribute]) > 1) {
         SimpleSAML_Logger::warning('SQLPersistentNameID: More than one value in attribute ' . var_export($this->attribute, TRUE) . ' on user - not generating persistent NameID.');
         return NULL;
     }
     $uid = array_values($state['Attributes'][$this->attribute]);
     /* Just in case the first index is no longer 0. */
     $uid = $uid[0];
     $value = sspmod_saml_IdP_SQLNameID::get($idpEntityId, $spEntityId, $uid);
     if ($value !== NULL) {
         SimpleSAML_Logger::debug('SQLPersistentNameID: Found persistent NameID ' . var_export($value, TRUE) . ' for user ' . var_export($uid, TRUE) . '.');
         return $value;
     }
     if (!isset($state['saml:AllowCreate']) || !$state['saml:AllowCreate']) {
         SimpleSAML_Logger::warning('SQLPersistentNameID: Did not find persistent NameID for user, and not allowed to create new NameID.');
         throw new sspmod_saml_Error(SAML2_Const::STATUS_RESPONDER, 'urn:oasis:names:tc:SAML:2.0:status:InvalidNameIDPolicy');
     }
     $value = SimpleSAML_Utilities::stringToHex(SimpleSAML_Utilities::generateRandomBytes(20));
     SimpleSAML_Logger::debug('SQLPersistentNameID: Created persistent NameID ' . var_export($value, TRUE) . ' for user ' . var_export($uid, TRUE) . '.');
     sspmod_saml_IdP_SQLNameID::add($idpEntityId, $spEntityId, $uid, $value);
     return $value;
 }
Beispiel #8
0
 protected function __construct()
 {
     /* Call the parent constructor in case it should become
      * necessary in the future.
      */
     parent::__construct();
     /* Initialize the php session handling.
      *
      * If session_id() returns a blank string, then we need
      * to call session start. Otherwise the session is already
      * started, and we should avoid calling session_start().
      */
     if (session_id() === '') {
         $config = SimpleSAML_Configuration::getInstance();
         $params = $this->getCookieParams();
         $version = explode('.', PHP_VERSION);
         if ((int) $version[0] === 5 && (int) $version[1] < 2) {
             session_set_cookie_params($params['lifetime'], $params['path'], $params['domain'], $params['secure']);
         } else {
             session_set_cookie_params($params['lifetime'], $params['path'], $params['domain'], $params['secure'], $params['httponly']);
         }
         $cookiename = $config->getString('session.phpsession.cookiename', NULL);
         if (!empty($cookiename)) {
             session_name($cookiename);
         }
         $savepath = $config->getString('session.phpsession.savepath', NULL);
         if (!empty($savepath)) {
             session_save_path($savepath);
         }
         if (!array_key_exists(session_name(), $_COOKIE)) {
             if (headers_sent()) {
                 throw new SimpleSAML_Error_Exception('Cannot create new session - headers already sent.');
             }
             /* Session cookie unset - session id not set. Generate new (secure) session id. */
             session_id(SimpleSAML_Utilities::stringToHex(SimpleSAML_Utilities::generateRandomBytes(16)));
         }
         session_start();
     }
 }
Beispiel #9
0
 /**
  * This function generates a password hash
  * @param $password  The unencrypted password
  * @param $algo      The hashing algorithm, capitals, optionally prepended with 'S' (salted)
  * @param $salt      Optional salt
  */
 public static function pwHash($password, $algo, $salt = NULL)
 {
     assert('is_string($algo)');
     assert('is_string($password)');
     if (in_array(strtolower($algo), hash_algos())) {
         $php_algo = strtolower($algo);
         // 'sha256' etc
         // LDAP compatibility
         return '{' . preg_replace('/^SHA1$/', 'SHA', $algo) . '}' . base64_encode(hash($php_algo, $password, TRUE));
     }
     // Salt
     if (!$salt) {
         // Default 8 byte salt, but 4 byte for LDAP SHA1 hashes
         $bytes = $algo == 'SSHA1' ? 4 : 8;
         $salt = SimpleSAML_Utilities::generateRandomBytes($bytes);
     }
     if ($algo[0] == 'S' && in_array(substr(strtolower($algo), 1), hash_algos())) {
         $php_algo = substr(strtolower($algo), 1);
         // 'sha256' etc
         // Salted hash, with LDAP compatibility
         return '{' . preg_replace('/^SSHA1$/', 'SSHA', $algo) . '}' . base64_encode(hash($php_algo, $password . $salt, TRUE) . $salt);
     }
     throw new Exception('Hashing algoritm \'' . strtolower($algo) . '\' not supported');
 }
Beispiel #10
0
 /**
  * Notify about an event.
  *
  * @param string $event  The event.
  * @param array $data  Event data. Optional.
  */
 public static function log($event, array $data = array())
 {
     assert('is_string($event)');
     assert('!isset($data["op"])');
     assert('!isset($data["time"])');
     assert('!isset($data["_id"])');
     if (!self::$initialized) {
         self::initOutputs();
         self::$initialized = TRUE;
     }
     if (empty(self::$outputs)) {
         /* Not enabled. */
         return;
     }
     $data['op'] = $event;
     $data['time'] = microtime(TRUE);
     /* The ID generation is designed to cluster IDs related in time close together. */
     $int_t = (int) $data['time'];
     $hd = SimpleSAML_Utilities::generateRandomBytes(16);
     $data['_id'] = sprintf('%016x%s', $int_t, bin2hex($hd));
     foreach (self::$outputs as $out) {
         $out->emit($data);
     }
 }
 private static function createSessionID()
 {
     return SimpleSAML_Utilities::stringToHex(SimpleSAML_Utilities::generateRandomBytes(16));
 }
Beispiel #12
0
 /**
  * Save an error report.
  *
  * @return array  The array with the error report data.
  */
 protected function saveError()
 {
     $data = $this->format();
     $emsg = array_shift($data);
     $etrace = implode("\n", $data);
     $reportId = SimpleSAML_Utilities::stringToHex(SimpleSAML_Utilities::generateRandomBytes(4));
     SimpleSAML_Logger::error('Error report with id ' . $reportId . ' generated.');
     $config = SimpleSAML_Configuration::getInstance();
     $session = SimpleSAML_Session::getInstance();
     if (isset($_SERVER['HTTP_REFERER'])) {
         $referer = $_SERVER['HTTP_REFERER'];
         /*
          * Remove anything after the first '?' or ';', just
          * in case it contains any sensitive data.
          */
         $referer = explode('?', $referer, 2);
         $referer = $referer[0];
         $referer = explode(';', $referer, 2);
         $referer = $referer[0];
     } else {
         $referer = 'unknown';
     }
     $errorData = array('exceptionMsg' => $emsg, 'exceptionTrace' => $etrace, 'reportId' => $reportId, 'trackId' => $session->getTrackID(), 'url' => SimpleSAML_Utilities::selfURLNoQuery(), 'version' => $config->getVersion(), 'referer' => $referer);
     $session->setData('core:errorreport', $reportId, $errorData);
     return $errorData;
 }
 /**
  * Creates boundary string
  *
  * @return void
  */
 protected function _createBoundary()
 {
     $random_hash = SimpleSAML_Utilities::stringToHex(SimpleSAML_Utilities::generateRandomBytes(16));
     $this->_altBoundary = 'alt-' . $random_hash;
     $this->_mixedBoundary = 'mixed-' . $random_hash;
 }
 function send()
 {
     if ($this->to == NULL) {
         throw new Exception('EMail field [to] is required and not set.');
     }
     if ($this->subject == NULL) {
         throw new Exception('EMail field [subject] is required and not set.');
     }
     // if ($this->body == NULL) throw new Exception('EMail field [body] is required and not set.');
     $random_hash = SimpleSAML_Utilities::stringToHex(SimpleSAML_Utilities::generateRandomBytes(16));
     $message = $this->buildMessage($random_hash);
     if (isset($this->from)) {
         $this->headers[] = 'From: ' . $this->from;
     }
     if (isset($this->replyto)) {
         $this->headers[] = 'Reply-To: ' . $this->replyto;
     }
     $this->headers[] = 'Content-Type: multipart/alternative; boundary="simplesamlphp-' . $random_hash . '"';
     $headers = join("\r\n", $this->headers);
     $mail_sent = @mail($this->to, $this->subject, $message, $headers);
     SimpleSAML_Logger::debug('Email: Sending e-mail to [' . $this->to . '] : ' . ($mail_sent ? 'OK' : 'Failed'));
     if (!$mail_sent) {
         throw new Exception('Error when sending e-mail');
     }
 }
Beispiel #15
0
 /**
  * Private constructor that restricts instantiation to getInstance().
  *
  * @param boolean $transient Whether to create a transient session or not.
  */
 private function __construct($transient = FALSE)
 {
     $this->authData = array();
     if ($transient) {
         $this->trackid = 'XXXXXXXXXX';
         $this->transient = TRUE;
         return;
     }
     $sh = SimpleSAML_SessionHandler::getSessionHandler();
     $this->sessionId = $sh->newSessionId();
     $this->trackid = SimpleSAML_Utilities::stringToHex(SimpleSAML_Utilities::generateRandomBytes(5));
     $this->dirty = TRUE;
     /* Initialize data for session check function if defined */
     $globalConfig = SimpleSAML_Configuration::getInstance();
     $checkFunction = $globalConfig->getArray('session.check_function', NULL);
     if (isset($checkFunction)) {
         assert('is_callable($checkFunction)');
         call_user_func($checkFunction, $this, TRUE);
     }
 }
Beispiel #16
0
    $t->show();
    exit;
}
/* Format of the email.
 * POST fields will be added to the email in the order they appear here, and with the description
 * from the value in the array.
 *
 * DEPRECATED. Included as reference of incoming parameters.
 */
$mailFormat = array('email' => 'Email address of submitter', 'url' => 'URL of page where the error occured', 'errorcode' => 'Error code', 'parameters' => 'Parameters for the error', 'text' => 'Message from user', 'trackid' => 'Track id for the user\' session', 'exceptionmsg' => 'Exception message', 'exceptiontrace' => 'Exception backtrace', 'version' => 'simpleSAMLphp version');
/* POST fields we can safely ignore. */
$ignoredFields = array('send');
/* Generate a error ID, and add it to both the log and the error message. This should make it
 * simple to find the error in the logs.
 */
$reportId = SimpleSAML_Utilities::stringToHex(SimpleSAML_Utilities::generateRandomBytes(4));
SimpleSAML_Logger::error('Error report with  id ' . $reportId . ' generated.');
function getPValue($key)
{
    if (array_key_exists($key, $_POST)) {
        return strip_tags($_POST[$key]);
    }
    return 'not set';
}
/* Build the email message. */
$message = '<h1>SimpleSAMLphp Error Report</h1>

<p>Message from user:</p>
<div class="box" style="background: yellow; color: #888; border: 1px solid #999900; padding: .4em; margin: .5em">' . getPValue('text') . '</div>

<p>Exception: <strong>' . getPValue('exceptionmsg') . '</strong></p>