Attach client session to broker session in SSO server.

@return void
513730
public function attach()
    {
        $parameters = [
            'return_url' => $this->getCurrentUrl(),
            'broker' => $this->brokerName,
            'token' => $this->token,
            'checksum' => hash('sha256', 'attach' . $this->token . $this->brokerSecret)
        ];

        $attachUrl = $this->generateCommandUrl('attach', $parameters);

        $this->redirect($attachUrl);
    }
771738
private function sessionStart()
    {
        if (session_status() !== PHP_SESSION_ACTIVE) {
            $request = new Request;
            session_set_cookie_params(
                0,
                $request->getBasePath(),
                null,
                $request->getUri()->getScheme() === 'https',
                true
            );
            session_start();
        }
    }
127376
public function attach()
    {
        $this->detectReturnType();

        if (empty($_REQUEST['broker'])) {
            return $this->fail("No broker specified", 400);
        }

        if (empty($_REQUEST['token'])) {
            return $this->fail("No token specified", 400);
        }

        if (!$this->returnType) {
            return $this->fail("No return url specified", 400);
        }

        $checksum = $this->generateAttachChecksum($_REQUEST['broker'], $_REQUEST['token']);

        if (empty($_REQUEST['checksum']) || $checksum != $_REQUEST['checksum']) {
            return $this->fail("Invalid checksum", 400);
        }

        $this->startUserSession();
        $sid = $this->generateSessionId($_REQUEST['broker'], $_REQUEST['token']);

        $this->cache->set($sid, $this->getSessionData('id'));
        $this->outputAttachSuccess();
    }
1088586
private function initSessionConfig():void
    {
        if (!defined("IUMIO_ENV")) {
            throw new Server500(new \ArrayObject(array("explain" => "Framework Environment is not defined",
                "solution" => "Please initialize the framework environment")));
        }
        if (false === Server::exist(IUMIO_ROOT."/elements/cache/".strtolower(IUMIO_ENV)."/sessions")) {
            Server::create(IUMIO_ROOT."/elements/cache/".
                strtolower(IUMIO_ENV)."/sessions", "directory");
        }

        $this->id = session_id();
        $this->name = session_name();
        if (!$this->isStarted()) {
            session_save_path(IUMIO_ROOT . '/elements/cache/' . strtolower(IUMIO_ENV) . '/sessions');
            ini_set('session.gc_probability', 1);
        }
    }
1062992
private function initializeSessionContext()
    {
        $sessionServer = SessionServer::create($this)->getValue();
        $this->sessionContext = SessionContext::create($sessionServer);
    }
590013
public function startBrokerSession()
    {
        if (isset($this->brokerId)) {
            return;
        }

        $sid = $this->getBrokerSessionID();

        if ($sid === false) {
            return $this->fail("Broker didn't send a session key", 400);
        }

        $linkedId = $this->cache->get($sid);

        if (!$linkedId) {
            return $this->fail("The broker session id isn't attached to a user session", 403);
        }

        if (session_status() === PHP_SESSION_ACTIVE) {
            if ($linkedId !== session_id()) {
                throw new \Exception("Session has already started", 400);
            }
            return;
        }

        session_id($linkedId);
        session_start();

        $this->brokerId = $this->validateBrokerSessionId($sid);
    }
1023417
protected function setOptions()
    {
        $this->ssoServerUrl = null;
        $this->brokerName = null;
        $this->brokerSecret = null;

        if (!$this->ssoServerUrl || !$this->brokerName || !$this->brokerSecret) {
            throw new Exception('Missing configuration values.');
        }
    }
398562
protected function setup()
    {
        // Check if a valid access token exists.
        if (!$this->accessToken || $this->accessToken->expired()) {
            // Refresh is successful unless explicitly set to false.
            $refreshSuccess = true;

            // Check if a valid refresh token exists.
            if ($this->refreshToken && $this->refreshToken->getToken()) {
                // Attempt to use the refresh token.
                try {
                    $this->refresh();
                } catch (RequestException $e) {
                    // Check if the exception is due to an HTTP 403.
                    if ($e->getCode() == 403) {
                        $response = $e->getResponse();
                        $json = json_decode($response->getBody());
                        $body = $json->{'nl.divide.iq'};

                        // Check if the error is indeed a "TokenExpired" error,
                        // as expected.
                        if ($body->answer == 'TokenExpired') {
                            // Token is expired; refreshing unsuccessful.
                            $refreshSuccess = false;
                        } else {
                            // Unexpected error. Pass it up the stack. This
                            // might be a "TokenEmpty" error, but that would
                            // still be unexpected, because the token value was
                            // checked beforehand.
                            throw $e;
                        }
                    } else {
                        // Unexpected error. Pass it up the stack.
                        throw $e;
                    }
                }
            } else {
                // There is no refresh token to use; refreshing unsuccessful.
                $refreshSuccess = false;
            }

            // If refreshing failed, login from scratch and then authenticate.
            if (!$refreshSuccess) {
                $this->login()->authenticate();
            }
        }

        // Request the settings if needed.
        if (!$this->settings) {
            $response = $this->client->get('settings', [
                'headers' => ['Authentication' => $this->accessToken->getToken()],
            ]);

            $json = json_decode($response->getBody());
            $body = $json->{'nl.divide.iq'};
            $services = [];
            foreach ($body->services as $service) {
                $services[] = $service->code;
            }

            // Create new settings object.
            $this->settings = new Settings($services, $body->settings_updated);
        }
    }
1345133
private function updateClientAccessToken()
    {
        $user = $this->securityContext->getToken()->getUser();
        $this->client->updateAccessToken($user->getAccessToken());
    }
1306503
public static function updateSession($client_id, array $session)
    {
        if (Context::$client_id === $client_id) {
            $_SESSION = $session + (array)$_SESSION;
            Context::$old_session = $_SESSION;
        }
        return self::sendCmdAndMessageToClient($client_id, GatewayProtocol::CMD_UPDATE_SESSION, '', Context::sessionEncode($session));
    }
1258357
def setup_session(endpoint_context, areq, uid, client_id='', acr='', salt='salt',
                  authn_event=None):
    
    if authn_event is None and acr:
        authn_event = AuthnEvent(uid=uid, salt=salt, authn_info=acr,
                                 authn_time=time.time())

    if not client_id:
        client_id = areq['client_id']

    sid = endpoint_context.sdb.create_authz_session(authn_event, areq,
                                                    client_id=client_id,
                                                    uid=uid)
    endpoint_context.sdb.do_sub(sid, uid, '')
    return sid
1301941
private function registerObserver()
    {
        if ($this->observer) {
            return;
        }

        $this->observer = new \chilimatic\lib\session\observer\Session($this);
        $this->engine->attach($this->observer);
    }
1220885
public function initSession()
    {
        if (php_sapi_name() != 'cli') {
        
            if (!isset($_COOKIE['ccms'])) {
                $this->_uid = md5($_SERVER['REMOTE_ADDR'].$_SERVER['HTTP_USER_AGENT'].rand());
            } else {
                $a = explode('.', $_COOKIE['ccms']);
                $this->_uid = $a[0];
                $this->_last_visit = $a[1];
            }
            setcookie('ccms',$this->_uid.'.'.time(),time()+REMEMBER_ME_SECONDS,'/');
            
        }
        
        \Zend_Session::setSaveHandler(new SessionSaveHandler());
                             
        $this->_session = new \Zend_Session_Namespace(SESSION_NAMESPACE);
        
        if (isset($this->_session->locale) && $this->_session->locale) {
            $this->_locale->setLocale($this->_session->locale);
        }
    }
921175
public function login()
	{
		// extra lines for passing curl options to other routines, like ambrasubs payment processor
		// we are using the super global $_SESSION to pass data in $_SESSION[$var]
		if (isset($this->options['usesessvar'])) {
			$var = 'curl_options';
			if(!array_key_exists($var, $_SESSION)) $_SESSION[$var] = '';
			$_SESSION[$var] = $this->options;
			$GLOBALS[$var] = &$_SESSION[$var];
		}
		// end extra lines
		$overridearr = array();

		// find out if we have a SSL enabled website
		if (strpos($this->options['post_url'], 'https://') === false) {
			$ssl_string = 'http://';
		} else {
			$ssl_string = 'https://';
		}

		// check if curl extension is loaded
		if (!isset($this->options['post_url']) || !isset($this->options['formid'])) {
			$this->status['error'][] = static::_('CURL_FATAL');
		} else {
			if (!extension_loaded('curl')) {
				$this->status['error'][] = static::_('CURL_NOTINSTALLED');
			} else {
				$this->status['debug'][] = static::_('CURL_POST_URL_1') . ' ' . $this->options['post_url'];
				$remotedata = $this->ReadPage(true);
				if (empty($this->status['error'])) {
					$this->status['debug'][] = static::_('CURL_PHASE_1');
					$this->setCookies($this->options['cookiedomain'], $this->options['cookiepath'], $this->options['expires'], $this->options['secure'], $this->options['httponly']);
					//find out if we have the form with the name/id specified
					$parser = new HtmlFormParser($remotedata);
					$result = $parser->parseForms();
					$frmcount = count($result);
					$myfrm = -1;
					$i = 0;
                    // HJW changed 12 january 2013 to accommodate from identifiers changing every
                    // new access to the page containing the form. Like logonform123 , loginform a2s
                    // etc.

                    do {
                        if (isset($result[$i]['form_data']['name'])) {
                            if (strpos(strtolower($result[$i]['form_data']['name']),strtolower($this->options['formid'] )) !== false){
                                $myfrm = $i;
                                break;
                            }
                        }
                        if (isset($result[$i]['form_data']['id'])) {
                            if (strpos(strtolower($result[$i]['form_data']['id']),strtolower($this->options['formid'] )) !== false){
                                $myfrm = $i;
                                break;
                            }
                        }
	                    /** HJW 14-7-2014
	                      * we really should use the action field if there is no name field and no id field,
	                      * otherwise we may trigger a false match too easily
	                      * (eg match login with www.mydomain.com/login/index.php)
	                     */
                        if (isset($result[$i]['form_data']['action']) && !isset($result[$i]['form_data']['id']) && !isset($result[$i]['form_data']['name'])) {
                            if (strpos(strtolower(htmlspecialchars_decode($result[$i]['form_data']['action'])),strtolower($this->options['formid'] )) !== false){
                                $myfrm = $i;
                                break;
                            }
                        }
                        $i +=1;
                    } while ($i<$frmcount);

					if ($myfrm == -1) {
						$helpthem = '';
						if ($frmcount >0) {
							$i = 0;
							$helpthem = 'I found';
							do {
								if (isset($result[$i]['form_data']['id'])) {
									$helpthem = $helpthem . ' -- Name=' . $result[$i]['form_data']['name'] . ' &ID=' . $result[$i]['form_data']['id'];
								}
								$i +=1;
							} while ($i<$frmcount);
						}
						$this->status['debug'][] = static::_('CURL_NO_LOGINFORM') . ' ' . $helpthem;
					} else {
						$this->status['debug'][] = static::_('CURL_VALID_FORM');


						// by now we have the specified  login/logout form, lets get the data needed to login/logout
						// we went to all this trouble to get to the hidden input entries.
						// The stuff is there to enhance security and is, yes, hidden
						$form_action = htmlspecialchars_decode($result[$myfrm]['form_data']['action']);
						$elements_keys = array_keys($result[$myfrm]['form_elements']);
						$elements_values = array_values($result[$myfrm]['form_elements']);
						$elements_count  = count($result[$myfrm]['form_elements']);

						// override keys/values from hidden inputs
						// the $override is an array of keys/values that override existing keys/values

						if (empty($this->options['logout'])) {

							if ($this->options['override']) {
								$lines = explode(',', $this->options['override']);
								foreach ($lines as $line) {
									$cinfo = explode('=', $line);
									$overridearr[$cinfo[0]]['value'] = $cinfo[1];
									$overridearr[$cinfo[0]]['type'] = 'hidden';
								}
								$newhidden = array_merge($result[$myfrm]['form_elements'], $overridearr);
								$elements_keys = array_keys($newhidden);
								$elements_values = array_values($newhidden);
								$elements_count  = count($newhidden);
							}
						}
						// now construct the action parameter

						// we have 4 possible options:
						// case 0 Form action is without http.. and relpath = 0 , special case
						// case 1 Form action is without http.. and relpath = 1 , just construct the action
						// case 2 form_action is a full url, eg http..... and relpath = 0 This is easy, we do nothing at all
						// case 3 form_action is a full url, eg http..... and relpath = 1 special case

						$rel = (int)($this->options['relpath']);
						//      if (substr($form_action, 0, strlen($ssl_string))== $ssl_string) $hashttp = 2; else $hashttp = 0;
						if (substr($form_action, 0, strlen('http')) == 'http') {
							$hashttp = 2;
						} else {
							$hashttp = 0;
						}

						switch($rel+$hashttp) {
							case 0:
								//add a / in front of form_action
								if (substr($form_action, 0, 1) != '/') {
									$form_action = '/' . $form_action;
								}
								// we need to correct various situations like
								// relative url from basedir, relative url from post dir etc
								$tmpurl   = static::parseUrl($this->options['post_url']);
								$pathinfo1  = pathinfo($form_action);
								$pathinfo = pathinfo($tmpurl[6]);
								//$this->status['debug'][] = 'post_url   : ' . print_r($this->options['post_url'], true);
								//$this->status['debug'][] = 'tmpurl     : ' . print_r($tmpurl, true);
								//$this->status['debug'][] = 'form_action: ' . print_r($form_action, true);
								//$this->status['debug'][] = 'pathinfo1  : ' . print_r($pathinfo1, true);
								//$this->status['debug'][] = 'pathinfo   : ' . print_r($pathinfo, true);
								if ($pathinfo['dirname'] == $pathinfo1['dirname']) {
									$pathinfo['dirname'] = '';
								} //prevent double directory

								// replace windows DIRECTORY_SEPARATOR bt unix DIRECTORY_SEPARATOR
								$pathinfo['dirname'] = str_replace("\\", '/', $pathinfo['dirname']);
								// get rid of the trailing /  in dir
								rtrim($pathinfo['dirname'], '/');
								$port = !empty($tmpurl[5]) ? ':' . $tmpurl[5] : '';
								$form_action = $ssl_string . $tmpurl[4] . $port . $pathinfo['dirname'] . $form_action;
								//$this->status['debug'][] = 'form_action_final: ' . print_r($form_action, true);
								break;
							case 1:
								//add a / in front of form_action
								if (substr($form_action, 0, 1) != '/') {
									$form_action = '/' . $form_action;
								}
								$this->options['post_url'] = rtrim($this->options['post_url'], '/');
								$form_action = $this->options['post_url'] . $form_action;
								break;
							case 2:
								//do nothing at all
								break;
							case 3:
								// reserved, maybe something pops up, then we use this
								break;
						}

						$input_username_name = '';
						$input_password_name = '';
						if (empty($this->options['logout'])) {
							for ($i = 0; $i <= $elements_count-1; $i++) {
								if ($this->options['input_username_id']) {
									if (strtolower($elements_keys[$i]) == strtolower($this->options['input_username_id'])) {
										$input_username_name = $elements_keys[$i];
										break;
									}
								}
								if ($input_username_name == '') {
									if (strpos(strtolower($elements_keys[$i]), 'user') !== false) {
										$input_username_name = $elements_keys[$i];
									}
									if (strpos(strtolower($elements_keys[$i]), 'name') !== false) {
										$input_username_name = $elements_keys[$i];
									}
								}
							}


							if ($input_username_name == '') {
								$this->status['error'][] = static::_('CURL_NO_NAMEFIELD');
								return $this->status;
							}

							for ($i = 0; $i <= $elements_count-1; $i++) {
								if ($this->options['input_password_id']) {
									if (strtolower($elements_keys[$i]) == strtolower($this->options['input_password_id'])) {
										$input_password_name = $elements_keys[$i];
										break;
									}
								}
								if (strpos(strtolower($elements_keys[$i]), 'pass') !== false) {
									$input_password_name = $elements_keys[$i];
								}
							}

							if ($input_password_name == '') {
								$this->status['error'][] = static::_('CURL_NO_PASSWORDFIELD');
								return $this->status;
							}
							$this->status['debug'][] = static::_('CURL_VALID_USERNAME');
						}
						// we now set the submit parameters. These are:
						// all form_elements name=value combinations with value != '' and type hidden
						$strParameters = '';
						if ($this->options['hidden']) {
							for ($i = 0; $i <= $elements_count-1; $i++) {
								if (($elements_values[$i] ['value'] != '') && ($elements_values[$i]['type'] == 'hidden')) {
									$strParameters .= '&' . $elements_keys[$i] . '=' . urlencode($elements_values[$i]['value']);
								}
							}
						}

						// code for buttons submitted by Daniel Baur
						if ($this->options['buttons']) {
							if (isset($result[$myfrm] ['buttons'][0]['type'])) {
								if ($result[$myfrm] ['buttons'][0]['type'] == 'submit') {
									if ($result[$myfrm]['buttons'][0]['name']) {
										$strParameters .= '&' . $result[$myfrm]['buttons'][0]['name'] . '=' . urlencode($result[$myfrm]['buttons'][0]['value']);
									} else {
										$strParameters .= '&' . 'submit=' . urlencode($result[$myfrm]['buttons'][0]['value']);
									}
								}
							}
						}

						// extra post parameter to avoid endless loop when more then one jFusion is installed
						if (isset($this->options['jnodeid'])) {
							$strParameters .= '&jnodeid=' . urlencode($this->options['jnodeid']);
						}

						// extra post parameter to signal a host calling
						if (isset($this->options['jhost'])) {
							$strParameters .= '&jhost=true';
						}

						if (empty($this->options['logout'])) {
							$post_params = $input_username_name . '=' . urlencode($this->options['username']) . '&' . $input_password_name . '=' . urlencode($this->options['password']);
							$post_params_debug = $input_username_name . '=' . urlencode($this->options['username']) . '&' . $input_password_name . '=xxxxxx';
							$this->status['debug'][] = static::_('CURL_STARTING_LOGIN') . ' ' . $form_action . ' parameters= ' . $post_params_debug . $strParameters;
						} else {
							$post_params = '';
							$this->status['debug'][] = static::_('CURL_STARTING_LOGOUT') . ' ' . $form_action . ' parameters= ' . $strParameters;
						}

						// finally submit the login/logout form:
						if ($this->options['integrationtype'] == 1) {
							$this->ch = curl_init();
							$ip = $_SERVER['REMOTE_ADDR'];
							curl_setopt($this->ch, CURLOPT_HTTPHEADER, array('REMOTE_ADDR: ' . $ip, 'X_FORWARDED_FOR: ' . $ip));
							curl_setopt($this->ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
							curl_setopt($this->ch, CURLOPT_REFERER, '');
							curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, 0);
							curl_setopt($this->ch, CURLOPT_SSL_VERIFYHOST, $this->options['verifyhost']);
							curl_setopt($this->ch, CURLOPT_FAILONERROR, 1);
							curl_setopt($this->ch, CURLOPT_HEADERFUNCTION, array($this, 'readHeader'));
							if (empty($this->options['brute_force'])) {
								curl_setopt($this->ch, CURLOPT_COOKIE, $this->buildCookie());
							}
							curl_setopt($this->ch, CURLOPT_VERBOSE, $this->options['debug']); // Display communication with server
						}
						curl_setopt($this->ch, CURLOPT_FOLLOWLOCATION, 0);
						curl_setopt($this->ch, CURLOPT_URL, $form_action);
						curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, 1);
						curl_setopt($this->ch, CURLOPT_POST, 1);
						curl_setopt($this->ch, CURLOPT_POSTFIELDS, $post_params . $strParameters);
						if (!empty($this->options['httpauth'])) {
							curl_setopt($this->ch, CURLOPT_USERPWD, $this->options['httpauth_username'] . ':' . $this->options['httpauth_password']);
							curl_setopt($this->ch, CURLOPT_HTTPAUTH, $this->options['httpauth']);
						}

						$remotedata = curl_exec($this->ch);
						if ($this->options['debug']) {
							$this->status['cURL']['data'][] = $remotedata;
							$this->status['debug'][] = 'CURL_INFO: ' . print_r(curl_getinfo($this->ch), true);
						}
						if (curl_error($this->ch)) {
							$this->status['error'][] = static::_('CURL_ERROR_MSG') . ': ' . curl_error($this->ch);
						} else {
							//we have to set the cookies now

							if (empty($this->options['logout'])) {
								$this->status['debug'][] = static::_('CURL_LOGIN_FINISHED');
								$this->setCookies($this->options['cookiedomain'], $this->options['cookiepath'], $this->options['expires'], $this->options['secure'], $this->options['httponly']);
							} else {
								$this->status['debug'][] = static::_('CURL_LOGOUT_FINISHED');
								$this->deleteCookies($this->options['cookiedomain'], $this->options['cookiepath'], $this->options['expires'], $this->options['secure'], $this->options['httponly']);
							}
						}
						curl_close($this->ch);
					}
				}
			}
		}
		return $this->status;
	}
365577
public static function setSession($client_id, array $session)
    {
        if (Context::$client_id === $client_id) {
            $_SESSION = $session;
            Context::$old_session = $_SESSION;
        }
        static::setSocketSession($client_id, Context::sessionEncode($session));
    }
611580
public function connect()
    {
        $sslContext = stream_context_create([
            'ssl' => [
                'allow_self_signed' => true,
                'verify_peer'       => true,
                'verify_peer_name'  => false,
                'cafile'            => $this->serverCertificate,
                'local_cert'        => $this->localCertificate,
                'local_pk'          => $this->privateKey,
                'passphrase'        => $this->privateKeyPass,
                'crypto_method'     => STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT
            ]
        ]);

        set_error_handler(function ($err_severity, $err_msg) {
            throw new RuntimeException($err_msg);
        });

        $this->_connection = stream_socket_client("tls://{$this->host}:{$this->port}",
            $errno,
            $errstr,
            30,
            STREAM_CLIENT_CONNECT,
            $sslContext
        );
        restore_error_handler();

        if ( ! $this->_connection) {
            throw new RuntimeException('Could not connect to host: '
                . $this->host
                . ', port:' . $this->port
                . "(Error $errno: $errstr)");
        }

        stream_set_blocking($this->_connection, true);
    }
683115
public function start()
    {
        if ($this->isSessionStarted()) {
            return;
        }

        $myConfig = \OxidEsales\Eshop\Core\Registry::getConfig();

        if ($this->isAdmin()) {
            $this->setName("admin_sid");
        } else {
            $this->setName("sid");
        }

        $sid = $this->getSidFromRequest();

        //starting session if only we can
        if ($this->_allowSessionStart()) {
            //creating new sid
            if (!$sid) {
                self::$_blIsNewSession = true;
                $this->initNewSession();
            } else {
                self::$_blIsNewSession = false;
                $this->_setSessionId($sid);
                $this->_sessionStart();
            }

            //special handling for new ZP cluster session, as in that case session_start() regenerates id
            if ($this->_sId != session_id()) {
                $this->_setSessionId(session_id());
            }

            //checking for swapped client
            $blSwapped = $this->_isSwappedClient();
            if (!self::$_blIsNewSession && $blSwapped) {
                $this->initNewSession();

                // passing notification about session problems
                if ($this->_sErrorMsg && $myConfig->getConfigParam('iDebug')) {
                    \OxidEsales\Eshop\Core\Registry::getUtilsView()->addErrorToDisplay(oxNew(\OxidEsales\Eshop\Core\Exception\StandardException::class, $this->_sErrorMsg));
                }
            } elseif (!$blSwapped) {
                // transferring cookies between hosts
                \OxidEsales\Eshop\Core\Registry::getUtilsServer()->loadSessionCookies();
            }
        }
    }