Search code examples
phpsessionsession-hijacking

PHP sessions set on another server


I am trying to understand sessions in php. As far as I understand in a basic login system the sessions work like this: On a page exampledomain.com/login.php:

if (password_verify($_POST['user_password'], $result->password_hash)) {
  //write user data into PHP SESSION
  $_SESSION['user_name'] = $_POST['user_name'];
}

Then on the pages that only logged in users can view I check:

if (isset($_SESSION['user_name'])) {
  //do something
}

Now what I don't understand is what if a hacker on his own servers (hackerdomain.com) does something like this assuming he knows a username:

session_start();
$_SESSION['user_name'] = 'Test';

<form method="post" action="exampledomain.com/page-only-logged-in-users-can-view.php" name="loginform">
 <input type="submit"  name="login" value="Login" />
</form>

Now he set a value in $_SESSION['user_name'] so he will be logged in wihtout even needing a password. I got very confused about this session thing. I read php documentation but I still don't get it.


Solution

  • A session in the end is a cookie that a server send to the browser. This cookie is special and has some properties like:

    • Name. For example, in php by default, PHPSESSID
    • Value. For a session id, a random string identifying the cookie on the server (this cookie has associated data like user name, email, etc)
    • Domain: Defines domain scope of the cookies, where the cookie will be send by browser (eg: a non value means just the main domain server generating the cookie without subdomains. A domain value includes subdomains by default)
    • Path: Path indicates a URL path that must exist in the requested URL in order to send the Cookie header
    • Expires / Max-Age: Expires the cookie at certain time (eg: 2018-08-03T17:30:56.146Z)
    • httpOnly: boolean value, if true then cookie can't be accessed by javascript (document.cookie) to prevent XSS attacks
    • Secure: boolean value, if true cookie must be sent under https
    • Same site: SameSite cookies let servers require that a cookie shouldn't be sent with cross-site requests, which somewhat protects against cross-site request forgery attacks (CSRF). SameSite cookies are still experimental and not yet supported by all browsers.

    More info at https://developer.mozilla.org/es/docs/Web/HTTP/Cookies