function sec_session_start() { $session_name = 'exatest_session_id'; //Asignamos un nombre de sesión $secure = false; //mejor en config.php Lo ideal sería true para trabajar con https $httponly = true; // Obliga a la sesión a utilizar solo cookies. // Habilitar este ajuste previene ataques que impican pasar el id de sesión en la URL. if (ini_set('session.use_only_cookies', 1) === FALSE) { $action = "error"; $error = "No puedo iniciar una sesion segura (ini_set)"; } // Obtener los parámetros de la cookie de sesión $cookieParams = session_get_cookie_params(); session_set_cookie_params($cookieParams["lifetime"], $cookieParams["path"], $cookieParams["domain"], $secure, $httponly); //Marca la cookie como accesible sólo a través del protocolo HTTP. //Esto siginifica que la cookie no será accesible por lenguajes de script, // tales como JavaScript. //Este ajuste puede ayudar de manera efectiva a reducir robos de //indentidad a través de ataques // Incia la sesión PHP session_name($session_name); session_start(); // Actualiza el id de sesión actual con uno generado más reciente //Ayuda a evitar ataques de fijación de sesión session_regenerate_id(true); }
function xoonips_session_regenerate() { $old_sessid = session_id(); session_regenerate_id(); $new_sessid = session_id(); session_id($old_sessid); session_destroy(); $old_session = $_SESSION; session_id($new_sessid); $sess_handler =& xoops_gethandler('session'); session_set_save_handler(array(&$sess_handler, 'open'), array(&$sess_handler, 'close'), array(&$sess_handler, 'read'), array(&$sess_handler, 'write'), array(&$sess_handler, 'destroy'), array(&$sess_handler, 'gc')); session_start(); $_SESSION = array(); foreach (array_keys($old_session) as $key) { $_SESSION[$key] = $old_session[$key]; } // write and close session for xnp_is_valid_session_id() session_write_close(); // restart session session_set_save_handler(array(&$sess_handler, 'open'), array(&$sess_handler, 'close'), array(&$sess_handler, 'read'), array(&$sess_handler, 'write'), array(&$sess_handler, 'destroy'), array(&$sess_handler, 'gc')); session_start(); $_SESSION = array(); foreach (array_keys($old_session) as $key) { $_SESSION[$key] = $old_session[$key]; } }
public function checkLogin() { session_start(); if (isset($_SESSION['LAST_ACTIVITY']) && time() - $_SESSION['LAST_ACTIVITY'] > 1800) { // last request was more than 30 minutes ago session_unset(); // unset $_SESSION variable for the run-time session_destroy(); // destroy session data in storage session_write_close(); setcookie(session_name(), '', 0, '/'); session_regenerate_id(true); } $_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp $input = Request::only('username', 'password'); // param was set in the query string if (!empty($input['username']) && !is_null($input['username'])) { // query string had param set to nothing ie ?param=¶m2=something $_SESSION['username'] = $input['username']; $_SESSION['password'] = $input['password']; } if (!empty($_SESSION['username']) && !is_null($_SESSION['password'])) { $count = Admin::where('username', $_SESSION['username'])->where('password', md5(md5($_SESSION['password'])))->count(); if ($count) { return true; } } session_unset(); session_destroy(); session_write_close(); setcookie(session_name(), '', 0, '/'); session_regenerate_id(true); return false; }
/** * セッションIDを再生成する * * @param boolean $destroy trueの場合は古いセッションを破棄する */ public function regenerate($destroy = true) { if (!self::$sessionIdRegenerated) { session_regenerate_id($destroy); self::$sessionIdRegenerated = true; } }
public function Authenticate(\model\User $user) { if ($this->users->GetUserLoginsForHour($user) > self::$MAX_LOGINS_PER_HOUR) { throw new \Exception("Max login attempts for username '" . $user->GetUserName() . "' reached. Please try again in 30-60 minutes."); } // Assert that the password is in plain text. assert($user->IsPasswordHashed() == false); // Log this login attempt in DAL $this->users->AddLoginAttempt($user); // Get user from database, if user exists $userFromDB = $this->users->GetUserByUsername($user->GetUserName()); if ($userFromDB) { // Verify password in user object against password in db table row. if (password_verify($user->GetPassword(), $userFromDB->GetPassword())) { // Hash password in user object. Does no need to be in clear text anymore. $user->HashPassword(); // Add id from DBuser to user $user->SetUserId($userFromDB->GetUserId()); // Regenerate session session_regenerate_id(true); // Return user from DB return $user; } } return false; }
public function tryLogin($data) { // Reject requests if ($this->isExceedingRateLimit(2)) { $this->response->setStatusCode(429, 'Too many requests'); $this->flash->notice('Too many requests.'); return false; } /** @var User $user */ $user = User::findFirst(['email = :email:', 'bind' => ['email' => $data['user']]]); // Sleep for 1-500ms usleep(mt_rand(1000, 500000)); if ($user && $user->validatePassword($data['password'])) { // Validate TOTP token // This needs to be done at this stage as the two factor auth key is // encrypted with the user's password. if ($otpKey = $user->getOtpKey($data['password'])) { $otp = new \Rych\OTP\TOTP($otpKey); if (!$otp->validate($data['token'])) { $this->flash->error('Incorrect login details'); return false; } } $keyService = new \Stecman\Passnote\AccountKeyService(); $keyService->unlockAccountKeyForSession($user, $data['password']); $this->session->set(Security::SESSION_USER_ID, $user->id); $this->session->set(Security::SESSION_KEY, $user->getSessionKey()); session_regenerate_id(); $this->response->redirect(''); } else { // Keep timing $this->security->hash(openssl_random_pseudo_bytes(12)); $this->flash->error('Incorrect login details'); } }
/** * Reset session */ public function reset() { // Clear session vars session_unset(); // Create new session id session_regenerate_id(false); }
function sec_session_start() { session_start(); // Start the php session session_regenerate_id(true); // regenerated the session, delete the old one }
/** * Open a session * * @access public * @param string $base_path Cookie path */ public function open($base_path = '/') { // HttpOnly and secure flags for session cookie session_set_cookie_params(SESSION_DURATION, $base_path ?: '/', null, Request::isHTTPS(), true); // Avoid session id in the URL ini_set('session.use_only_cookies', '1'); // Enable strict mode if (version_compare(PHP_VERSION, '7.0.0') < 0) { ini_set('session.use_strict_mode', '1'); } // Ensure session ID integrity ini_set('session.entropy_file', '/dev/urandom'); ini_set('session.entropy_length', '32'); ini_set('session.hash_bits_per_character', 6); // If the session was autostarted with session.auto_start = 1 in php.ini destroy it if (isset($_SESSION)) { session_destroy(); } // Custom session name session_name('__S'); // Start the session session_start(); // Regenerate the session id to avoid session fixation issue if (empty($_SESSION['__validated'])) { session_regenerate_id(true); $_SESSION['__validated'] = 1; } }
public function loggedOutProtect() { if ($this->loggedIn() === false) { header('Location: ' . BASE_URL . 'login'); exit; } // source: http://stackoverflow.com/a/1270960/2790481 // last request was more than 1 day ago if (isset($_SESSION['LAST_ACTIVITY']) && time() - $_SESSION['LAST_ACTIVITY'] > 86400) { session_unset(); // unset $_SESSION variable for the run-time session_destroy(); // destroy session data in storage header('Location: ' . BASE_URL . 'login'); exit; } $_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp if (!isset($_SESSION['CREATED'])) { $_SESSION['CREATED'] = time(); } else { if (time() - $_SESSION['CREATED'] > 3600) { // session started more than 1 hour ago $id = $_SESSION['id']; // better security - avoid fixation attack. session_regenerate_id(true); // change session ID for the current session and invalidate old session ID $_SESSION['CREATED'] = time(); // update creation time $_SESSION['id'] = $id; $_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp } } }
function sec_session_start() { $session_name = 'sec_session_id'; // Set a custom session name $secure = false; // Set to true if using https. $httponly = true; // This stops javascript being able to access the session id. ini_set('session.use_only_cookies', 1); // Forces sessions to only use cookies. $cookieParams = session_get_cookie_params(); // Gets current cookies params. session_set_cookie_params($cookieParams["lifetime"], $cookieParams["path"], $cookieParams["domain"], $secure, $httponly); session_name($session_name); // Sets the session name to the one set above. session_start(); // Start the php session session_regenerate_id(false); // regenerated the session, delete the old one. $inactive = 600; // check to see if $_SESSION['timeout'] is set if (isset($_SESSION['timeout'])) { $session_life = time() - $_SESSION['timeout']; if ($session_life > $inactive) { echo "<script language=javascript>\n\t\talert('Sesi Telah Habis');</script>"; echo '<script type=text/javascript> window.location = "logout.php"; </script>'; } } $_SESSION['timeout'] = time(); }
function checkLogin($mysqli) { $email = trim(htmlentities($_POST['email'], ENT_QUOTES, "UTF-8")); $email = $mysqli->real_escape_string($email); $emailExist = $mysqli->query("SELECT id, password FROM users WHERE email = '{$email}' "); if ($emailExist->num_rows == 1) { $userArray = $emailExist->fetch_array(); $userId = $userArray['id']; $password = $userArray['password']; } if ($emailExist->num_rows == 0 || md5($_POST['password']) != $password) { return false; } /* Neue Session erstellen */ session_regenerate_id(); $sessionId = session_id(); $_SESSION['userId'] = $userId; $_SESSION['sessionId'] = $sessionId; $time = time(); $date = date('Y-m-d H:i:s'); /* Gucken ob noch alte Session */ $deleteOldSession = $mysqli->query("DELETE FROM sessions WHERE userId = '{$userId}' "); $write = $mysqli->query("INSERT INTO sessions VALUES ('{$userId}', '{$sessionId}', '{$time}')"); $update = $mysqli->query("UPDATE users SET lastLogin = '******' WHERE id = '{$userId}' "); return true; }
function forum_session_start() { static $forum_session_started = FALSE; $return = ($hook = get_hook('fn_forum_session_start_start')) ? eval($hook) : null; if ($return != null) { return; } // Check if session already started if ($forum_session_started && session_id()) { return; } session_cache_limiter(FALSE); // Check session id $forum_session_id = NULL; if (isset($_COOKIE['PHPSESSID'])) { $forum_session_id = $_COOKIE['PHPSESSID']; } else { if (isset($_GET['PHPSESSID'])) { $forum_session_id = $_GET['PHPSESSID']; } } if (empty($forum_session_id) || !preg_match('/^[a-z0-9]{16,32}$/', $forum_session_id)) { // Create new session id $forum_session_id = random_key(32, FALSE, TRUE); session_id($forum_session_id); } session_start(); if (!isset($_SESSION['initiated'])) { session_regenerate_id(); $_SESSION['initiated'] = TRUE; } $forum_session_started = TRUE; }
/** * セッションを開始する * @param string $name * @return $this */ protected function __new__($name = 'sess') { $this->ses_n = $name; if ('' === session_id()) { $session_name = \org\rhaco\Conf::get('session_name', 'SID'); if (!ctype_alpha($session_name)) { throw new \InvalidArgumentException('session name is is not a alpha value'); } session_cache_limiter(\org\rhaco\Conf::get('session_limiter', 'nocache')); session_cache_expire((int) (\org\rhaco\Conf::get('session_expire', 10800) / 60)); session_name(); if (static::has_module('session_read')) { ini_set('session.save_handler', 'user'); session_set_save_handler(array($this, 'open'), array($this, 'close'), array($this, 'read'), array($this, 'write'), array($this, 'destroy'), array($this, 'gc')); if (isset($this->vars[$session_name])) { session_regenerate_id(true); } } session_start(); register_shutdown_function(function () { if ('' != session_id()) { session_write_close(); } }); } }
/** * Regenerates session id */ function regenerate_id() { // copy old session data, including its id $old_session_id = session_id(); $old_session_data = $_SESSION; // regenerate session id and store it session_regenerate_id(); $new_session_id = session_id(); // switch to the old session and destroy its storage session_id($old_session_id); session_destroy(); // switch back to the new session id and send the cookie session_id($new_session_id); session_start(); // restore the old session data into the new session $_SESSION = $old_session_data; // update the session creation time $_SESSION['regenerated'] = time(); // session_write_close() patch based on this thread // http://www.codeigniter.com/forums/viewthread/1624/ // there is a question mark ?? as to side affects // end the current session and store session data. session_write_close(); }
/** * Resets the entire session * * Generates a new session ID and reassigns the current session * to the new ID, then wipes out the Cart contents. * * @since 1.0 * * @return boolean **/ function reset () { session_regenerate_id(); $this->session = session_id(); session_write_close(); do_action('ecart_session_reset'); return true; }
/** * writes logged user details into the session file * * @param object: user detals * * @return boolean */ public function login($user) { // if already logged in if ($this->logged_in) { return false; } // if data is not an object if (!is_object($user)) { return false; } // if data is empty if (empty($user->id)) { return false; } // generate a new SID session_regenerate_id(true); // write into the session file $this->user_id = $_SESSION['user_id'] = $user->id; $this->username = $_SESSION['username'] = $user->username; $this->ual = $_SESSION['ual'] = $user->ual; $this->logged_in = true; defined('USER_ID') ? null : define('USER_ID', $this->user_id); //echo $_SESSION['username']; exit; return true; }
function evalLoggedUser($id, $u, $p) { $sql = "SELECT password FROM users WHERE id='{$id}' AND username='******' AND activated='1' LIMIT 1"; $query = mysql_query($sql); $row = mysql_fetch_row($query); $db_pass_pregd = preg_replace('#[^a-z0-9]#i', '', $row[0]); $sql = "SELECT ip FROM users WHERE id='{$id}' AND username='******' AND activated='1' LIMIT 1"; $query = mysql_query($sql) or die(mysql_error()); $numrows = mysql_num_rows($query); if ($numrows > 0 && $p == $db_pass_pregd) { //If wanted to log out because of a session left open without action, could destroy here. See older files for ie $_SESSION['LAST_ACT'] = time(); //Avoid attacks like Session Fixation if (!isset($_SESSION['CREATION'])) { $_SESSION['CREATION'] = time(); } else { if (time() - $_SESSION['CREATION'] > 1800) { // session started more than 30 minutes ago session_regenerate_id(true); // change session ID for the current session an invalidate old session ID $_SESSION['CREATION'] = time(); // update creation time } } //** Don't need to update last_act here anymore. See js/update-status.js **/ //$sql = "UPDATE users SET last_act=now() WHERE id='$id' LIMIT 1"; //$query = mysql_query($sql); return true; } }
function adodb_session_regenerate_id() { $conn =& ADODB_Session::_conn(); if (!$conn) { return false; } $old_id = session_id(); if (function_exists('session_regenerate_id')) { session_regenerate_id(); } else { session_id(md5(uniqid(rand(), true))); $ck = session_get_cookie_params(); setcookie(session_name(), session_id(), false, $ck['path'], $ck['domain'], $ck['secure']); //@session_start(); } $new_id = session_id(); $ok =& $conn->Execute('UPDATE ' . ADODB_Session::table() . ' SET sesskey=' . $conn->qstr($new_id) . ' WHERE sesskey=' . $conn->qstr($old_id)); /* it is possible that the update statement fails due to a collision */ if (!$ok) { session_id($old_id); if (empty($ck)) { $ck = session_get_cookie_params(); } setcookie(session_name(), session_id(), false, $ck['path'], $ck['domain'], $ck['secure']); return false; } return true; }
public function login() { $this->setTemplate('elib:/login.tpl'); if (isset($_POST['login'])) { $n = Model::load('UserItem'); $n->username = $_POST['username']; $n->password = $_POST['password']; // $n->sanitize(); $n->validateLogin(); if (!$n->hasValErrors()) { $user_id = $n->login(); if ($user_id > 0) { session_regenerate_id(); Session::set('user_id', $user_id); $n->id = $user_id; $n->load(); $ua = Model::load('UserAccess', null, false); $this->loginSuccess($n); if (!($n->getAuth($n->id) < $ua->getLevel('admin'))) { $this->redirect('admin'); } else { $this->redirect(''); } } else { $n->addValError('Wrong username/password combination.', 'success'); } } if ($n->hasValErrors() || $user_id < 1) { $this->presenter->assign('errors', $n->getValErrors()); $this->presenter->assign("username", $_POST['username']); $this->presenter->assign("password", $_POST['password']); } } }
public function login($user, $password, $remember = false, $auto = false) { $user = $this->db->filter($user); if (!$auto) { $password = @md5($password); } $user = $this->db->super_query("SELECT * FROM " . $this->db_prefix . "_users WHERE name='{$user}'"); if ($user['user_id'] and $user['password'] and $user['password'] == md5($password)) { if (!$auto) { session_regenerate_id(); if ($remember) { $this->setCookie("pcp_user_id", "", 0); $this->setCookie("pcp_password", "", 0); $this->setCookie("pcp_user_name", "", 0); } else { $this->setCookie("pcp_user_id", $user['user_id'], 365); $this->setCookie("pcp_user_name", $user['name'], 365); $this->setCookie("pcp_password", $password, 365); } $_SESSION['pcp_user_id'] = $user['user_id']; $_SESSION['pcp_user_name'] = $user['name']; $_SESSION['pcp_password'] = $password; } $this->user_logged = true; $this->user_name = $user['name']; return true; } return false; }
function regenerateSession($reload = false) { // This token is used by forms to prevent cross site forgery attempts if (!isset($_SESSION['nonce']) || $reload) { $_SESSION['nonce'] = md5(microtime(true)); } if (!isset($_SESSION['IPaddress']) || $reload) { $_SESSION['IPaddress'] = $_SERVER['REMOTE_ADDR']; } if (!isset($_SESSION['userAgent']) || $reload) { $_SESSION['userAgent'] = $_SERVER['HTTP_USER_AGENT']; } //$_SESSION['user_id'] = $this->user->getId(); // Set current session to expire in 1 minute $_SESSION['OBSOLETE'] = true; $_SESSION['EXPIRES'] = time() + 60; // Create new session without destroying the old one session_regenerate_id(false); // Grab current session ID and close both sessions to allow other scripts to use them $newSession = session_id(); session_write_close(); // Set session ID to the new one, and start it back up again session_id($newSession); session_start(); // Don't want this one to expire unset($_SESSION['OBSOLETE']); unset($_SESSION['EXPIRES']); }
/** * @param bool|true $regenerate */ public function destroy($regenerate = true) { session_destroy(); if ($regenerate === true) { session_regenerate_id(true); } }
public static function logout() { // clear $_SESSION array session_unset(); // delete session data on the server and send the client a new cookie session_regenerate_id(true); }
/** * Regenerate a session Id * * @param bool $deleteOld Specify if the session's data are to be destroyed. Default false * * @return string New session Id */ public function newId($deleteOld = false) { if ($deleteOld) { $_SESSION = array(); } return session_regenerate_id($deleteOld); }
function start_session($session_name, $secure) { // Make sure the session cookie is not accessible via javascript. $httponly = true; // Hash algorithm to use for the session. (use hash_algos() to get a list of available hashes.) $session_hash = 'sha512'; // Check if hash is available if (in_array($session_hash, hash_algos())) { // Set the has function. ini_set('session.hash_function', $session_hash); } // How many bits per character of the hash. // The possible values are '4' (0-9, a-f), '5' (0-9, a-v), and '6' (0-9, a-z, A-Z, "-", ","). ini_set('session.hash_bits_per_character', 5); // Force the session to only use cookies, not URL variables. ini_set('session.use_only_cookies', 1); // Get session cookie parameters $cookieParams = session_get_cookie_params(); // Set the parameters session_set_cookie_params($cookieParams["lifetime"], $cookieParams["path"], $cookieParams["domain"], $secure, $httponly); // Change the session name session_name($session_name); // Now we cat start the session session_start(); // This line regenerates the session and delete the old one. // It also generates a new encryption key in the database. session_regenerate_id(true); }
function __construct() { // REQUIRED IN EXTENDED CLASS TO LOAD DEFAULTS parent::__construct(); session_start(); session_regenerate_id(); }
public function clear() { session_unset(); @session_regenerate_id(true); @session_start(); $this->data = $_SESSION = array(); }
/** Construction. This kills the current session if any started, and restart the given session */ public function __construct($name, $cleanPreviousSession = false) { if (session_id() == "") { // Start a default session and save on the handler session_start(); SessionSwitcher::$sessionArray[] = array('id' => session_id(), 'name' => session_name()); session_write_close(); } // Please note that there is no start here, session might be already started if (session_id() != "") { // There was a previous session if ($cleanPreviousSession) { if (isset($_COOKIE[session_name()])) { setcookie(session_name(), '', time() - 42000, '/'); } session_destroy(); } // Close the session session_write_close(); session_regenerate_id(false); $_SESSION = array(); // Need to generate a new session id } session_id(md5(SessionSwitcher::$sessionArray[0]['id'] . $name)); session_name($name); session_start(); }
public function signIn(UserInterface $user, Request $req, Response $res) { // nothing to do if the user ID is already signed in $currentUserId = $req->session(self::SESSION_USER_ID_KEY); $userId = $user->id(); if ($currentUserId == $userId) { return true; } // we are going to kill the current session and start a new one $req->destroySession(); if (session_status() == PHP_SESSION_ACTIVE) { // remove the currently active session, for signed in users if ($currentUserId > 0 && ($sid = session_id())) { // delete any active sessions for this session ID $this->deleteSession($sid); } // regenerate session id to prevent session hijacking session_regenerate_id(true); // hang on to the new session id $sid = session_id(); // close the old and new sessions session_write_close(); // re-open the new session session_id($sid); session_start(); // record the active session, for signed in users if ($userId > 0) { // create an active session for this session ID $this->createSession($sid, $userId, $req); } } // set the user id $req->setSession([self::SESSION_USER_ID_KEY => $userId, self::SESSION_USER_AGENT_KEY => $req->agent()]); return true; }